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 require-account-login policy in desktop auth (#5382)
Ezra Elletteba00fdc22b60
diff --git a/apps/screenpipe-app-tauri/app/onboarding/page.tsx b/apps/screenpipe-app-tauri/app/onboarding/page.tsxindex b47254d50..3bdc8cb66 100644--- a/apps/screenpipe-app-tauri/app/onboarding/page.tsx+++ b/apps/screenpipe-app-tauri/app/onboarding/page.tsx@@ -123,6 +123,7 @@ export default function OnboardingPage() {isManagedAuthenticated,selectAuthenticationMethod,submitLicenseKey,+ policy: managedPolicy,} = useManagedPolicy();// Restore saved step on mount@@ -323,13 +324,15 @@ export default function OnboardingPage() {handleNextSlide={handleNextSlide}suppressAutoAdvance/>- <button- type="button"- onClick={() => selectAuthenticationMethod("license_key")}- className="mt-3 font-mono text-xs text-muted-foreground/70 underline underline-offset-4 decoration-muted-foreground/40 transition-colors hover:text-foreground hover:decoration-foreground"- >- use enterprise key- </button>+ {!managedPolicy?.requireAccountLogin && (+ <button+ type="button"+ onClick={() => selectAuthenticationMethod("license_key")}+ className="mt-3 font-mono text-xs text-muted-foreground/70 underline underline-offset-4 decoration-muted-foreground/40 transition-colors hover:text-foreground hover:decoration-foreground"+ >+ use enterprise key+ </button>+ )}</div>) : (<div className="flex min-h-[400px] items-center justify-center">diff --git a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsxindex 10c7e76f1..92922e1f7 100644--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx@@ -135,7 +135,12 @@ export function AppEntitlementGate({isManagedAuthenticated,selectAuthenticationMethod,submitLicenseKey,+ policy: managedPolicy,} = useManagedPolicy();+ // When the org policy requires account sign-in, the license key can't+ // authenticate — don't offer it. Best-effort: known from the last fetched+ // or cached policy, and always known right after a key was refused.+ const licenseKeyAllowed = !managedPolicy?.requireAccountLogin;const [isRefreshing, setIsRefreshing] = useState(false);const [refreshError, setRefreshError] = useState<string | null>(null);const [devToken, setDevToken] = useState("");@@ -723,14 +728,16 @@ export function AppEntitlementGate({<LogIn className="h-4 w-4" />sign in with enterprise account</Button>- <Button- onClick={() => selectAuthenticationMethod("license_key")}- variant="outline"- className="w-full gap-2"- >- <KeyRound className="h-4 w-4" />- use enterprise key- </Button>+ {licenseKeyAllowed && (+ <Button+ onClick={() => selectAuthenticationMethod("license_key")}+ variant="outline"+ className="w-full gap-2"+ >+ <KeyRound className="h-4 w-4" />+ use enterprise key+ </Button>+ )}</div>{devLoginBlock}</EntitlementShell>@@ -773,14 +780,16 @@ export function AppEntitlementGate({<LogIn className="h-4 w-4" />{signedIn ? "use different account" : "sign in"}</Button>- <Button- onClick={() => selectAuthenticationMethod("license_key")}- variant="outline"- className="w-full gap-2"- >- <KeyRound className="h-4 w-4" />- use enterprise key- </Button>+ {licenseKeyAllowed && (+ <Button+ onClick={() => selectAuthenticationMethod("license_key")}+ variant="outline"+ className="w-full gap-2"+ >+ <KeyRound className="h-4 w-4" />+ use enterprise key+ </Button>+ )}</div>{devLoginBlock}</EntitlementShell>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 5103fa0be..972578b39 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@@ -427,4 +427,101 @@ describe("enterprise policy runtime manual activation", () => {expect(result.current.isEnterpriseAuthenticated).toBe(true);expect(mocks.commands.saveEnterpriseLicenseKey).toHaveBeenCalledWith(KEY);});++ it("refuses key activation when the org requires account sign-in", async () => {+ mockEnterpriseApi({ policy: { requireAccountLogin: true } });+ 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: false,+ error: "your organization requires signing in with your screenpipe account",+ });+ expect(result.current.authenticationState).toBe("account");+ expect(result.current.isEnterpriseAuthenticated).toBe(false);+ expect(mocks.commands.saveEnterpriseLicenseKey).not.toHaveBeenCalled();+ });++ it("does not authenticate a saved key when the org requires account sign-in", async () => {+ mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);+ mockEnterpriseApi({ policy: { requireAccountLogin: true } });++ const { result } = await renderEnterprisePolicy();++ await waitFor(() => expect(result.current.authenticationState).toBe("account"));+ expect(result.current.isEnterpriseAuthenticated).toBe(false);+ expect(result.current.authenticationError).toMatch(/requires signing in/i);+ expect(result.current.policy.requireAccountLogin).toBe(true);+ });++ 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 } });++ const { result } = await renderEnterprisePolicy();++ await waitFor(() => expect(result.current.isEnterpriseAuthenticated).toBe(true));+ const accountPolicyCall = mocks.tauriFetch.mock.calls.find(+ ([url, init]) =>+ String(url).includes("/api/enterprise/policy") &&+ init?.headers?.Authorization === "Bearer account-token" &&+ init?.headers?.["X-License-Key"] === undefined+ );+ expect(accountPolicyCall).toBeDefined();+ });++ it("signs out a key-authenticated device when the policy flips to require account sign-in", async () => {+ vi.useFakeTimers();+ mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);+ mockEnterpriseApi({});++ const { result } = await renderEnterprisePolicy();+ 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 } });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ });++ expect(result.current.authenticationState).toBe("account");+ expect(result.current.isEnterpriseAuthenticated).toBe(false);+ expect(result.current.authenticationError).toMatch(/requires signing in/i);+ });++ it("switches a key-authenticated device to its signed-in account when the policy flips", async () => {+ vi.useFakeTimers();+ mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);+ Object.assign(mocks.settings, { user: { token: "account-token" } });+ mockEnterpriseApi({});++ const { result } = await renderEnterprisePolicy();+ await act(async () => {});+ expect(result.current.isEnterpriseAuthenticated).toBe(true);++ mockEnterpriseApi({ policy: { requireAccountLogin: true } });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ });++ // Seamlessly re-authenticated with the account credential instead of+ // stranding the employee on the sign-in gate.+ expect(result.current.authenticationState).toBe("authenticated");+ const accountPolicyCall = [...mocks.tauriFetch.mock.calls]+ .reverse()+ .find(+ ([url, init]) =>+ String(url).includes("/api/enterprise/policy") &&+ init?.headers?.Authorization === "Bearer account-token" &&+ init?.headers?.["X-License-Key"] === undefined+ );+ expect(accountPolicyCall).toBeDefined();+ });});diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.tsindex 4aa8cdd18..785b19f0e 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts+++ b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts@@ -44,6 +44,9 @@ interface EnterprisePolicy {appUpdatePolicy: EnterpriseAppUpdatePolicy;managedPipes: ManagedPipe[];orgName: string;+ /** Admin requires employees to sign in with their screenpipe account —+ * the enterprise license key alone must not authenticate this device. */+ requireAccountLogin: boolean;}const EMPTY_POLICY: EnterprisePolicy = {@@ -54,8 +57,12 @@ const EMPTY_POLICY: EnterprisePolicy = {appUpdatePolicy: DEFAULT_ENTERPRISE_APP_UPDATE_POLICY,managedPipes: [],orgName: "",+ requireAccountLogin: false,};+const ACCOUNT_LOGIN_REQUIRED_ERROR =+ "your organization requires signing in with your screenpipe account";+// Sections always hidden in enterprise builds (regardless of policy).// "account" is deliberately NOT here: authentication is handled by onboarding// and the global fallback gate, while the account settings section remains@@ -123,6 +130,7 @@ function readE2ePolicyMock(licenseKey: string): E2ePolicyMockResult {appUpdatePolicy: DEFAULT_ENTERPRISE_APP_UPDATE_POLICY,managedPipes: [],orgName: "E2E Enterprise",+ requireAccountLogin: false,...policy,},};@@ -476,6 +484,7 @@ function loadCachedPolicy(): EnterprisePolicy | null {appUpdatePolicy: normalizeEnterpriseAppUpdatePolicy(policy.appUpdatePolicy),managedPipes: Array.isArray(policy.managedPipes) ? policy.managedPipes : [],orgName: typeof policy.orgName === "string" ? policy.orgName : "",+ requireAccountLogin: policy.requireAccountLogin === true,};}} catch {}@@ -521,6 +530,13 @@ export function useEnterprisePolicyRuntime() {useState<EnterpriseAuthenticationState>("checking");const [authenticationError, setAuthenticationError] = useState<string | null>(null);const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ // Refs for the polling handler: it must read the latest account token and+ // re-enter authentication without recreating the interval on every render.+ const accountTokenRef = useRef<string | null>(accountToken);+ accountTokenRef.current = accountToken;+ const authenticateCredentialRef = useRef<+ ((credential: EnterpriseCredential) => Promise<boolean>) | null+ >(null);const fetchPolicy = useCallback(async (credential: EnterpriseCredential,@@ -622,6 +638,7 @@ export function useEnterprisePolicyRuntime() {appUpdatePolicy,managedPipes: data.managedPipes || [],orgName: data.orgName || "",+ requireAccountLogin: data.requireAccountLogin === true,};console.log(@@ -782,6 +799,27 @@ export function useEnterprisePolicyRuntime() {const result = await fetchPolicy(credential);if (result.ok) {setPolicy(result.policy);+ // Remote settings update: the admin flipped the org from+ // license-key-allowed to sign-in-required while this device is+ // authenticated with the key. Drop the key session immediately —+ // fall back to the signed-in screenpipe account when one exists,+ // otherwise gate the app on account sign-in.+ if (credential.type === "license_key" && result.policy.requireAccountLogin) {+ console.warn(+ "[enterprise] organization now requires account sign-in — ending license-key session"+ );+ stopPolling();+ const token = accountTokenRef.current;+ if (token && authenticateCredentialRef.current) {+ const reauthenticated = await authenticateCredentialRef.current({+ type: "account",+ value: token,+ });+ if (reauthenticated) return;+ }+ setAuthenticationState("account");+ setAuthenticationError(ACCOUNT_LOGIN_REQUIRED_ERROR);+ }} else if (result.reason === "invalid_key") {console.warn("[enterprise] saved key is no longer valid, prompting for a new one");stopPolling();@@ -807,6 +845,15 @@ export function useEnterprisePolicyRuntime() {): Promise<boolean> => {const result = await fetchPolicy(credential);if (result.ok) {+ // The key is valid as a device credential, but the org requires every+ // employee to sign in with their screenpipe account. Device policy was+ // already applied by fetchPolicy; only authentication is refused.+ if (credential.type === "license_key" && result.policy.requireAccountLogin) {+ setPolicy(result.policy);+ setAuthenticationState("account");+ setAuthenticationError(ACCOUNT_LOGIN_REQUIRED_ERROR);+ return false;+ }setAuthenticationError(null);setAuthenticationState("authenticated");setPolicy(result.policy);@@ -834,6 +881,7 @@ export function useEnterprisePolicyRuntime() {setAuthenticationError("could not verify enterprise access - check your connection and try again");return false;}, [fetchPolicy, startPolling]);+ authenticateCredentialRef.current = authenticateCredential;/*** Called from the license key prompt dialog. Validates the key against the@@ -855,6 +903,15 @@ export function useEnterprisePolicyRuntime() {};}+ // Org policy forbids key-only activation: route the employee to account+ // sign-in instead of saving the key.+ if (result.policy.requireAccountLogin) {+ setPolicy(result.policy);+ setAuthenticationState("account");+ setAuthenticationError(ACCOUNT_LOGIN_REQUIRED_ERROR);+ return { ok: false, error: ACCOUNT_LOGIN_REQUIRED_ERROR };+ }+const heartbeat = await withTimeout("enterprise heartbeat",sendHeartbeat(credential),