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(app): enforce signup trial boundary (#5329)
Ezra Ellette30964cdc30fe
diff --git a/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx b/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsxindex b98a2f1d5..1e61b1735 100644--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx@@ -408,6 +408,48 @@ describe("AppEntitlementGate", () => {}});+ it("recomputes a signup trial as Free at its exact hard-expiry boundary", async () => {+ vi.useFakeTimers();+ try {+ const now = new Date("2026-06-05T12:00:00.000Z");+ const expiresAt = new Date(now.getTime() + 1_000).toISOString();+ vi.setSystemTime(now);+ mocks.state.user = baseUser({+ id: "signup-trial-expiring",+ cloud_subscribed: true,+ app_entitled: true,+ subscription_plan: "pro",+ entitlement: {+ active: true,+ plan: "pro",+ source: "signup_trial",+ status: "trialing",+ checked_at: now.toISOString(),+ current_period_end: expiresAt,+ expires_at: expiresAt,+ grace_until: null,+ features: { app: true, cloud: true, integrations: true },+ },+ });+ render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);+ expect(screen.getByTestId("protected-app")).toBeInTheDocument();++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1_000);+ });++ expect(screen.getByTestId("protected-app")).toBeInTheDocument();+ expect(+ screen.queryByRole("heading", { name: /refresh access/i }),+ ).not.toBeInTheDocument();+ expect(mocks.stopScreenpipe).not.toHaveBeenCalled();+ expect(mocks.setCloudToken).toHaveBeenCalledWith("tok");+ expect(mocks.loadUser).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+it("rechecks and gates paid evidence after a backwards clock jump", async () => {vi.useFakeTimers();try {diff --git a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsxindex 0f4c34457..d1c230181 100644--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx@@ -193,22 +193,33 @@ export function AppEntitlementGate({}const remaining = paidPolicyDeadlineMs - nowMs;- // Freshness is valid through the exact boundary. Minute-sized slices- // detect wall-clock changes and also avoid overflowing long JS timers.- if (remaining >= 0) {+ // Signup trials end at their exact boundary, while ordinary freshness+ // remains valid through its boundary. Re-render at zero for the trial;+ // if policy is still valid, one final 1ms tick handles freshness.+ if (remaining > 0) {timeout = setTimeout(schedule,- Math.min(remaining + 1, POLICY_CLOCK_CHECK_INTERVAL_MS),+ Math.min(remaining, POLICY_CLOCK_CHECK_INTERVAL_MS),);return;}setPaidPolicyExpiryTick((value) => value + 1);+ // The Rust manager owns the live pipe cap and free-retention flag. A+ // clock-only transition does not write settings, so explicitly ask the+ // existing token/policy command to re-read the cached entitlement and+ // apply its new local classification without a network request.+ if (user?.token) {+ void commands.setCloudToken(user.token).catch((error) => {+ console.warn("failed to apply local plan deadline:", error);+ });+ }+ if (remaining === 0) timeout = setTimeout(schedule, 1);};schedule();return () => {if (timeout !== undefined) clearTimeout(timeout);};- }, [devBypass, paidPolicyDeadlineMs]);+ }, [devBypass, paidPolicyDeadlineMs, user?.token]);// Retry secret-store hydration only during a bounded window. The window may// delay a consumer login prompt for already verified policy, but it neverdiff --git a/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts b/apps/screenpipe-app-tauri/lib/app-entitlement.test.tsindex 032949ebb..0d2540cf2 100644--- a/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts+++ b/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts@@ -37,6 +37,34 @@ function user(overrides: Record<string, any>) {} as any;}+function signupTrialUser(expiresAtMs: number) {+ const hardExpiry = new Date(expiresAtMs).toISOString();+ return user({+ id: "user_signup_trial",+ cloud_subscribed: true,+ app_entitled: true,+ subscription_plan: "pro",+ entitlement: {+ active: true,+ plan: "pro",+ source: "signup_trial",+ status: "trialing",+ checked_at: new Date(NOW.getTime() - 60_000).toISOString(),+ current_period_end: hardExpiry,+ expires_at: hardExpiry,+ grace_until: null,+ features: {+ app: true,+ local_recording: true,+ cloud: true,+ integrations: true,+ team: false,+ enterprise: false,+ },+ },+ });+}+describe("app entitlement", () => {beforeEach(() => {vi.useFakeTimers();@@ -66,6 +94,55 @@ describe("app entitlement", () => {).toBe(true);});+ it("treats a fresh pro signup trial as Business until its hard expiry", () => {+ const expiresAtMs = NOW.getTime() + 60 * 60 * 1000;+ const trial = signupTrialUser(expiresAtMs);++ expect(getLocalPlanPolicy(trial)).toBe("verified-paid");+ expect(hasAppEntitlement(trial)).toBe(true);+ expect(hasCloudEntitlement(trial)).toBe(true);+ expect(hasConsumerAppSubscription(trial)).toBe(true);+ expect(planDisplayName(trial.subscription_plan)).toBe("Business");+ expect(getPaidPlanPolicyDeadlineMs(trial, NOW.getTime())).toBe(expiresAtMs);+ });++ it("downgrades a signup trial to Free exactly at ends_at", () => {+ const expiresAtMs = NOW.getTime() + 60 * 60 * 1000;+ const trial = signupTrialUser(expiresAtMs);++ vi.setSystemTime(expiresAtMs - 1);+ expect(getLocalPlanPolicy(trial)).toBe("verified-paid");++ vi.setSystemTime(expiresAtMs);+ expect(getLocalPlanPolicy(trial)).toBe("verified-free");+ expect(hasAppEntitlement(trial)).toBe(false);+ expect(hasCloudEntitlement(trial)).toBe(false);+ expect(hasConsumerAppSubscription(trial)).toBe(false);+ expect(isAuthenticatedFreeUser(trial)).toBe(true);+ expect(needsAppEntitlementRefresh(trial)).toBe(true);+ expect(getPaidPlanPolicyDeadlineMs(trial, expiresAtMs)).toBeNull();++ vi.setSystemTime(expiresAtMs + 1);+ expect(getLocalPlanPolicy(trial)).toBe("verified-free");+ });++ it("fails malformed signup trials closed and never lets grace extend them", () => {+ const expiresAtMs = NOW.getTime() + 60 * 60 * 1000;+ const missingExpiry = signupTrialUser(expiresAtMs);+ delete missingExpiry.entitlement.expires_at;+ const malformedPeriodEnd = signupTrialUser(expiresAtMs);+ malformedPeriodEnd.entitlement.current_period_end = "not-a-date";+ const graceCannotExtend = signupTrialUser(expiresAtMs);+ graceCannotExtend.entitlement.expires_at = new Date(NOW.getTime() - 1).toISOString();+ graceCannotExtend.entitlement.grace_until = new Date(+ NOW.getTime() + 24 * 60 * 60 * 1000,+ ).toISOString();++ expect(getLocalPlanPolicy(missingExpiry)).toBe("unknown");+ expect(getLocalPlanPolicy(malformedPeriodEnd)).toBe("unknown");+ expect(getLocalPlanPolicy(graceCannotExtend)).toBe("verified-free");+ });+it("blocks stale cached app access", () => {const staleUser = user({app_entitled: true,diff --git a/apps/screenpipe-app-tauri/lib/app-entitlement.ts b/apps/screenpipe-app-tauri/lib/app-entitlement.tsindex e9a30f511..6705853aa 100644--- a/apps/screenpipe-app-tauri/lib/app-entitlement.ts+++ b/apps/screenpipe-app-tauri/lib/app-entitlement.ts@@ -16,6 +16,7 @@ export type AppEntitlementPlan =export type AppEntitlementSource =| "none"| "subscription"+ | "signup_trial"| "manual"| "enterprise"| "lifetime"@@ -141,6 +142,38 @@ function parseEntitlementTime(value: string | null | undefined) {return Number.isFinite(time) ? time : null;}+function entitlementSource(entitlement: AppEntitlement | null): string | null {+ return typeof entitlement?.source === "string"+ ? entitlement.source.trim().toLowerCase()+ : null;+}++function isSignupTrial(entitlement: AppEntitlement | null): boolean {+ return entitlementSource(entitlement) === "signup_trial";+}++// Signup trials are non-renewable and have no offline grace. The website+// returns both fields with the same ends_at. Requiring both means a partial or+// malformed cache cannot extend the trial; the earlier value fails closed if+// the fields ever disagree.+function getSignupTrialHardExpiryMs(+ entitlement: AppEntitlement | null,+): number | null {+ if (!isSignupTrial(entitlement)) return null;+ const expiresAt = parseEntitlementTime(entitlement?.expires_at);+ const currentPeriodEnd = parseEntitlementTime(entitlement?.current_period_end);+ if (expiresAt === null || currentPeriodEnd === null) return null;+ return Math.min(expiresAt, currentPeriodEnd);+}++function isSignupTrialActiveAt(+ entitlement: AppEntitlement | null,+ nowMs: number,+): boolean {+ const hardExpiryMs = getSignupTrialHardExpiryMs(entitlement);+ return hardExpiryMs !== null && nowMs < hardExpiryMs && entitlement?.active === true;+}+function getStableAccountId(user: AppUser | null | undefined,): string | null {@@ -175,9 +208,29 @@ function isEntitlementFresh(entitlement: AppEntitlement | null) {*/function hasVerifiedFreePlan(user: AppUser | null | undefined): boolean {const stableAccountId = getStableAccountId(user);- if (!user || !stableAccountId || user.cloud_subscribed === true) return false;+ if (!user || !stableAccountId) return false;const entitlement = asEntitlement(user.entitlement);+ if (isSignupTrial(entitlement)) {+ const nowMs = Date.now();+ const checkedAt = parseEntitlementTime(entitlement?.checked_at);+ const hardExpiryMs = getSignupTrialHardExpiryMs(entitlement);+ const accountPlan = user.subscription_plan?.trim().toLowerCase();+ const entitlementPlan =+ typeof entitlement?.plan === "string"+ ? entitlement.plan.trim().toLowerCase()+ : null;+ return (+ accountPlan === "pro" &&+ entitlementPlan === "pro" &&+ checkedAt !== null &&+ checkedAt <= nowMs + APP_ENTITLEMENT_CLOCK_SKEW_MS &&+ hardExpiryMs !== null &&+ nowMs >= hardExpiryMs+ );+ }++ if (user.cloud_subscribed === true) return false;// Once verified, free limits persist offline; merely waiting 72 hours must// not silently unlock pipes or retention controls.const checkedAt = parseEntitlementTime(entitlement?.checked_at);@@ -203,6 +256,7 @@ function hasVerifiedFreePlan(user: AppUser | null | undefined): boolean {source === "manual" ||source === "enterprise" ||source === "lifetime" ||+ source === "signup_trial" ||source === "dev" ||hasFutureGrace(entitlement)) {@@ -271,6 +325,15 @@ function hasVerifiedPaidPlanAt((user.app_entitled === true || entitlement.features?.app === true);if (!hasAppFeature) return false;+ // active:true, grace, and a fresh check must never carry this fixed trial+ // through the server-issued ends_at instant.+ if (isSignupTrial(entitlement)) {+ return (+ isEntitlementFreshAt(entitlement, nowMs) &&+ isSignupTrialActiveAt(entitlement, nowMs)+ );+ }+if (isLifetimeEntitlement(entitlement) ||hasFutureGraceAt(entitlement, nowMs)@@ -330,6 +393,10 @@ export function getPaidPlanPolicyDeadlineMs(if (!entitlement || isLifetimeEntitlement(entitlement)) return null;const deadlines: number[] = [];+ const signupTrialDeadline = getSignupTrialHardExpiryMs(entitlement);+ if (signupTrialDeadline !== null && signupTrialDeadline > nowMs) {+ deadlines.push(signupTrialDeadline);+ }const checkedAt = parseEntitlementTime(entitlement.checked_at);if (entitlement.active === true && checkedAt !== null) {const freshnessDeadline = checkedAt + APP_ENTITLEMENT_MAX_STALE_MS;@@ -364,6 +431,13 @@ export function hasLegacyPaidAccess(user: AppUser | null | undefined) {(user.app_entitled === true || entitlement.features?.app === true);if (!hasAppFeature) return false;+ if (isSignupTrial(entitlement)) {+ return (+ isEntitlementFresh(entitlement) &&+ isSignupTrialActiveAt(entitlement, Date.now())+ );+ }+if (isLifetimeEntitlement(entitlement) || hasFutureGrace(entitlement)) return true;return isEntitlementFresh(entitlement) && entitlement.active === true;@@ -383,7 +457,12 @@ export function hasConsumerAppSubscription(user: AppUser | null | undefined) {: null;if (source === "enterprise") return false;- if (source === "subscription" || source === "manual" || source === "lifetime") {+ if (+ source === "subscription" ||+ source === "signup_trial" ||+ source === "manual" ||+ source === "lifetime"+ ) {return hasAppEntitlement(user);}@@ -455,7 +534,10 @@ export function needsAppEntitlementRefresh(user: AppUser | null | undefined) {// they never need a re-verification prompt.if (isLifetimeEntitlement(entitlement) || hasFutureGrace(entitlement)) return false;const appearsEntitled = user.app_entitled === true || entitlement?.features?.app === true;- return appearsEntitled && !isEntitlementFresh(entitlement);+ const signupTrialExpiredOrInvalid =+ isSignupTrial(entitlement) &&+ !isSignupTrialActiveAt(entitlement, Date.now());+ return appearsEntitled && (!isEntitlementFresh(entitlement) || signupTrialExpiredOrInvalid);}export function normalizePlanLabel(plan: string | null | undefined) {diff --git a/apps/screenpipe-app-tauri/lib/auth-guard.test.tsx b/apps/screenpipe-app-tauri/lib/auth-guard.test.tsxindex 5f765db8f..dc72982dc 100644--- a/apps/screenpipe-app-tauri/lib/auth-guard.test.tsx+++ b/apps/screenpipe-app-tauri/lib/auth-guard.test.tsx@@ -33,10 +33,13 @@ vi.mock("posthog-js", () => ({ default: { capture: mocks.capture } }));vi.mock("@/components/ui/use-toast", () => ({ toast: mocks.toast }));vi.mock("@/components/ui/toast", () => ({ ToastAction: () => null }));-vi.mock("@/lib/web-url", () => ({ screenpipeWebUrl: () => "https://screenpipe.com/login" }));+vi.mock("@/lib/web-url", () => ({+ screenpipeWebUrl: (path: string) => `https://screenpipe.com${path}`,+}));import {AuthGuard,+ appLoginUrl,installAuthInterceptor,isScreenpipeApi,isScreenpipeAuthApi,@@ -45,6 +48,12 @@ import {const LOGGED_IN = { token: "tok-123", cloud_subscribed: false };+describe("appLoginUrl", () => {+ it("marks direct web login as app initiated", () => {+ expect(appLoginUrl()).toBe("https://screenpipe.com/login?source=app");+ });+});+function renderGuard() {return render(<AuthGuard>diff --git a/apps/screenpipe-app-tauri/lib/auth-guard.tsx b/apps/screenpipe-app-tauri/lib/auth-guard.tsxindex 89b039e70..b44953368 100644--- a/apps/screenpipe-app-tauri/lib/auth-guard.tsx+++ b/apps/screenpipe-app-tauri/lib/auth-guard.tsx@@ -20,6 +20,10 @@ const FOCUS_REVERIFY_COOLDOWN_MS = 30 * 1000;let lastToastTime = 0;+export function appLoginUrl() {+ return screenpipeWebUrl("/login?source=app", "https://screenpipe.com");+}+// Decide whether a window-focus / visibility change should trigger an eager// entitlement re-verify. Exported for unit testing. We skip while the window is// hidden (a `visibilitychange` to hidden shouldn't fetch) and debounce against@@ -38,7 +42,7 @@ export function shouldReverifyOnFocus(function openLogin() {// dynamic import to avoid SSR/test crashes from tauri plugins- const loginUrl = screenpipeWebUrl("/login", "https://screenpipe.com");+ const loginUrl = appLoginUrl();import("@tauri-apps/plugin-shell").then(({ open }) => {open(loginUrl);}).catch(() => {diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rsindex d86cb4b70..0ae6ecf0e 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs@@ -41,7 +41,10 @@ fn log_webview_build_failure(label: &str, url_hint: &str, err: &(impl std::fmt::#[cfg(all(test, target_os = "macos"))]mod tests {- use super::{fallback_local_api_config, is_login_callback_scheme, scan_chat_entries_by_mtime};+ use super::{+ app_login_url, fallback_local_api_config, is_login_callback_scheme,+ scan_chat_entries_by_mtime,+ };#[test]fn chat_entries_missing_dir_is_empty() {@@ -78,6 +81,18 @@ mod tests {assert!(is_login_callback_scheme("screenpipe"));}+ #[test]+ fn app_login_url_marks_source_and_preserves_return_scheme() {+ assert_eq!(+ app_login_url(None),+ "https://screenpipe.com/login?source=app"+ );+ assert_eq!(+ app_login_url(Some("screenpipe-enterprise")),+ "https://screenpipe.com/login?source=app&return_scheme=screenpipe-enterprise"+ );+ }+// Regression for b7dc02415: `get_local_api_config` returned {key: null}// during the cold-spawn window between webview load and `spawn_screenpipe`// populating `RecordingState.server`. The privacy panel's `loadLiveApiKey`@@ -1535,7 +1550,14 @@ pub async fn get_disk_usage(}}-const LOGIN_URL: &str = "https://screenpipe.com/login";+const LOGIN_URL: &str = "https://screenpipe.com/login?source=app";++fn app_login_url(return_scheme: Option<&str>) -> String {+ match return_scheme {+ Some(return_scheme) => format!("{LOGIN_URL}&return_scheme={return_scheme}"),+ None => LOGIN_URL.to_string(),+ }+}/// The custom URL scheme this build registers for deep links. The enterprise/// build uses a distinct scheme so it does not collide with the consumer app's@@ -1576,7 +1598,7 @@ pub async fn open_login_window(// with another installed build here (#3890) and stays correct until// the website honours `return_scheme`.let callback_url = match crate::auth_session::start_session(- LOGIN_URL.to_string(),+ app_login_url(None),"screenpipe".to_string(),fresh_session,)@@ -1625,7 +1647,7 @@ pub async fn open_login_window(let app_for_nav = app_handle.clone();let label_for_nav = label.clone();- let login_url = format!("{}?return_scheme={}", LOGIN_URL, deep_link_scheme());+ let login_url = app_login_url(Some(deep_link_scheme()));let mut builder = WebviewWindowBuilder::new(&app_handle,label.clone(),diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rsindex 5d98f3089..fb337a83f 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs@@ -1161,21 +1161,25 @@ fn parse_entitlement_time(.map(|value| value.with_timezone(&chrono::Utc))}-fn entitlement_checked_recently(entitlement: &serde_json::Value) -> bool {+fn entitlement_checked_recently_at(+ entitlement: &serde_json::Value,+ now: chrono::DateTime<chrono::Utc>,+) -> bool {let Some(checked_at) = parse_entitlement_time(entitlement.get("checked_at")) else {return false;};- let now = chrono::Utc::now();checked_at <= now + chrono::Duration::minutes(APP_ENTITLEMENT_CLOCK_SKEW_MINUTES)&& now.signed_duration_since(checked_at)<= chrono::Duration::hours(APP_ENTITLEMENT_MAX_STALE_HOURS)}-fn entitlement_was_verified(entitlement: &serde_json::Value) -> bool {+fn entitlement_was_verified_at(+ entitlement: &serde_json::Value,+ now: chrono::DateTime<chrono::Utc>,+) -> bool {parse_entitlement_time(entitlement.get("checked_at")).is_some_and(|checked_at| {- checked_at- <= chrono::Utc::now() + chrono::Duration::minutes(APP_ENTITLEMENT_CLOCK_SKEW_MINUTES)+ checked_at <= now + chrono::Duration::minutes(APP_ENTITLEMENT_CLOCK_SKEW_MINUTES)})}@@ -1186,12 +1190,41 @@ fn entitlement_active(entitlement: &serde_json::Value) -> bool {.unwrap_or(false)}-fn entitlement_has_future_grace(entitlement: &serde_json::Value) -> bool {+fn entitlement_has_future_grace_at(+ entitlement: &serde_json::Value,+ now: chrono::DateTime<chrono::Utc>,+) -> bool {parse_entitlement_time(entitlement.get("grace_until"))- .map(|grace_until| grace_until > chrono::Utc::now())+ .map(|grace_until| grace_until > now).unwrap_or(false)}+fn entitlement_is_signup_trial(entitlement: &serde_json::Value) -> bool {+ entitlement+ .get("source")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|source| source.trim().eq_ignore_ascii_case("signup_trial"))+}++fn signup_trial_hard_expiry(+ entitlement: &serde_json::Value,+) -> Option<chrono::DateTime<chrono::Utc>> {+ if !entitlement_is_signup_trial(entitlement) {+ return None;+ }+ let expires_at = parse_entitlement_time(entitlement.get("expires_at"))?;+ let current_period_end = parse_entitlement_time(entitlement.get("current_period_end"))?;+ Some(std::cmp::min(expires_at, current_period_end))+}++fn signup_trial_active_at(+ entitlement: &serde_json::Value,+ now: chrono::DateTime<chrono::Utc>,+) -> bool {+ signup_trial_hard_expiry(entitlement)+ .is_some_and(|hard_expiry| now < hard_expiry && entitlement_active(entitlement))+}+fn entitlement_is_lifetime(entitlement: &serde_json::Value) -> bool {let field = |key: &str| {entitlement@@ -1629,9 +1662,34 @@ impl SettingsStore {config}- fn has_verified_free_plan(&self) -> bool {- if !self.has_account_identity()- || self.user.cloud_subscribed == Some(true)+ fn has_verified_free_plan_at(&self, now: chrono::DateTime<chrono::Utc>) -> bool {+ if !self.has_account_identity() {+ return false;+ }++ if let Some(entitlement) = self+ .user+ .entitlement+ .as_ref()+ .filter(|entitlement| entitlement_is_signup_trial(entitlement))+ {+ let account_plan_is_pro = self+ .user+ .subscription_plan+ .as_deref()+ .is_some_and(|plan| plan.trim().eq_ignore_ascii_case("pro"));+ let entitlement_plan_is_pro = entitlement+ .get("plan")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|plan| plan.trim().eq_ignore_ascii_case("pro"));+ return account_plan_is_pro+ && entitlement_plan_is_pro+ && entitlement_was_verified_at(entitlement, now)+ && signup_trial_hard_expiry(entitlement)+ .is_some_and(|hard_expiry| now >= hard_expiry);+ }++ if self.user.cloud_subscribed == Some(true)|| !self.user.subscription_plan@@ -1648,11 +1706,11 @@ impl SettingsStore {.is_some_and(|source| {matches!(source.to_ascii_lowercase().as_str(),- "manual" | "enterprise" | "lifetime" | "dev"+ "manual" | "enterprise" | "lifetime" | "signup_trial" | "dev")});!source_is_paid_override- && !entitlement_has_future_grace(entitlement)+ && !entitlement_has_future_grace_at(entitlement, now)&& entitlement.get("plan").and_then(serde_json::Value::as_str)@@ -1660,11 +1718,11 @@ impl SettingsStore {// Once a successful account refresh marks this install free,// keep the local policy while offline. A later paid refresh// clears it; merely waiting 72 hours must not unlock limits.- && entitlement_was_verified(entitlement)+ && entitlement_was_verified_at(entitlement, now)})}- fn has_verified_paid_plan(&self) -> bool {+ fn has_verified_paid_plan_at(&self, now: chrono::DateTime<chrono::Utc>) -> bool {if !self.has_account_identity() {return false;}@@ -1688,7 +1746,7 @@ impl SettingsStore {let Some(entitlement) = self.user.entitlement.as_ref() else {return false;};- if !entitlement_was_verified(entitlement) {+ if !entitlement_was_verified_at(entitlement, now) {return false;}let Some(entitlement_plan) = entitlement@@ -1716,24 +1774,34 @@ impl SettingsStore {return false;}+ if entitlement_is_signup_trial(entitlement) {+ return entitlement_checked_recently_at(entitlement, now)+ && signup_trial_active_at(entitlement, now);+ }+entitlement_is_lifetime(entitlement)- || entitlement_has_future_grace(entitlement)- || (entitlement_checked_recently(entitlement) && entitlement_active(entitlement))+ || entitlement_has_future_grace_at(entitlement, now)+ || (entitlement_checked_recently_at(entitlement, now)+ && entitlement_active(entitlement))}/// Local paid-only behavior is unlocked only by internally consistent,/// server-verified plan evidence. Missing, conflicting, stale-paid, and/// future-dated evidence remains explicitly unknown.- pub(crate) fn local_plan_policy(&self) -> LocalPlanPolicy {- if self.has_verified_paid_plan() {+ fn local_plan_policy_at(&self, now: chrono::DateTime<chrono::Utc>) -> LocalPlanPolicy {+ if self.has_verified_paid_plan_at(now) {LocalPlanPolicy::VerifiedPaid- } else if self.has_verified_free_plan() {+ } else if self.has_verified_free_plan_at(now) {LocalPlanPolicy::VerifiedFree} else {LocalPlanPolicy::Unknown}}+ pub(crate) fn local_plan_policy(&self) -> LocalPlanPolicy {+ self.local_plan_policy_at(chrono::Utc::now())+ }+pub(crate) fn has_free_plan_policy(&self) -> bool {self.local_plan_policy() == LocalPlanPolicy::VerifiedFree}@@ -1760,7 +1828,7 @@ impl SettingsStore {}fn has_current_app_entitlement(&self) -> bool {- self.has_verified_paid_plan()+ self.has_verified_paid_plan_at(chrono::Utc::now())}/// Consumer binaries must not record behind an org's mandatory-enterprise-@@ -2244,6 +2312,78 @@ mod tests {assert!(store.has_current_app_entitlement());}+ #[test]+ fn signup_trial_is_paid_only_before_its_hard_expiry() {+ let now = chrono::DateTime::parse_from_rfc3339("2026-06-05T12:00:00Z")+ .unwrap()+ .with_timezone(&chrono::Utc);+ let ends_at = now + chrono::Duration::hours(1);+ let mut store = SettingsStore::default();+ store.user.id = Some("user_signup_trial".to_string());+ store.user.token = Some("token".to_string());+ store.user.cloud_subscribed = Some(true);+ store.user.app_entitled = Some(true);+ store.user.subscription_plan = Some("pro".to_string());+ store.user.entitlement = Some(json!({+ "active": true,+ "plan": "pro",+ "source": "signup_trial",+ "status": "trialing",+ "checked_at": (now - chrono::Duration::minutes(1)).to_rfc3339(),+ "current_period_end": ends_at.to_rfc3339(),+ "expires_at": ends_at.to_rfc3339(),+ "grace_until": null,+ "features": {+ "app": true,+ "local_recording": true,+ "cloud": true,+ "integrations": true,+ "team": false,+ "enterprise": false+ }+ }));++ assert_eq!(+ store.local_plan_policy_at(now),+ LocalPlanPolicy::VerifiedPaid+ );+ assert_eq!(+ store.local_plan_policy_at(ends_at - chrono::Duration::nanoseconds(1)),+ LocalPlanPolicy::VerifiedPaid+ );+ assert_eq!(+ store.local_plan_policy_at(ends_at),+ LocalPlanPolicy::VerifiedFree+ );+ assert_eq!(+ store.local_plan_policy_at(ends_at + chrono::Duration::seconds(1)),+ LocalPlanPolicy::VerifiedFree+ );+ }++ #[test]+ fn signup_trial_missing_or_malformed_hard_expiry_fails_closed() {+ let now = chrono::DateTime::parse_from_rfc3339("2026-06-05T12:00:00Z")+ .unwrap()+ .with_timezone(&chrono::Utc);+ let mut store = SettingsStore::default();+ store.user.id = Some("user_signup_trial".to_string());+ store.user.app_entitled = Some(true);+ store.user.subscription_plan = Some("pro".to_string());+ store.user.entitlement = Some(json!({+ "active": true,+ "plan": "pro",+ "source": "signup_trial",+ "checked_at": now.to_rfc3339(),+ "current_period_end": (now + chrono::Duration::days(7)).to_rfc3339(),+ "expires_at": "not-a-date",+ "grace_until": (now + chrono::Duration::days(30)).to_rfc3339(),+ "features": { "app": true }+ }));++ assert_eq!(store.local_plan_policy_at(now), LocalPlanPolicy::Unknown);+ }+#[test]fn explicit_app_entitlement_denial_overrides_cached_entitlement_blob() {let mut store = SettingsStore::default();