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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat(enterprise): enforce per-seat recording controls
Louis Beaumont80f7076c6890
diff --git a/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-enterprise-policy.test.tsx b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-enterprise-policy.test.tsxindex eda834ac7..4f5b309d8 100644--- a/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-enterprise-policy.test.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-enterprise-policy.test.tsx@@ -126,16 +126,18 @@ function policyResponse(overrides: Record<string, unknown> = {}) {);}-function heartbeatResponse(status = 200) {- return new Response(JSON.stringify(status === 200 ? { ok: true } : { error: "x" }), {- status,- });+function heartbeatResponse(status = 200, code?: string) {+ return new Response(+ JSON.stringify(status === 200 ? { ok: true } : { error: "x", code }),+ { status },+ );}function mockEnterpriseApi(opts: {policyStatus?: number;policy?: Record<string, unknown>;heartbeatStatus?: number;+ heartbeatCode?: string;}) {mocks.tauriFetch.mockImplementation(async (url: string) => {if (url.includes("/api/enterprise/policy")) {@@ -147,7 +149,7 @@ function mockEnterpriseApi(opts: {return policyResponse(opts.policy);}if (url.includes("/api/enterprise/heartbeat")) {- return heartbeatResponse(opts.heartbeatStatus ?? 200);+ return heartbeatResponse(opts.heartbeatStatus ?? 200, opts.heartbeatCode);}throw new Error(`unexpected fetch ${url}`);});@@ -358,6 +360,31 @@ describe("enterprise policy runtime manual activation", () => {);});+ it("keeps an admin-paused seat authenticated while native recording stays revoked", async () => {+ mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);+ mockEnterpriseApi({+ policy: { recordingAllowed: false },+ heartbeatStatus: 403,+ heartbeatCode: "recording_disabled_by_admin",+ });++ const { result } = await renderEnterprisePolicy();++ await waitFor(() => expect(result.current.isEnterpriseAuthenticated).toBe(true));+ expect(result.current.policy.recordingAllowed).toBe(false);+ expect(result.current.authenticationError).toBeNull();+ expect(mocks.commands.setEnterpriseRecordingAuthorized).toHaveBeenCalledWith(+ false,+ null,+ null,+ );+ expect(mocks.commands.setEnterpriseRecordingAuthorized).not.toHaveBeenCalledWith(+ true,+ "license_key",+ KEY,+ );+ });+it("pushes explicit startup enforcement to Rust and applies it live", async () => {mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);Object.assign(mocks.settings, { autoStartEnabled: false });@@ -535,6 +562,30 @@ describe("enterprise policy runtime manual activation", () => {expect(result.current.policy.orgName).toBe("Bungalow");});+ it("saves a valid key for a paused seat without misreporting a seat-limit error", async () => {+ mockEnterpriseApi({+ policy: { recordingAllowed: false },+ heartbeatStatus: 403,+ heartbeatCode: "recording_disabled_by_admin",+ });+ const { result } = await renderEnterprisePolicy();++ let activation!: Awaited<ReturnType<typeof result.current.submitLicenseKey>>;+ await act(async () => {+ activation = await result.current.submitLicenseKey(KEY);+ });++ expect(activation).toEqual({ ok: true });+ expect(mocks.commands.saveEnterpriseLicenseKey).toHaveBeenCalledWith(KEY);+ expect(result.current.isEnterpriseAuthenticated).toBe(true);+ expect(result.current.policy.recordingAllowed).toBe(false);+ expect(mocks.commands.setEnterpriseRecordingAuthorized).not.toHaveBeenCalledWith(+ true,+ "license_key",+ KEY,+ );+ });+it("does not publish authenticated state when the native recording grant fails", async () => {mockEnterpriseApi({});const { result } = await renderEnterprisePolicy();@@ -706,7 +757,9 @@ describe("enterprise policy runtime manual activation", () => {});it("refuses key activation when the org requires account sign-in", async () => {- mockEnterpriseApi({ policy: { requireAccountLogin: true } });+ mockEnterpriseApi({+ policy: { requireAccountLogin: true, recordingAllowed: false },+ });const { result } = await renderEnterprisePolicy();let activation!: Awaited<ReturnType<typeof result.current.submitLicenseKey>>;@@ -725,7 +778,9 @@ describe("enterprise policy runtime manual activation", () => {it("does not authenticate a saved key when the org requires account sign-in", async () => {mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);- mockEnterpriseApi({ policy: { requireAccountLogin: true } });+ mockEnterpriseApi({+ policy: { requireAccountLogin: true, recordingAllowed: false },+ });const { result } = await renderEnterprisePolicy();@@ -738,7 +793,9 @@ describe("enterprise policy runtime manual activation", () => {it("falls back to the signed-in account when the saved key is refused by policy", async () => {mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);Object.assign(mocks.settings, { user: { token: "account-token" } });- mockEnterpriseApi({ policy: { requireAccountLogin: true } });+ mockEnterpriseApi({+ policy: { requireAccountLogin: true, recordingAllowed: false },+ });const { result } = await renderEnterprisePolicy();@@ -750,6 +807,12 @@ describe("enterprise policy runtime manual activation", () => {init?.headers?.["X-License-Key"] === KEY);expect(accountPolicyCall).toBeDefined();+ expect(result.current.policy.recordingAllowed).toBe(false);+ expect(mocks.commands.setEnterpriseRecordingAuthorized).toHaveBeenLastCalledWith(+ false,+ null,+ null,+ );});it("recovers a rotated saved key through the signed-in account", async () => {@@ -807,9 +870,11 @@ describe("enterprise policy runtime manual activation", () => {await act(async () => {});expect(result.current.isEnterpriseAuthenticated).toBe(true);- // Admin flips the org to sign-in-required; the next 5-minute policy poll- // must end the license-key session immediately.- mockEnterpriseApi({ policy: { requireAccountLogin: true } });+ // Account sign-in remains authoritative even if the admin pauses capture+ // in the same policy update.+ mockEnterpriseApi({+ policy: { requireAccountLogin: true, recordingAllowed: false },+ });await act(async () => {await vi.advanceTimersByTimeAsync(5 * 60 * 1000);});@@ -824,6 +889,34 @@ describe("enterprise policy runtime manual activation", () => {);}, 20_000);+ it("revokes recording without signing out when an admin pauses the seat", async () => {+ vi.useFakeTimers();+ mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);+ mockEnterpriseApi({});++ const { result } = await renderEnterprisePolicy();+ await act(async () => {});+ expect(result.current.isEnterpriseAuthenticated).toBe(true);++ mockEnterpriseApi({+ policy: { recordingAllowed: false },+ heartbeatStatus: 403,+ heartbeatCode: "recording_disabled_by_admin",+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ });++ expect(result.current.authenticationState).toBe("authenticated");+ expect(result.current.policy.recordingAllowed).toBe(false);+ expect(result.current.authenticationError).toBeNull();+ expect(mocks.commands.setEnterpriseRecordingAuthorized).toHaveBeenLastCalledWith(+ false,+ null,+ null,+ );+ }, 20_000);+it("bounds the initial policy request with a deadline and a connect timeout", async () => {mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);mockEnterpriseApi({});diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.tsindex 4185e7887..5d24c3178 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts+++ b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts@@ -56,6 +56,9 @@ interface EnterprisePolicy {/** Admin requires employees to sign in with their screenpipe account —* the enterprise license key alone must not authenticate this device. */requireAccountLogin: boolean;+ /** False pauses new capture for this stable seat installation while keeping+ * Enterprise authentication and the rest of the app available. */+ recordingAllowed: boolean;}const EMPTY_POLICY: EnterprisePolicy = {@@ -68,12 +71,14 @@ const EMPTY_POLICY: EnterprisePolicy = {managedSkills: [],orgName: "",requireAccountLogin: false,+ recordingAllowed: true,};const ACCOUNT_LOGIN_REQUIRED_ERROR ="your organization requires signing in with your screenpipe account";const NATIVE_RECORDING_AUTH_ERROR ="enterprise access was verified, but recording could not be enabled - check enrollment, seat availability, and your connection, then try again";+const RECORDING_DISABLED_BY_ADMIN_CODE = "recording_disabled_by_admin";// Sections always hidden in enterprise builds (regardless of policy).// "account" is deliberately NOT here: authentication is handled by onboarding@@ -420,7 +425,12 @@ type HeartbeatResult =| { ok: true }| {ok: false;- reason: "seat_limit" | "invalid_credential" | "expired_key" | "network_error";+ reason:+ | "seat_limit"+ | "invalid_credential"+ | "expired_key"+ | "recording_disabled"+ | "network_error";error?: string;};@@ -510,6 +520,14 @@ async function sendHeartbeat();if (res.status === 403) {+ const body = await res.json().catch(() => ({}));+ if (body?.code === RECORDING_DISABLED_BY_ADMIN_CODE) {+ return {+ ok: false,+ reason: "recording_disabled",+ error: "recording disabled by workspace admin",+ };+ }return { ok: false, reason: "seat_limit", error: "license seat limit reached" };}if (res.status === 401) {@@ -564,6 +582,7 @@ function loadCachedPolicy(): EnterprisePolicy | null {managedSkills: Array.isArray(policy.managedSkills) ? policy.managedSkills : [],orgName: typeof policy.orgName === "string" ? policy.orgName : "",requireAccountLogin: policy.requireAccountLogin === true,+ recordingAllowed: policy.recordingAllowed !== false,};}} catch {}@@ -825,6 +844,7 @@ export function useEnterprisePolicyRuntime() {managedSkills: Array.isArray(data.managedSkills) ? data.managedSkills : [],orgName: data.orgName || "",requireAccountLogin: data.requireAccountLogin === true,+ recordingAllowed: data.recordingAllowed !== false,};console.log(@@ -1052,6 +1072,13 @@ export function useEnterprisePolicyRuntime() {await setNativeRecordingAuthorized(false);setAuthenticationState("account");setAuthenticationError(ACCOUNT_LOGIN_REQUIRED_ERROR);+ return;+ }+ if (!result.policy.recordingAllowed) {+ await setNativeRecordingAuthorized(false);+ setAuthenticationError(null);+ setAuthenticationState("authenticated");+ return;}} else if (result.reason === "invalid_key") {console.warn("[enterprise] saved key is no longer valid, falling back to account auth");@@ -1140,6 +1167,14 @@ export function useEnterprisePolicyRuntime() {setAuthenticationError(ACCOUNT_LOGIN_REQUIRED_ERROR);return { authenticated: false, retryable: false };}+ if (!result.policy.recordingAllowed) {+ await setNativeRecordingAuthorized(false);+ setAuthenticationError(null);+ setAuthenticationState("authenticated");+ setPolicy(result.policy);+ startPolling(credential);+ return { authenticated: true, retryable: false };+ }if (!await setNativeRecordingAuthorized(true, credential)) {setAuthenticationState(credential.type);setAuthenticationError(NATIVE_RECORDING_AUTH_ERROR);@@ -1229,6 +1264,9 @@ export function useEnterprisePolicyRuntime() {reason: "network_error",error: String(e),}));+ const recordingDisabledByAdmin =+ !result.policy.recordingAllowed ||+ (!heartbeat.ok && heartbeat.reason === "recording_disabled");if (!heartbeat.ok && heartbeat.reason === "seat_limit") {await setNativeRecordingAuthorized(false);return {@@ -1263,6 +1301,15 @@ export function useEnterprisePolicyRuntime() {return { ok: false, error: `failed to save: ${e}` };}+ if (recordingDisabledByAdmin) {+ await setNativeRecordingAuthorized(false);+ setAuthenticationError(null);+ setAuthenticationState("authenticated");+ setPolicy({ ...result.policy, recordingAllowed: false });+ startPolling(credential);+ return { ok: true };+ }+// Grant native recording before publishing the authenticated React state.// AppEntitlementGate reacts to that state by calling spawnScreenpipe; the// native guard must already be open when that restart reaches Rust.diff --git a/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rs b/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rsindex bc920d187..c6bdeebd0 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rs@@ -732,6 +732,11 @@ mod imp {}const HIDDEN_UI_POLICY_POLL_INTERVAL: std::time::Duration =std::time::Duration::from_secs(5 * 60);+ const RECORDING_DISABLED_BY_ADMIN_CODE: &str = "recording_disabled_by_admin";++ fn default_recording_allowed() -> bool {+ true+ }#[derive(Deserialize)]struct HiddenUiPolicyResponse {@@ -741,6 +746,8 @@ mod imp {locked_settings: HashMap<String, serde_json::Value>,#[serde(rename = "requireAccountLogin", default)]require_account_login: bool,+ #[serde(rename = "recordingAllowed", default = "default_recording_allowed")]+ recording_allowed: bool,}#[derive(Debug, PartialEq, Eq)]@@ -748,6 +755,7 @@ mod imp {hidden_sections: Vec<String>,enforce_auto_start: bool,require_account_login: bool,+ recording_allowed: bool,}fn locked_setting_enforces_auto_start(value: Option<&serde_json::Value>) -> bool {@@ -769,6 +777,7 @@ mod imp {hidden_sections: self.hidden_sections,enforce_auto_start,require_account_login: self.require_account_login,+ recording_allowed: self.recording_allowed,}}}@@ -835,14 +844,40 @@ mod imp {credentials}- #[derive(Debug)]+ #[derive(Debug, PartialEq, Eq)]enum NativePolicyFetchError {CredentialRejected(String),+ RecordingDisabled,Unavailable(String),}+ #[derive(Deserialize)]+ struct EnterpriseErrorResponse {+ code: Option<String>,+ }++ fn classify_failed_enterprise_response(+ status: reqwest::StatusCode,+ code: Option<&str>,+ context: &str,+ ) -> NativePolicyFetchError {+ if status == reqwest::StatusCode::FORBIDDEN+ && code == Some(RECORDING_DISABLED_BY_ADMIN_CODE)+ {+ return NativePolicyFetchError::RecordingDisabled;+ }++ let error = format!("{context} HTTP {status}");+ if explicitly_rejects_authorization(status) {+ NativePolicyFetchError::CredentialRejected(error)+ } else {+ NativePolicyFetchError::Unavailable(error)+ }+ }+enum NativeAuthorizationResult {Authorized(NativeEnterprisePolicy),+ RecordingDisabled,RequiresAccount,Rejected,Unavailable(String),@@ -862,12 +897,17 @@ mod imp {.await.map_err(|error| NativePolicyFetchError::Unavailable(error.to_string()))?;if !response.status().is_success() {- let error = format!("HTTP {}", response.status());- return Err(if explicitly_rejects_authorization(response.status()) {- NativePolicyFetchError::CredentialRejected(error)- } else {- NativePolicyFetchError::Unavailable(error)- });+ let status = response.status();+ let code = response+ .json::<EnterpriseErrorResponse>()+ .await+ .ok()+ .and_then(|body| body.code);+ return Err(classify_failed_enterprise_response(+ status,+ code.as_deref(),+ "policy",+ ));}response.json::<HiddenUiPolicyResponse>()@@ -901,14 +941,19 @@ mod imp {return Ok(());}- let error = format!("heartbeat HTTP {}", response.status());- Err(if explicitly_rejects_authorization(response.status()) {- // 403 includes seat exhaustion. Policy validity alone must never- // bypass the enrollment limit that the heartbeat enforces.- NativePolicyFetchError::CredentialRejected(error)- } else {- NativePolicyFetchError::Unavailable(error)- })+ let status = response.status();+ let code = response+ .json::<EnterpriseErrorResponse>()+ .await+ .ok()+ .and_then(|body| body.code);+ // Generic 403 still includes seat exhaustion. Policy validity alone+ // must never bypass the enrollment limit that heartbeat enforces.+ Err(classify_failed_enterprise_response(+ status,+ code.as_deref(),+ "heartbeat",+ ))}async fn resolve_native_authorization(@@ -928,6 +973,9 @@ mod imp {for credential in credentials {match fetch_hidden_ui_policy(http, policy_url, device_id, &credential).await {+ Ok(policy) if !policy.recording_allowed => {+ return NativeAuthorizationResult::RecordingDisabled;+ }Ok(policy)if credential_authorizes_policy(credential.kind(),@@ -938,6 +986,9 @@ mod imp {.await{Ok(()) => return NativeAuthorizationResult::Authorized(policy),+ Err(NativePolicyFetchError::RecordingDisabled) => {+ return NativeAuthorizationResult::RecordingDisabled;+ }Err(NativePolicyFetchError::CredentialRejected(error)) => {rejected += 1;warn!(@@ -958,6 +1009,9 @@ mod imp {// account token before revoking the running session.account_required = true;}+ Err(NativePolicyFetchError::RecordingDisabled) => {+ return NativeAuthorizationResult::RecordingDisabled;+ }Err(NativePolicyFetchError::CredentialRejected(error)) => {rejected += 1;warn!(@@ -1030,7 +1084,7 @@ mod imp {if credential_authorizes_policy(credential.kind(),policy.require_account_login,- ) =>+ ) && policy.recording_allowed =>{match send_enrollment_heartbeat(&http, &heartbeat_url, &device_id, &credential).await@@ -1043,6 +1097,10 @@ mod imp {);Ok(())}+ Err(NativePolicyFetchError::RecordingDisabled) => {+ crate::enterprise_policy::update_recording_authorized(false);+ Err(RECORDING_DISABLED_BY_ADMIN_CODE.to_string())+ }Err(NativePolicyFetchError::CredentialRejected(_)) => {crate::enterprise_policy::update_recording_authorized(false);Err("enterprise enrollment was rejected".to_string())@@ -1052,6 +1110,10 @@ mod imp {}}}+ Ok(policy) if !policy.recording_allowed => {+ crate::enterprise_policy::update_recording_authorized(false);+ Err(RECORDING_DISABLED_BY_ADMIN_CODE.to_string())+ }Ok(_) => {crate::enterprise_policy::update_recording_authorized(false);Err("organization requires account sign-in".to_string())@@ -1060,6 +1122,10 @@ mod imp {crate::enterprise_policy::update_recording_authorized(false);Err("enterprise credential was rejected".to_string())}+ Err(NativePolicyFetchError::RecordingDisabled) => {+ crate::enterprise_policy::update_recording_authorized(false);+ Err(RECORDING_DISABLED_BY_ADMIN_CODE.to_string())+ }Err(NativePolicyFetchError::Unavailable(error)) => {Err(format!("enterprise policy is unavailable: {error}"))}@@ -1140,6 +1206,16 @@ mod imp {}}}+ NativeAuthorizationResult::RecordingDisabled => {+ crate::enterprise_policy::update_recording_authorized(false);+ info!("enterprise: recording paused for this device by workspace admin");+ // The frontend policy poll may have revoked the grant+ // first. An explicit admin pause must still stop an+ // already-running recorder, so do not condition this+ // teardown on the current grant bit.+ let state = app.state::<crate::recording::RecordingState>();+ let _ = crate::recording::stop_screenpipe(state, app.clone()).await;+ }NativeAuthorizationResult::RequiresAccount => {let was_authorized = crate::enterprise_policy::recording_authorized();crate::enterprise_policy::update_recording_authorized(false);@@ -1448,10 +1524,11 @@ mod imp {#[cfg(test)]mod device_id_tests {use super::{- choose_device_id, credential_authorizes_policy, enterprise_license_hash,- exact_frame_url, explicitly_rejects_authorization, image_uploads_allowed,- locked_setting_enforces_auto_start, sibling_heartbeat_url,- EnterprisePolicyCredentialKind, HiddenUiPolicyResponse,+ choose_device_id, classify_failed_enterprise_response, credential_authorizes_policy,+ enterprise_license_hash, exact_frame_url, explicitly_rejects_authorization,+ image_uploads_allowed, locked_setting_enforces_auto_start, sibling_heartbeat_url,+ EnterprisePolicyCredentialKind, HiddenUiPolicyResponse, NativePolicyFetchError,+ RECORDING_DISABLED_BY_ADMIN_CODE,};use std::collections::HashMap;@@ -1521,6 +1598,7 @@ mod imp {),]),require_account_login: true,+ recording_allowed: false,};let policy = response.into_native_policy();@@ -1534,6 +1612,19 @@ mod imp {);assert!(policy.enforce_auto_start);assert!(policy.require_account_login);+ assert!(!policy.recording_allowed);+ }++ #[test]+ fn recording_control_defaults_on_for_older_control_planes() {+ let response: HiddenUiPolicyResponse = serde_json::from_value(serde_json::json!({+ "hiddenSections": [],+ "lockedSettings": {},+ "requireAccountLogin": false+ }))+ .unwrap();++ assert!(response.into_native_policy().recording_allowed);}#[test]@@ -1570,6 +1661,26 @@ mod imp {}}+ #[test]+ fn admin_pause_is_distinct_from_seat_and_credential_rejection() {+ assert_eq!(+ classify_failed_enterprise_response(+ reqwest::StatusCode::FORBIDDEN,+ Some(RECORDING_DISABLED_BY_ADMIN_CODE),+ "heartbeat",+ ),+ NativePolicyFetchError::RecordingDisabled,+ );+ assert!(matches!(+ classify_failed_enterprise_response(+ reqwest::StatusCode::FORBIDDEN,+ Some("seat_limit_reached"),+ "heartbeat",+ ),+ NativePolicyFetchError::CredentialRejected(_),+ ));+ }+#[test]fn heartbeat_follows_custom_and_on_prem_policy_origins() {assert_eq!(