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 enterprise device enrollment flow (#5249)

Louis Beaumonte0ea43e80488
diff --git a/apps/screenpipe-app-tauri/app/onboarding/page.tsx b/apps/screenpipe-app-tauri/app/onboarding/page.tsx
index 4a05fa8cc..b415143ef 100644
--- a/apps/screenpipe-app-tauri/app/onboarding/page.tsx
+++ b/apps/screenpipe-app-tauri/app/onboarding/page.tsx
@@ -4,7 +4,7 @@
"use client";
-import React, { useState, useEffect } from "react";
+import React, { useState, useEffect, useCallback } from "react";
import { useToast } from "@/components/ui/use-toast";
import OnboardingLogin from "@/components/onboarding/login-gate";
import PermissionsStep from "@/components/onboarding/permissions-step";
@@ -12,7 +12,9 @@ import EngineStartup from "@/components/onboarding/engine-startup";
import ConnectApps from "@/components/onboarding/connect-apps";
import PickPipe from "@/components/onboarding/pick-pipe";
import { useOnboarding } from "@/lib/hooks/use-onboarding";
-import { useIsEnterpriseBuild } from "@/lib/hooks/use-is-enterprise-build";
+import { useEnterpriseBuildStatus } from "@/lib/hooks/use-is-enterprise-build";
+import { useEnterprisePolicy } from "@/lib/hooks/use-enterprise-policy";
+import { EnterpriseLicensePrompt } from "@/components/enterprise-license-prompt";
import posthog from "posthog-js";
import { commands } from "@/lib/utils/tauri";
@@ -42,14 +44,13 @@ export default function OnboardingPage() {
const [isVisible, setIsVisible] = useState(true);
const [isTransitioning, setIsTransitioning] = useState(false);
const { onboardingData, isLoading } = useOnboarding();
- const isEnterprise = useIsEnterpriseBuild();
-
- // Enterprise builds skip the login slide
- useEffect(() => {
- if (isEnterprise && currentSlide === "login") {
- setCurrentSlide("permissions");
- }
- }, [isEnterprise, currentSlide]);
+ const enterpriseBuild = useEnterpriseBuildStatus();
+ const {
+ licenseStatus,
+ policy: enterprisePolicy,
+ requestOrganizationKey,
+ submitLicenseKey,
+ } = useEnterprisePolicy();
// Restore saved step on mount
useEffect(() => {
@@ -109,7 +110,7 @@ export default function OnboardingPage() {
// nothing needed for error state currently
}, [toast]);
- const handleNextSlide = async () => {
+ const handleNextSlide = useCallback(async () => {
if (isTransitioning) return;
setIsTransitioning(true);
@@ -140,9 +141,33 @@ export default function OnboardingPage() {
setIsVisible(true);
setIsTransitioning(false);
}, 300);
- };
+ }, [currentSlide, isTransitioning]);
- if (isLoading) {
+ // A managed enterprise device has exactly one activation path. A key pushed
+ // by IT advances silently; otherwise the key form owns this first step.
+ // Waiting for the build check prevents a brief consumer sign-in flash.
+ useEffect(() => {
+ if (
+ currentSlide === "login" &&
+ enterpriseBuild.resolved &&
+ enterpriseBuild.isEnterprise &&
+ licenseStatus === "active" &&
+ enterprisePolicy.enrollmentMode === "organization_key" &&
+ !isTransitioning
+ ) {
+ void handleNextSlide();
+ }
+ }, [
+ currentSlide,
+ enterpriseBuild.isEnterprise,
+ enterpriseBuild.resolved,
+ licenseStatus,
+ enterprisePolicy.enrollmentMode,
+ isTransitioning,
+ handleNextSlide,
+ ]);
+
+ if (isLoading || !enterpriseBuild.resolved) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<div className="w-6 h-6 border border-foreground border-t-transparent rounded-full animate-spin" />
@@ -163,7 +188,33 @@ export default function OnboardingPage() {
}`}
>
{currentSlide === "login" && (
- <OnboardingLogin handleNextSlide={handleNextSlide} />
+ enterpriseBuild.isEnterprise ? (
+ licenseStatus === "required" ? (
+ <EnterpriseLicensePrompt
+ embedded
+ onSubmit={submitLicenseKey}
+ />
+ ) : (licenseStatus === "active" &&
+ enterprisePolicy.enrollmentMode === "member_sign_in") ||
+ licenseStatus === "member_login" ? (
+ <div className="flex flex-col items-center">
+ <OnboardingLogin handleNextSlide={handleNextSlide} />
+ <button
+ type="button"
+ onClick={requestOrganizationKey}
+ 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 organization key
+ </button>
+ </div>
+ ) : (
+ <div className="flex min-h-[400px] items-center justify-center">
+ <div className="h-6 w-6 animate-spin rounded-full border border-foreground border-t-transparent" />
+ </div>
+ )
+ ) : (
+ <OnboardingLogin handleNextSlide={handleNextSlide} />
+ )
)}
{currentSlide === "permissions" && (
<PermissionsStep handleNextSlide={handleNextSlide} />
diff --git a/apps/screenpipe-app-tauri/components/__tests__/enterprise-license-prompt.test.tsx b/apps/screenpipe-app-tauri/components/__tests__/enterprise-license-prompt.test.tsx
index 3519c6627..556308e3f 100644
--- a/apps/screenpipe-app-tauri/components/__tests__/enterprise-license-prompt.test.tsx
+++ b/apps/screenpipe-app-tauri/components/__tests__/enterprise-license-prompt.test.tsx
@@ -45,7 +45,14 @@ describe("EnterpriseLicensePrompt", () => {
it("normalizes lowercase and surrounding spaces before submit", async () => {
const onSubmit = vi.fn(async () => ({ ok: true }));
- render(<EnterpriseLicensePrompt onSubmit={onSubmit} />);
+ const onActivated = vi.fn();
+ render(
+ <EnterpriseLicensePrompt
+ embedded
+ onSubmit={onSubmit}
+ onActivated={onActivated}
+ />,
+ );
fireEvent.change(screen.getByPlaceholderText("ENT-XXXX-XXXX-XXXX-XXXX"), {
target: { value: " ent-gwxx-rnub-lw9f-3ya6 " },
@@ -53,6 +60,8 @@ describe("EnterpriseLicensePrompt", () => {
fireEvent.click(screen.getByRole("button", { name: /activate/i }));
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("ENT-GWXX-RNUB-LW9F-3YA6"));
+ expect(onActivated).toHaveBeenCalledOnce();
+ expect(screen.getByText("no employee account is required for managed devices")).toBeInTheDocument();
});
it("rejects malformed license keys locally", async () => {
diff --git a/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx b/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
index 0e89c85f6..26d02e3b4 100644
--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
@@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => ({
hiddenSections: [] as string[],
needsLicenseKey: false,
orgName: "",
+ enrollmentMode: "member_sign_in" as "organization_key" | "member_sign_in",
},
}));
@@ -55,7 +56,10 @@ vi.mock("@/lib/hooks/use-enterprise-policy", () => ({
isEnterprise: mocks.enterprise.isEnterprise,
isSectionHidden: (sectionId: string) => mocks.enterprise.hiddenSections.includes(sectionId),
needsLicenseKey: mocks.enterprise.needsLicenseKey,
- policy: { orgName: mocks.enterprise.orgName },
+ policy: {
+ orgName: mocks.enterprise.orgName,
+ enrollmentMode: mocks.enterprise.enrollmentMode,
+ },
}),
}));
@@ -107,6 +111,7 @@ describe("AppEntitlementGate", () => {
hiddenSections: [],
needsLicenseKey: false,
orgName: "",
+ enrollmentMode: "member_sign_in",
};
});
@@ -133,6 +138,7 @@ describe("AppEntitlementGate", () => {
hiddenSections: ["referral"],
needsLicenseKey: false,
orgName: "Our Future Foundation",
+ enrollmentMode: "member_sign_in",
};
mocks.state.user = null;
@@ -146,13 +152,13 @@ describe("AppEntitlementGate", () => {
expect(mocks.openLoginWindow).toHaveBeenCalled();
});
- it("does not force enterprise sign-in when the account section is hidden by policy", () => {
- vi.stubEnv("TAURI_ENV_DEBUG", "true");
+ it("lets managed enterprise devices run without an employee account", () => {
mocks.enterprise = {
isEnterprise: true,
hiddenSections: ["account", "referral"],
needsLicenseKey: false,
orgName: "Locked Workspace",
+ enrollmentMode: "organization_key",
};
mocks.state.user = null;
@@ -430,6 +436,7 @@ describe("AppEntitlementGate", () => {
hiddenSections: [],
needsLicenseKey: false,
orgName: "Acme",
+ enrollmentMode: "member_sign_in",
};
mocks.state.user = null; // no token → enterprise-login gate, not entitlement
render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
diff --git a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
index 7888ddd96..f9b052fd5 100644
--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
@@ -166,7 +166,7 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
isEnterprise &&
enterpriseAccountPolicyLoaded &&
!needsLicenseKey &&
- !isSectionHidden("account");
+ enterprisePolicy.enrollmentMode === "member_sign_in";
const shouldGateForEnterpriseLogin = enterpriseRequiresLogin && !user?.token;
const shouldGateForEnterpriseApp =
!devBypass &&
@@ -175,7 +175,10 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
!hasConsumerSubscription &&
enterpriseAccount?.requires_enterprise_app === true;
const shouldGateForEntitlement =
- !devBypass && !isEntitled && !failOpenForTransientAccessLoss;
+ !devBypass &&
+ !isEnterprise &&
+ !isEntitled &&
+ !failOpenForTransientAccessLoss;
const shouldGate =
shouldGateForEnterpriseApp ||
shouldGateForEnterpriseLogin ||
diff --git a/apps/screenpipe-app-tauri/components/enterprise-license-prompt.tsx b/apps/screenpipe-app-tauri/components/enterprise-license-prompt.tsx
index 6b47e2302..b5b47115f 100644
--- a/apps/screenpipe-app-tauri/components/enterprise-license-prompt.tsx
+++ b/apps/screenpipe-app-tauri/components/enterprise-license-prompt.tsx
@@ -9,6 +9,8 @@ import { Loader2 } from "lucide-react";
interface EnterpriseLicensePromptProps {
onSubmit: (key: string) => Promise<{ ok: boolean; error?: string }>;
+ embedded?: boolean;
+ onActivated?: () => void;
}
const LICENSE_KEY_PATTERN = /^ENT-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;
@@ -18,7 +20,11 @@ function normalizeLicenseKey(value: string): string {
return value.trim().toUpperCase();
}
-export function EnterpriseLicensePrompt({ onSubmit }: EnterpriseLicensePromptProps) {
+export function EnterpriseLicensePrompt({
+ onSubmit,
+ embedded = false,
+ onActivated,
+}: EnterpriseLicensePromptProps) {
const [key, setKey] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -39,6 +45,8 @@ export function EnterpriseLicensePrompt({ onSubmit }: EnterpriseLicensePromptPro
const result = await onSubmit(normalized);
if (!result.ok) {
setError(result.error || "failed to validate license key");
+ } else {
+ onActivated?.();
}
} catch (e) {
console.error("[enterprise] license activation failed:", e);
@@ -49,11 +57,17 @@ export function EnterpriseLicensePrompt({ onSubmit }: EnterpriseLicensePromptPro
};
return (
- <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-background/80 px-4 pt-12 pb-6 backdrop-blur-sm">
+ <div
+ className={
+ embedded
+ ? "flex w-full items-center justify-center"
+ : "fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-background/80 px-4 pt-12 pb-6 backdrop-blur-sm"
+ }
+ >
<div className="w-full max-w-sm border border-border bg-background p-6 rounded-lg shadow-lg">
- <h2 className="text-lg font-semibold mb-1">enterprise license</h2>
+ <h2 className="text-lg font-semibold mb-1">activate this device</h2>
<p className="text-sm text-muted-foreground mb-4">
- enter the license key provided by your IT admin to configure this device
+ enter the organization key provided by your IT admin
</p>
<form onSubmit={handleSubmit} className="space-y-3">
@@ -93,7 +107,7 @@ export function EnterpriseLicensePrompt({ onSubmit }: EnterpriseLicensePromptPro
</form>
<p className="text-[11px] text-muted-foreground mt-3">
- contact your admin if you don&apos;t have a license key
+ no employee account is required for managed devices
</p>
</div>
</div>
diff --git a/apps/screenpipe-app-tauri/e2e/specs/zz-enterprise-license-prompt.spec.ts b/apps/screenpipe-app-tauri/e2e/specs/zz-enterprise-license-prompt.spec.ts
index b9c040d3f..d5f60709c 100644
--- a/apps/screenpipe-app-tauri/e2e/specs/zz-enterprise-license-prompt.spec.ts
+++ b/apps/screenpipe-app-tauri/e2e/specs/zz-enterprise-license-prompt.spec.ts
@@ -8,6 +8,12 @@
// - retrying after seats are added must activate without a reload.
import { openHomeWindow, waitForAppReady, t } from '../helpers/test-utils.js';
+import {
+ closeWindow,
+ invokeOrThrow,
+ showWindow,
+ waitForWindowHandle,
+} from '../helpers/tauri.js';
const FORCE_ENTERPRISE_BUILD_KEY = 'screenpipe_e2e_force_enterprise_build';
const POLICY_KEY = 'screenpipe_e2e_enterprise_policy';
@@ -43,6 +49,7 @@ async function configureEnterpriseMocks(heartbeatStatus: number): Promise<void>
managedAiPreset: null,
managedPipes: [],
orgName: 'Bungalow',
+ enrollmentMode: 'organization_key',
syncStreams: {
frames: true,
audio: true,
@@ -67,6 +74,10 @@ async function configureEnterpriseMocks(heartbeatStatus: number): Promise<void>
await browser.pause(t(2500));
await browser.switchToWindow('home').catch(() => {});
+ await invokeOrThrow('reset_onboarding');
+ await showWindow('Onboarding');
+ await waitForWindowHandle('onboarding', t(15000));
+ await browser.switchToWindow('onboarding');
}
async function setHeartbeatStatus(status: number): Promise<void> {
@@ -78,6 +89,7 @@ async function setHeartbeatStatus(status: number): Promise<void> {
}
async function clearEnterpriseMocks(): Promise<void> {
+ await invokeOrThrow('complete_onboarding').catch(() => {});
await browser.execute(
(keys: string[], policyCacheKey: string) => {
for (const key of keys) {
@@ -92,6 +104,7 @@ async function clearEnterpriseMocks(): Promise<void> {
await browser.pause(t(2000));
await browser.switchToWindow('home').catch(() => {});
+ await closeWindow('Onboarding').catch(() => {});
}
async function waitForBodyText(text: string): Promise<void> {
@@ -135,7 +148,7 @@ async function submitLicense(value: string): Promise<void> {
await button.click();
}
-describe('Enterprise license prompt', () => {
+describe('Enterprise onboarding activation', () => {
before(async () => {
await waitForAppReady();
await openHomeWindow();
@@ -147,7 +160,11 @@ describe('Enterprise license prompt', () => {
});
it('handles invalid key, seat-limit, and retry success without sticking on validating', async () => {
- await waitForBodyText('enterprise license');
+ await waitForBodyText('activate this device');
+ const initialText = ((await browser.execute(
+ () => document.body.innerText.toLowerCase(),
+ )) as string);
+ expect(initialText).not.toContain('sign in to activate your plan');
await submitLicense(WRONG_LICENSE);
await waitForBodyText('invalid or expired license key');
@@ -159,10 +176,7 @@ describe('Enterprise license prompt', () => {
await setHeartbeatStatus(200);
await submitLicense(VALID_LICENSE);
- await waitForBodyTextGone('enterprise license');
-
- const homePage = await $('[data-testid="home-page"]');
- await homePage.waitForExist({ timeout: t(15000) });
- expect(await homePage.isExisting()).toBe(true);
+ await waitForBodyTextGone('activate this device');
+ await waitForBodyText('permissions');
});
});
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.tsx
index cf2b0fd33..8606f9381 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
@@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => {
return {
settings,
+ cloudUser: { token: null as string | null },
store,
isEnterprise: { value: true },
commands: {
@@ -54,6 +55,9 @@ vi.mock("@/lib/hooks/use-is-enterprise-build", () => ({
vi.mock("@/lib/hooks/use-settings", () => ({
getStore: vi.fn(async () => mocks.store),
+ useSettings: () => ({
+ settings: { user: mocks.cloudUser.token ? { token: mocks.cloudUser.token } : null },
+ }),
}));
vi.mock("@/lib/utils/tauri", () => ({
@@ -106,13 +110,17 @@ function heartbeatResponse(status = 200) {
function mockEnterpriseApi(opts: {
policyStatus?: number;
+ policyErrorCode?: string;
policy?: Record<string, unknown>;
heartbeatStatus?: number;
}) {
mocks.tauriFetch.mockImplementation(async (url: string) => {
if (url.includes("/api/enterprise/policy")) {
if (opts.policyStatus && opts.policyStatus !== 200) {
- return new Response(JSON.stringify({ error: "bad key" }), { status: opts.policyStatus });
+ return new Response(
+ JSON.stringify({ error: "bad key", code: opts.policyErrorCode }),
+ { status: opts.policyStatus },
+ );
}
return policyResponse(opts.policy);
}
@@ -133,7 +141,9 @@ describe("useEnterprisePolicy manual activation", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
+ window.localStorage?.removeItem("enterprise-policy-cache");
mocks.isEnterprise.value = true;
+ mocks.cloudUser.token = null;
Object.keys(mocks.settings).forEach((k) => delete mocks.settings[k]);
Object.assign(mocks.settings, { deviceId: "device-1" });
mocks.localFetch.mockResolvedValue(
@@ -195,6 +205,7 @@ describe("useEnterprisePolicy manual activation", () => {
expect(activation).toEqual({ ok: true });
expect(mocks.commands.saveEnterpriseLicenseKey).toHaveBeenCalledWith(KEY);
expect(result.current.needsLicenseKey).toBe(false);
+ expect(result.current.licenseStatus).toBe("active");
expect(result.current.policy.orgName).toBe("Bungalow");
});
@@ -230,7 +241,8 @@ describe("useEnterprisePolicy manual activation", () => {
ok: false,
error: "license seat limit reached - contact your admin to add seats",
});
- expect(result.current.needsLicenseKey).toBe(true);
+ expect(result.current.needsLicenseKey).toBe(false);
+ expect(result.current.licenseStatus).toBe("member_login");
expect(mocks.commands.saveEnterpriseLicenseKey).not.toHaveBeenCalled();
expect(mocks.commands.setEnterprisePolicy).not.toHaveBeenCalled();
});
@@ -245,7 +257,7 @@ describe("useEnterprisePolicy manual activation", () => {
});
expect(activation).toEqual({ ok: false, error: "invalid or expired license key" });
- expect(result.current.needsLicenseKey).toBe(true);
+ expect(result.current.needsLicenseKey).toBe(false);
expect(mocks.commands.saveEnterpriseLicenseKey).not.toHaveBeenCalled();
});
@@ -262,4 +274,61 @@ describe("useEnterprisePolicy manual activation", () => {
expect(result.current.needsLicenseKey).toBe(false);
expect(mocks.commands.saveEnterpriseLicenseKey).toHaveBeenCalledWith(KEY);
});
+
+ it("loads member policy with the signed-in session and no organization key", async () => {
+ mocks.cloudUser.token = "member-token";
+ mocks.settings.user = { token: "member-token" };
+ mockEnterpriseApi({ policy: { enrollmentMode: "member_sign_in" } });
+
+ const { result } = await renderEnterprisePolicy();
+
+ expect(result.current.licenseStatus).toBe("active");
+ expect(result.current.policy.enrollmentMode).toBe("member_sign_in");
+ expect(mocks.tauriFetch).toHaveBeenCalledWith(
+ expect.stringContaining("/api/enterprise/policy"),
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: "Bearer member-token" }),
+ }),
+ );
+ const request = mocks.tauriFetch.mock.calls.find(([url]) =>
+ String(url).includes("/api/enterprise/policy"),
+ );
+ expect(request?.[1]?.headers).not.toHaveProperty("X-License-Key");
+ });
+
+ it("honors organization-key mode returned by the workspace policy", async () => {
+ mockEnterpriseApi({ policy: { enrollmentMode: "organization_key" } });
+ const { result } = await renderEnterprisePolicy();
+
+ await act(async () => {
+ await result.current.submitLicenseKey(KEY);
+ });
+
+ expect(result.current.policy.enrollmentMode).toBe("organization_key");
+ expect(result.current.licenseStatus).toBe("active");
+ });
+
+ it("switches a signed-in device to key enrollment when the org requires it", async () => {
+ mocks.cloudUser.token = "member-token";
+ mocks.settings.user = { token: "member-token" };
+ mockEnterpriseApi({
+ policyStatus: 403,
+ policyErrorCode: "organization_key_required",
+ });
+
+ const { result } = await renderEnterprisePolicy();
+
+ expect(result.current.needsLicenseKey).toBe(true);
+ expect(result.current.licenseStatus).toBe("required");
+ });
+
+ it("lets a fresh shared device choose organization-key enrollment", async () => {
+ mockEnterpriseApi({});
+ const { result } = await renderEnterprisePolicy();
+
+ expect(result.current.licenseStatus).toBe("member_login");
+ act(() => result.current.requestOrganizationKey());
+ expect(result.current.needsLicenseKey).toBe(true);
+ expect(result.current.licenseStatus).toBe("required");
+ });
});
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts
index 993c63e9e..1f0b01b03 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts
@@ -6,7 +6,7 @@ import { useState, useEffect, useCallback, useRef } from "react";
import { useIsEnterpriseBuild } from "./use-is-enterprise-build";
import { commands } from "@/lib/utils/tauri";
import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
-import { getStore } from "./use-settings";
+import { getStore, useSettings } from "./use-settings";
import { computeManagedSettingUpdates } from "./managed-settings";
import { getVersion } from "@tauri-apps/api/app";
import { localFetch } from "@/lib/api";
@@ -36,6 +36,7 @@ interface EnterprisePolicy {
appUpdatePolicy: EnterpriseAppUpdatePolicy;
managedPipes: ManagedPipe[];
orgName: string;
+ enrollmentMode: "organization_key" | "member_sign_in";
}
const EMPTY_POLICY: EnterprisePolicy = {
@@ -46,6 +47,7 @@ const EMPTY_POLICY: EnterprisePolicy = {
appUpdatePolicy: DEFAULT_ENTERPRISE_APP_UPDATE_POLICY,
managedPipes: [],
orgName: "",
+ enrollmentMode: "member_sign_in",
};
// Sections always hidden in enterprise builds (regardless of policy).
@@ -445,7 +447,7 @@ function loadCachedPolicy(): EnterprisePolicy | null {
type FetchResult =
| { ok: true; policy: EnterprisePolicy }
- | { ok: false; reason: "invalid_key" | "network_error" };
+ | { ok: false; reason: "invalid_key" | "key_required" | "login_required" | "network_error" };
interface FetchPolicyOptions {
applyLocalPolicy?: boolean;
@@ -467,15 +469,20 @@ interface FetchPolicyOptions {
*/
export function useEnterprisePolicy() {
const isEnterprise = useIsEnterpriseBuild();
+ const { settings } = useSettings();
+ const cloudUserToken = settings.user?.token ?? null;
const [policy, setPolicy] = useState<EnterprisePolicy>(() => {
return loadCachedPolicy() ?? EMPTY_POLICY;
});
const [needsLicenseKey, setNeedsLicenseKey] = useState(false);
+ const [licenseStatus, setLicenseStatus] = useState<
+ "loading" | "required" | "member_login" | "active"
+ >("loading");
const licenseKeyRef = useRef<string | null>(null);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const fetchPolicy = useCallback(async (
- licenseKey: string,
+ licenseKey: string | null,
options: FetchPolicyOptions = {}
): Promise<FetchResult> => {
try {
@@ -511,15 +518,16 @@ export function useEnterprisePolicy() {
}
}
- const headers: Record<string, string> = {
- "X-License-Key": licenseKey,
- "X-Device-Id": deviceId,
- };
+ if (!licenseKey && !cloudToken) {
+ return { ok: false, reason: "login_required" };
+ }
+ const headers: Record<string, string> = { "X-Device-Id": deviceId };
+ if (licenseKey) headers["X-License-Key"] = licenseKey;
if (cloudToken) {
headers["Authorization"] = `Bearer ${cloudToken}`;
}
let data: any;
- const e2ePolicy = readE2ePolicyMock(licenseKey);
+ const e2ePolicy = readE2ePolicyMock(licenseKey ?? "");
if (e2ePolicy.present) {
if (!e2ePolicy.ok) {
return { ok: false, reason: e2ePolicy.reason };
@@ -534,6 +542,12 @@ export function useEnterprisePolicy() {
console.error(`[enterprise] policy fetch: key rejected (${res.status})`);
return { ok: false, reason: "invalid_key" };
}
+ if (res.status === 403) {
+ const error = await res.json().catch(() => null);
+ if (error?.code === "organization_key_required") {
+ return { ok: false, reason: "key_required" };
+ }
+ }
if (!res.ok) {
console.error(`[enterprise] policy fetch failed: ${res.status} ${res.statusText}`);
return { ok: false, reason: "network_error" };
@@ -560,6 +574,13 @@ export function useEnterprisePolicy() {
appUpdatePolicy,
managedPipes: data.managedPipes || [],
orgName: data.orgName || "",
+ enrollmentMode:
+ data.enrollmentMode === "organization_key" ||
+ data.enrollmentMode === "member_sign_in"
+ ? data.enrollmentMode
+ : allHidden.includes("account")
+ ? "organization_key"
+ : "member_sign_in",
};
console.log(
`[enterprise] policy loaded: org=${result.orgName}, hidden=[${result.hiddenSections.join(",")}], locked=[${lockedKeys.join(",")}]`
@@ -600,11 +621,13 @@ export function useEnterprisePolicy() {
}
// Fire-and-forget heartbeat
- sendHeartbeat(licenseKey).then((heartbeat) => {
- if (!heartbeat.ok) {
- console.warn("[enterprise] heartbeat failed:", heartbeat.reason, heartbeat.error);
- }
- });
+ if (licenseKey) {
+ sendHeartbeat(licenseKey).then((heartbeat) => {
+ if (!heartbeat.ok) {
+ console.warn("[enterprise] heartbeat failed:", heartbeat.reason, heartbeat.error);
+ }
+ });
+ }
// Sync managed pipes to local filesystem. Always runs (even with an
// empty list) so pipes removed from the policy get disabled on devices.
@@ -713,39 +736,63 @@ export function useEnterprisePolicy() {
}
}, []);
- const startPolling = useCallback((key: string) => {
+ const startPolling = useCallback((key: string | null) => {
stopPolling();
intervalRef.current = setInterval(async () => {
const result = await fetchPolicy(key);
if (result.ok) {
setPolicy(result.policy);
- } else if (result.reason === "invalid_key") {
- // Key was revoked/expired — stop polling and prompt for new key
- console.warn("[enterprise] saved key is no longer valid, prompting for new one");
+ } else if (result.reason === "invalid_key" || result.reason === "key_required") {
+ // Auth mode changed or the key was revoked — stop polling and show
+ // the enrollment method now required by the workspace.
+ console.warn("[enterprise] enrollment credentials no longer satisfy policy");
stopPolling();
- setNeedsLicenseKey(true);
+ const requiresKey = Boolean(key) || result.reason === "key_required";
+ setNeedsLicenseKey(requiresKey);
+ setLicenseStatus(requiresKey ? "required" : "member_login");
}
// network_error: silently keep polling, use cached policy
}, POLL_INTERVAL_MS);
}, [fetchPolicy, stopPolling]);
+ const initWithMember = useCallback(async () => {
+ licenseKeyRef.current = null;
+ const result = await fetchPolicy(null);
+ if (result.ok) {
+ setNeedsLicenseKey(false);
+ setLicenseStatus("active");
+ setPolicy(result.policy);
+ startPolling(null);
+ return;
+ }
+
+ const requiresKey = result.reason === "key_required";
+ setNeedsLicenseKey(requiresKey);
+ setLicenseStatus(requiresKey ? "required" : "member_login");
+ const cached = loadCachedPolicy();
+ setPolicy(cached ?? EMPTY_POLICY);
+ }, [fetchPolicy, startPolling]);
+
const initWithKey = useCallback(async (key: string) => {
licenseKeyRef.current = key;
const result = await fetchPolicy(key);
if (result.ok) {
setNeedsLicenseKey(false);
+ setLicenseStatus("active");
setPolicy(result.policy);
startPolling(key);
} else if (result.reason === "invalid_key") {
// Saved key is bad — prompt for a new one
console.warn("[enterprise] saved key is invalid, prompting for new one");
setNeedsLicenseKey(true);
+ setLicenseStatus("required");
const cached = loadCachedPolicy();
setPolicy(cached ?? { ...EMPTY_POLICY, hiddenSections: ENTERPRISE_DEFAULT_HIDDEN });
} else {
// Network error — use cached policy, keep trying
setNeedsLicenseKey(false);
+ setLicenseStatus("active");
const cached = loadCachedPolicy();
setPolicy(cached ?? { ...EMPTY_POLICY, hiddenSections: ENTERPRISE_DEFAULT_HIDDEN });
startPolling(key);
@@ -805,6 +852,7 @@ export function useEnterprisePolicy() {
// Apply the policy and start polling
licenseKeyRef.current = key;
setNeedsLicenseKey(false);
+ setLicenseStatus("active");
setPolicy(result.policy);
startPolling(key);
@@ -847,10 +895,15 @@ export function useEnterprisePolicy() {
if (cancelled) return;
if (!key) {
- console.warn("[enterprise] no license key — prompting user to enter one");
- setNeedsLicenseKey(true);
const cached = loadCachedPolicy();
- setPolicy(cached ?? { ...EMPTY_POLICY, hiddenSections: ENTERPRISE_DEFAULT_HIDDEN });
+ if (cached?.enrollmentMode === "organization_key") {
+ console.warn("[enterprise] organization key required by cached policy");
+ setNeedsLicenseKey(true);
+ setLicenseStatus("required");
+ setPolicy(cached);
+ return;
+ }
+ await initWithMember();
return;
}
@@ -861,7 +914,7 @@ export function useEnterprisePolicy() {
cancelled = true;
stopPolling();
};
- }, [isEnterprise, initWithKey, stopPolling]);
+ }, [isEnterprise, cloudUserToken, initWithKey, initWithMember, stopPolling]);
// Consumer builds: stable no-op functions (no network calls, no re-renders)
const noop = useCallback(() => false, []);
@@ -882,6 +935,11 @@ export function useEnterprisePolicy() {
},
[policy.lockedSettings]
);
+ const requestOrganizationKey = useCallback(() => {
+ if (!isEnterprise) return;
+ setNeedsLicenseKey(true);
+ setLicenseStatus("required");
+ }, [isEnterprise]);
return {
policy: isEnterprise ? policy : EMPTY_POLICY,
@@ -890,6 +948,8 @@ export function useEnterprisePolicy() {
isSettingLocked: isEnterprise ? checkLocked : noop,
getManagedValue: isEnterprise ? getManagedValue : noopGet,
needsLicenseKey: isEnterprise ? needsLicenseKey : false,
+ licenseStatus: isEnterprise ? licenseStatus : "active",
submitLicenseKey,
+ requestOrganizationKey,
};
}