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

feat(enterprise): make persistence policy-controlled (#6665)

Ezra Ellette6e3d2a9af8ba
diff --git a/apps/screenpipe-app-tauri/src-tauri/macos/persistence/payload/Library/PrivilegedHelperTools/screenpipe-persistence-supervisor b/apps/screenpipe-app-tauri/src-tauri/macos/persistence/payload/Library/PrivilegedHelperTools/screenpipe-persistence-supervisor
index ad9bc850e..d8487093b 100755
--- a/apps/screenpipe-app-tauri/src-tauri/macos/persistence/payload/Library/PrivilegedHelperTools/screenpipe-persistence-supervisor
+++ b/apps/screenpipe-app-tauri/src-tauri/macos/persistence/payload/Library/PrivilegedHelperTools/screenpipe-persistence-supervisor
@@ -10,9 +10,12 @@ AGENT_PLIST="${SCREENPIPE_PERSISTENCE_AGENT_PLIST:-/Library/LaunchAgents/${LABEL
STATE_DIR="${SCREENPIPE_PERSISTENCE_STATE_DIR:-/Library/Application Support/screenpipe/persistence}"
ENABLED_MARKER="${STATE_DIR}/enabled"
MAINTENANCE_MARKER="${STATE_DIR}/maintenance"
+POLICY_DISABLED_MARKER="${STATE_DIR}/policy-disabled"
LAST_UID_FILE="${STATE_DIR}/active-console-uid"
LAUNCHCTL="${SCREENPIPE_PERSISTENCE_LAUNCHCTL:-/bin/launchctl}"
SLEEP="${SCREENPIPE_PERSISTENCE_SLEEP:-/bin/sleep}"
+POLICY_INTERVAL_SECONDS="${SCREENPIPE_PERSISTENCE_POLICY_INTERVAL_SECONDS:-300}"
+DEFAULT_POLICY_URL="${SCREENPIPE_PERSISTENCE_POLICY_URL:-https://screenpipe.com/api/enterprise/policy}"
console_uid() {
if [ -n "${SCREENPIPE_PERSISTENCE_TEST_CONSOLE_UID:-}" ]; then
@@ -36,6 +39,124 @@ stop_previous_session() {
fi
}
+set_policy_value() {
+ if [ "$1" = "false" ]; then
+ /usr/bin/touch "$POLICY_DISABLED_MARKER"
+ /usr/sbin/chown root:wheel "$POLICY_DISABLED_MARKER" 2>/dev/null || true
+ /bin/chmod 600 "$POLICY_DISABLED_MARKER" 2>/dev/null || true
+ else
+ /bin/rm -f "$POLICY_DISABLED_MARKER"
+ fi
+}
+
+policy_config() {
+ if [ -n "${SCREENPIPE_PERSISTENCE_POLICY_CONFIG:-}" ]; then
+ /usr/bin/printf '%s\n' "$SCREENPIPE_PERSISTENCE_POLICY_CONFIG"
+ return
+ fi
+
+ bundled="/Applications/screenpipe enterprise.app/Contents/Resources/enterprise.json"
+ if [ -r "$bundled" ]; then
+ /usr/bin/printf '%s\n' "$bundled"
+ return
+ fi
+
+ uid="$1"
+ valid_user_uid "$uid" || return
+ username="$(/usr/bin/id -nu "$uid" 2>/dev/null || true)"
+ [ -n "$username" ] || return
+ home="$(/usr/bin/dscl . -read "/Users/${username}" NFSHomeDirectory 2>/dev/null | /usr/bin/awk '{print $2}')"
+ [ -n "$home" ] || return
+ user_config="${home}/.screenpipe/enterprise.json"
+ [ -r "$user_config" ] && /usr/bin/printf '%s\n' "$user_config"
+}
+
+user_home() {
+ if [ -n "${SCREENPIPE_PERSISTENCE_USER_HOME:-}" ]; then
+ /usr/bin/printf '%s\n' "$SCREENPIPE_PERSISTENCE_USER_HOME"
+ return
+ fi
+ uid="$1"
+ valid_user_uid "$uid" || return
+ username="$(/usr/bin/id -nu "$uid" 2>/dev/null || true)"
+ [ -n "$username" ] || return
+ /usr/bin/dscl . -read "/Users/${username}" NFSHomeDirectory 2>/dev/null | /usr/bin/awk '{print $2}'
+}
+
+policy_url() {
+ config="$1"
+ ingest_url="$(/usr/bin/plutil -extract ingest_url raw -o - "$config" 2>/dev/null || true)"
+ case "$ingest_url" in
+ http://*|https://*)
+ scheme="$(/usr/bin/printf '%s\n' "$ingest_url" | /usr/bin/awk -F/ '{print $1}')"
+ host="$(/usr/bin/printf '%s\n' "$ingest_url" | /usr/bin/awk -F/ '{print $3}')"
+ if /usr/bin/printf '%s\n' "$host" | /usr/bin/grep -Eq '^[A-Za-z0-9.-]+(:[0-9]+)?$'; then
+ /usr/bin/printf '%s//%s/api/enterprise/policy\n' "$scheme" "$host"
+ return
+ fi
+ ;;
+ esac
+ /usr/bin/printf '%s\n' "$DEFAULT_POLICY_URL"
+}
+
+safe_header_value() {
+ [ -z "$1" ] && return 0
+ /usr/bin/printf '%s\n' "$1" | /usr/bin/grep -Eq '^[A-Za-z0-9._~+/-]+$'
+}
+
+refresh_policy() (
+ [ ! -e "$MAINTENANCE_MARKER" ] || return
+ if [ "${SCREENPIPE_PERSISTENCE_TEST_POLICY_VALUE+x}" = "x" ]; then
+ set_policy_value "$SCREENPIPE_PERSISTENCE_TEST_POLICY_VALUE"
+ return
+ fi
+
+ uid="$(console_uid)"
+ config="$(policy_config "$uid")"
+ license_key=""
+ if [ -n "$config" ]; then
+ license_key="$(/usr/bin/plutil -extract license_key raw -o - "$config" 2>/dev/null || true)"
+ fi
+ home="$(user_home "$uid")"
+ account_token=""
+ if [ -n "$home" ] && [ -r "${home}/.screenpipe/auth.json" ]; then
+ account_token="$(/usr/bin/plutil -extract token raw -o - "${home}/.screenpipe/auth.json" 2>/dev/null || true)"
+ fi
+ [ -n "$license_key" ] || [ -n "$account_token" ] || return
+ safe_header_value "$license_key" || return
+ safe_header_value "$account_token" || return
+
+ /bin/mkdir -p "$STATE_DIR"
+ response="$(/usr/bin/mktemp "${STATE_DIR}/policy.XXXXXX")" || return
+ cleanup_policy_files() {
+ [ -z "${response:-}" ] || /bin/rm -f "$response"
+ [ -z "${request_config:-}" ] || /bin/rm -f "$request_config"
+ }
+ trap cleanup_policy_files EXIT
+ trap 'cleanup_policy_files; exit 1' HUP INT TERM
+ request_config="$(/usr/bin/mktemp "${STATE_DIR}/request.XXXXXX")" || {
+ return
+ }
+ /bin/chmod 600 "$request_config"
+ if [ -n "$license_key" ]; then
+ /usr/bin/printf 'header = "X-License-Key: %s"\n' "$license_key" >> "$request_config"
+ fi
+ if [ -n "$account_token" ]; then
+ /usr/bin/printf 'header = "Authorization: Bearer %s"\n' "$account_token" >> "$request_config"
+ fi
+ if /usr/bin/curl --config "$request_config" \
+ --silent --show-error --fail --max-time 15 \
+ --output "$response" \
+ "$(policy_url "$config")"; then
+ if [ ! -e "$MAINTENANCE_MARKER" ]; then
+ value="$(/usr/bin/plutil -extract lockedSettings.enforcePersistence raw -o - "$response" 2>/dev/null || true)"
+ set_policy_value "$value"
+ fi
+ fi
+ cleanup_policy_files
+ trap - EXIT HUP INT TERM
+)
+
reconcile_once() {
[ -e "$ENABLED_MARKER" ] || return 0
[ ! -e "$MAINTENANCE_MARKER" ] || return 0
@@ -46,6 +167,15 @@ reconcile_once() {
previous_uid="$(/bin/cat "$LAST_UID_FILE" 2>/dev/null || true)"
fi
+ if [ -e "$POLICY_DISABLED_MARKER" ]; then
+ stop_previous_session "$previous_uid"
+ if [ "$uid" != "$previous_uid" ]; then
+ stop_previous_session "$uid"
+ fi
+ /bin/rm -f "$LAST_UID_FILE"
+ return 0
+ fi
+
if ! valid_user_uid "$uid"; then
stop_previous_session "$previous_uid"
/bin/rm -f "$LAST_UID_FILE"
@@ -75,11 +205,18 @@ reconcile_once() {
}
if [ "${SCREENPIPE_PERSISTENCE_RUN_ONCE:-0}" = "1" ]; then
+ refresh_policy
reconcile_once
exit 0
fi
+last_policy_check=0
while :; do
+ now="$(/bin/date +%s)"
+ if [ $((now - last_policy_check)) -ge "$POLICY_INTERVAL_SECONDS" ]; then
+ refresh_policy &
+ last_policy_check="$now"
+ fi
reconcile_once
"$SLEEP" 10
done
diff --git a/apps/screenpipe-app-tauri/src-tauri/macos/persistence/test-supervisor.sh b/apps/screenpipe-app-tauri/src-tauri/macos/persistence/test-supervisor.sh
index 24c3b2c49..5945e42f0 100755
--- a/apps/screenpipe-app-tauri/src-tauri/macos/persistence/test-supervisor.sh
+++ b/apps/screenpipe-app-tauri/src-tauri/macos/persistence/test-supervisor.sh
@@ -33,14 +33,39 @@ EOF
/bin/chmod 755 "$FAKE_LAUNCHCTL"
run_supervisor() {
+ policy_value="${2-true}"
SCREENPIPE_PERSISTENCE_RUN_ONCE=1 \
SCREENPIPE_PERSISTENCE_TEST_CONSOLE_UID="$1" \
+ SCREENPIPE_PERSISTENCE_TEST_POLICY_VALUE="$policy_value" \
SCREENPIPE_PERSISTENCE_STATE_DIR="$STATE_DIR" \
SCREENPIPE_PERSISTENCE_LAUNCHCTL="$FAKE_LAUNCHCTL" \
SCREENPIPE_PERSISTENCE_TEST_LOG="$LOG" \
"$SUPERVISOR"
}
+run_supervisor_from_policy_file() {
+ SCREENPIPE_PERSISTENCE_RUN_ONCE=1 \
+ SCREENPIPE_PERSISTENCE_TEST_CONSOLE_UID="$1" \
+ SCREENPIPE_PERSISTENCE_STATE_DIR="$STATE_DIR" \
+ SCREENPIPE_PERSISTENCE_LAUNCHCTL="$FAKE_LAUNCHCTL" \
+ SCREENPIPE_PERSISTENCE_TEST_LOG="$LOG" \
+ SCREENPIPE_PERSISTENCE_POLICY_CONFIG="${TMP}/enterprise.json" \
+ SCREENPIPE_PERSISTENCE_POLICY_URL="file://${TMP}/policy.json" \
+ "$SUPERVISOR"
+}
+
+run_supervisor_from_account_policy_file() {
+ SCREENPIPE_PERSISTENCE_RUN_ONCE=1 \
+ SCREENPIPE_PERSISTENCE_TEST_CONSOLE_UID="$1" \
+ SCREENPIPE_PERSISTENCE_STATE_DIR="$STATE_DIR" \
+ SCREENPIPE_PERSISTENCE_LAUNCHCTL="$FAKE_LAUNCHCTL" \
+ SCREENPIPE_PERSISTENCE_TEST_LOG="$LOG" \
+ SCREENPIPE_PERSISTENCE_POLICY_CONFIG="${TMP}/missing-enterprise.json" \
+ SCREENPIPE_PERSISTENCE_POLICY_URL="file://${TMP}/policy.json" \
+ SCREENPIPE_PERSISTENCE_USER_HOME="${TMP}/home" \
+ "$SUPERVISOR"
+}
+
/usr/bin/touch "${STATE_DIR}/enabled"
run_supervisor 501
/usr/bin/grep -q '^enable gui/501/screenpi.pe.enterprise.persistence$' "$LOG"
@@ -54,6 +79,32 @@ run_supervisor 501
[ ! -s "$LOG" ]
/bin/rm -f "${STATE_DIR}/maintenance"
+: > "$LOG"
+run_supervisor 501 false
+/usr/bin/grep -q '^bootout gui/501/screenpi.pe.enterprise.persistence$' "$LOG"
+[ -e "${STATE_DIR}/policy-disabled" ]
+[ ! -e "${STATE_DIR}/active-console-uid" ]
+
+: > "$LOG"
+run_supervisor 501 true
+/usr/bin/grep -q '^bootstrap gui/501 ' "$LOG"
+[ ! -e "${STATE_DIR}/policy-disabled" ]
+
+/usr/bin/printf '{"license_key":"test-key"}\n' > "${TMP}/enterprise.json"
+/usr/bin/printf '{"lockedSettings":{"enforcePersistence":"false"}}\n' > "${TMP}/policy.json"
+: > "$LOG"
+run_supervisor_from_policy_file 501
+/usr/bin/grep -q '^bootout gui/501/screenpi.pe.enterprise.persistence$' "$LOG"
+[ -e "${STATE_DIR}/policy-disabled" ]
+
+/bin/mkdir -p "${TMP}/home/.screenpipe"
+/usr/bin/printf '{"token":"test.account.token"}\n' > "${TMP}/home/.screenpipe/auth.json"
+/usr/bin/printf '{"lockedSettings":{"enforcePersistence":"true"}}\n' > "${TMP}/policy.json"
+: > "$LOG"
+run_supervisor_from_account_policy_file 501
+/usr/bin/grep -q '^bootstrap gui/501 ' "$LOG"
+[ ! -e "${STATE_DIR}/policy-disabled" ]
+
: > "$LOG"
run_supervisor 0
/usr/bin/grep -q '^bootout gui/501/screenpi.pe.enterprise.persistence$' "$LOG"
diff --git a/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/README.md b/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/README.md
index 23ae550a3..44e64b989 100644
--- a/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/README.md
+++ b/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/README.md
@@ -17,6 +17,7 @@ Screenpipe database, perform network requests, or update the application.
- Application and signed supervisor binaries: the Screenpipe directory under
`%ProgramFiles%`.
- Protected opt-in marker: `%ProgramData%\screenpipe\persistence\enabled`.
+- Cached admin opt-out: `%ProgramData%\screenpipe\persistence\policy-disabled`.
- Supervisor log: `%ProgramData%\screenpipe\persistence\supervisor.log`.
- Administrator removal shortcut: **Remove Screenpipe Enterprise Persistence**
in the all-users Start menu.
@@ -26,6 +27,12 @@ Administrators. Standard users receive read and execute access only. The normal
consumer and enterprise installers do not define the persistence build flag,
install this service, or create the marker.
+The service refreshes the Enterprise `enforcePersistence` policy every five
+minutes. An explicit `false` stops supervised relaunches while leaving the
+service alive so a later admin `true` can resume enforcement. Missing policy or
+refresh failures retain the protected package default or the last valid admin
+decision.
+
## Administrator removal
Run **Remove Screenpipe Enterprise Persistence** from the Start menu and approve
diff --git a/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/src/lib.rs b/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/src/lib.rs
index 9ef7b0b33..03a5831a9 100644
--- a/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/src/lib.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/src/lib.rs
@@ -10,6 +10,8 @@ pub const SUPERVISOR_EXE: &str = "screenpipe-persistence-supervisor.exe";
pub const REMOVER_EXE: &str = "remove-screenpipe-persistence.exe";
pub const APP_EXE: &str = "screenpipe-app.exe";
pub const RECHECK_SECONDS: u64 = 5;
+pub const POLICY_REFRESH_SECONDS: u64 = 5 * 60;
+pub const POLICY_DISABLED_FILE: &str = "policy-disabled";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LaunchDecision {
@@ -76,6 +78,18 @@ pub fn log_path(program_data: &Path) -> PathBuf {
state_dir(program_data).join("supervisor.log")
}
+pub fn policy_disabled_path(program_data: &Path) -> PathBuf {
+ state_dir(program_data).join(POLICY_DISABLED_FILE)
+}
+
+pub fn policy_enforcement_from_exit_code(code: Option<i32>) -> Option<bool> {
+ match code {
+ Some(10) => Some(false),
+ Some(11) => Some(true),
+ _ => None,
+ }
+}
+
pub fn path_eq(left: &Path, right: &Path) -> bool {
left.to_string_lossy()
.eq_ignore_ascii_case(&right.to_string_lossy())
@@ -117,6 +131,14 @@ mod tests {
assert_eq!(select_active_session(Some(7), &[]), None);
}
+ #[test]
+ fn policy_refresh_exit_codes_are_explicit_and_fail_closed() {
+ assert_eq!(policy_enforcement_from_exit_code(Some(10)), Some(false));
+ assert_eq!(policy_enforcement_from_exit_code(Some(11)), Some(true));
+ assert_eq!(policy_enforcement_from_exit_code(Some(20)), None);
+ assert_eq!(policy_enforcement_from_exit_code(None), None);
+ }
+
#[test]
fn exact_session_match_suppresses_duplicates() {
assert_eq!(
diff --git a/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/src/platform.rs b/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/src/platform.rs
index 54d837870..7ab482cc2 100644
--- a/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/src/platform.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/windows/persistence-supervisor/src/platform.rs
@@ -10,8 +10,10 @@ use std::io::Write;
use std::mem::size_of;
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
use std::ptr;
use std::sync::mpsc;
+use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use windows::core::{PCWSTR, PWSTR};
@@ -43,9 +45,9 @@ use windows_service::service_dispatcher;
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
use crate::{
- is_path_within, launch_decision, log_path, marker_path, path_eq, select_active_session,
- state_dir, LaunchDecision, APP_EXE, RECHECK_SECONDS, SERVICE_DISPLAY_NAME, SERVICE_NAME,
- SUPERVISOR_EXE,
+ is_path_within, launch_decision, log_path, marker_path, path_eq, policy_disabled_path,
+ policy_enforcement_from_exit_code, select_active_session, state_dir, LaunchDecision, APP_EXE,
+ POLICY_REFRESH_SECONDS, RECHECK_SECONDS, SERVICE_DISPLAY_NAME, SERVICE_NAME, SUPERVISOR_EXE,
};
type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
@@ -57,10 +59,11 @@ const APP_LAUNCH_WAIT_SECONDS: u64 = 20;
define_windows_service!(ffi_service_main, service_main);
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug)]
enum WorkerEvent {
Wake,
Stop,
+ PolicyRefreshed(std::result::Result<bool, String>),
}
struct OwnedHandle(HANDLE);
@@ -100,13 +103,14 @@ fn service_main(_arguments: Vec<OsString>) {
fn run_service() -> Result<()> {
let (event_tx, event_rx) = mpsc::channel();
+ let control_tx = event_tx.clone();
let handler = move |control| match control {
ServiceControl::Stop | ServiceControl::Shutdown => {
- let _ = event_tx.send(WorkerEvent::Stop);
+ let _ = control_tx.send(WorkerEvent::Stop);
ServiceControlHandlerResult::NoError
}
ServiceControl::SessionChange(_) => {
- let _ = event_tx.send(WorkerEvent::Wake);
+ let _ = control_tx.send(WorkerEvent::Wake);
ServiceControlHandlerResult::NoError
}
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
@@ -117,11 +121,43 @@ fn run_service() -> Result<()> {
log_event("info", "service_started", "supervision active");
let app_path = installed_app_path()?;
+ let mut enforce_persistence = cached_policy_enforcement();
+ let mut next_policy_refresh = Instant::now();
+ let mut policy_refresh_in_flight = false;
loop {
- supervise_once(&app_path);
+ if !policy_refresh_in_flight && Instant::now() >= next_policy_refresh {
+ policy_refresh_in_flight = true;
+ next_policy_refresh = Instant::now() + Duration::from_secs(POLICY_REFRESH_SECONDS);
+ let policy_tx = event_tx.clone();
+ let policy_app_path = app_path.clone();
+ thread::spawn(move || {
+ let result = refresh_policy(&policy_app_path).map_err(|error| error.to_string());
+ let _ = policy_tx.send(WorkerEvent::PolicyRefreshed(result));
+ });
+ }
+
+ supervise_once(&app_path, enforce_persistence);
match event_rx.recv_timeout(Duration::from_secs(RECHECK_SECONDS)) {
Ok(WorkerEvent::Stop) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
Ok(WorkerEvent::Wake) | Err(mpsc::RecvTimeoutError::Timeout) => {}
+ Ok(WorkerEvent::PolicyRefreshed(result)) => {
+ policy_refresh_in_flight = false;
+ match result {
+ Ok(enforced) => {
+ if let Err(error) = cache_policy_enforcement(enforced) {
+ log_event("warn", "policy_cache_failed", &error.to_string());
+ } else if enforce_persistence != enforced {
+ enforce_persistence = enforced;
+ log_event(
+ "info",
+ "persistence_policy_changed",
+ if enforced { "enforced" } else { "not_enforced" },
+ );
+ }
+ }
+ Err(error) => log_event("warn", "policy_refresh_failed", &error),
+ }
+ }
}
}
@@ -149,8 +185,8 @@ fn service_status(current_state: ServiceState) -> ServiceStatus {
}
}
-fn supervise_once(app_path: &Path) {
- let enabled = marker_matches_app(app_path);
+fn supervise_once(app_path: &Path, enforce_persistence: bool) {
+ let enabled = enforce_persistence && marker_matches_app(app_path);
let active_session = match active_interactive_session() {
Ok(session) => session,
Err(error) => {
@@ -183,6 +219,149 @@ fn supervise_once(app_path: &Path) {
}
}
+fn cached_policy_enforcement() -> bool {
+ let Some(program_data) = env::var_os("ProgramData") else {
+ return true;
+ };
+ !policy_disabled_path(Path::new(&program_data)).is_file()
+}
+
+fn cache_policy_enforcement(enforced: bool) -> Result<()> {
+ let program_data = env::var_os("ProgramData").ok_or("ProgramData is unavailable")?;
+ let marker = policy_disabled_path(Path::new(&program_data));
+ if enforced {
+ match fs::remove_file(marker) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(error.into()),
+ }
+ } else {
+ fs::write(marker, b"disabled-by-enterprise-policy\n")?;
+ Ok(())
+ }
+}
+
+const POLICY_POWERSHELL: &str = r#"
+$ErrorActionPreference = 'Stop'
+$headers = @{}
+$config = $null
+if (Test-Path -LiteralPath $env:SCREENPIPE_PERSISTENCE_ENTERPRISE_CONFIG) {
+ $config = Get-Content -Raw -LiteralPath $env:SCREENPIPE_PERSISTENCE_ENTERPRISE_CONFIG | ConvertFrom-Json
+ if ($config.license_key) { $headers['X-License-Key'] = [string]$config.license_key }
+}
+if (-not $headers.ContainsKey('X-License-Key')) {
+ $registry = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\screenpipe' -ErrorAction SilentlyContinue
+ if ($registry.EnterpriseLicenseKey) { $headers['X-License-Key'] = [string]$registry.EnterpriseLicenseKey }
+}
+if ($env:SCREENPIPE_PERSISTENCE_USER_PROFILE) {
+ $userConfigPath = Join-Path $env:SCREENPIPE_PERSISTENCE_USER_PROFILE '.screenpipe\enterprise.json'
+ if (Test-Path -LiteralPath $userConfigPath) {
+ $userConfig = Get-Content -Raw -LiteralPath $userConfigPath | ConvertFrom-Json
+ if (-not $config) { $config = $userConfig }
+ if (-not $headers.ContainsKey('X-License-Key') -and $userConfig.license_key) {
+ $headers['X-License-Key'] = [string]$userConfig.license_key
+ }
+ }
+ $authPath = Join-Path $env:SCREENPIPE_PERSISTENCE_USER_PROFILE '.screenpipe\auth.json'
+ if (Test-Path -LiteralPath $authPath) {
+ $auth = Get-Content -Raw -LiteralPath $authPath | ConvertFrom-Json
+ if ($auth.token) { $headers['Authorization'] = 'Bearer ' + [string]$auth.token }
+ }
+}
+if ($headers.Count -eq 0) { exit 20 }
+$policyUrl = $env:SCREENPIPE_PERSISTENCE_DEFAULT_POLICY_URL
+if ($config.ingest_url) {
+ $ingest = [Uri][string]$config.ingest_url
+ if ($ingest.Scheme -eq 'http' -or $ingest.Scheme -eq 'https') {
+ $policyUrl = $ingest.GetLeftPart([UriPartial]::Authority) + '/api/enterprise/policy'
+ }
+}
+$response = Invoke-RestMethod -Method Get -Uri $policyUrl -Headers $headers -TimeoutSec 15
+$value = $response.lockedSettings.enforcePersistence
+if ($value -eq $false -or [string]$value -eq 'false') { exit 10 }
+exit 11
+"#;
+
+fn refresh_policy(app_path: &Path) -> Result<bool> {
+ let config = app_path
+ .parent()
+ .ok_or("installed app path has no parent directory")?
+ .join("enterprise.json");
+ let profile = active_interactive_session()?
+ .and_then(|session_id| user_profile_for_session(session_id).ok().flatten());
+ let mut command = Command::new("powershell.exe");
+ command
+ .args([
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ POLICY_POWERSHELL,
+ ])
+ .env("SCREENPIPE_PERSISTENCE_ENTERPRISE_CONFIG", config)
+ .env(
+ "SCREENPIPE_PERSISTENCE_DEFAULT_POLICY_URL",
+ default_policy_url(),
+ )
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ if let Some(profile) = profile {
+ command.env("SCREENPIPE_PERSISTENCE_USER_PROFILE", profile);
+ }
+ let status = command.status()?;
+ policy_enforcement_from_exit_code(status.code())
+ .ok_or_else(|| format!("policy helper exited with {:?}", status.code()).into())
+}
+
+fn default_policy_url() -> String {
+ if let Ok(url) = env::var("SCREENPIPE_ENTERPRISE_POLICY_URL") {
+ if !url.trim().is_empty() {
+ return url;
+ }
+ }
+ let base = option_env!("NEXT_PUBLIC_SCREENPIPE_WEB_URL")
+ .unwrap_or("https://screenpipe.com")
+ .trim()
+ .trim_end_matches('/');
+ format!("{base}/api/enterprise/policy")
+}
+
+fn user_profile_for_session(session_id: u32) -> Result<Option<PathBuf>> {
+ let mut user_token = HANDLE::default();
+ unsafe { WTSQueryUserToken(session_id, &mut user_token) }?;
+ let user_token = OwnedHandle::new(user_token);
+ let mut environment = ptr::null_mut();
+ unsafe { CreateEnvironmentBlock(&mut environment, user_token.0, false) }?;
+ let profile = environment_value(environment.cast(), "USERPROFILE").map(PathBuf::from);
+ let _ = unsafe { DestroyEnvironmentBlock(environment) };
+ Ok(profile)
+}
+
+fn environment_value(block: *const u16, name: &str) -> Option<OsString> {
+ if block.is_null() {
+ return None;
+ }
+ let mut offset = 0usize;
+ while offset < 1_048_576 {
+ let start = unsafe { block.add(offset) };
+ let mut length = 0usize;
+ while offset + length < 1_048_576 && unsafe { *start.add(length) } != 0 {
+ length += 1;
+ }
+ if length == 0 {
+ return None;
+ }
+ let entry = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(start, length) });
+ if let Some((key, value)) = entry.split_once('=') {
+ if key.eq_ignore_ascii_case(name) {
+ return Some(OsString::from(value));
+ }
+ }
+ offset += length + 1;
+ }
+ None
+}
+
fn marker_matches_app(app_path: &Path) -> bool {
let Ok(program_data) = env::var("ProgramData") else {
return false;
@@ -372,9 +551,14 @@ fn install_persistence() -> Result<()> {
app_path.as_os_str().to_string_lossy().as_bytes(),
)?;
- if let Err(error) =
- create_and_start_service(&supervisor).and_then(|_| wait_for_supervised_app(&app_path))
- {
+ let start_result = create_and_start_service(&supervisor).and_then(|_| {
+ if cached_policy_enforcement() {
+ wait_for_supervised_app(&app_path)
+ } else {
+ Ok(())
+ }
+ });
+ if let Err(error) = start_result {
let _ = fs::remove_file(marker_path(Path::new(&program_data)));
let _ = remove_service();
return Err(error);
@@ -499,6 +683,7 @@ pub fn remove_persistence() -> Result<()> {
if let Some(program_data) = env::var_os("ProgramData") {
let state = state_dir(Path::new(&program_data));
+ let _ = fs::remove_file(policy_disabled_path(Path::new(&program_data)));
let _ = fs::remove_file(log_path(Path::new(&program_data)));
let _ = fs::remove_dir(state);
}