diff --git a/packages/react-native/src/lib/common/config.ts b/packages/react-native/src/lib/common/config.ts index 8f55b4a..7cd519f 100644 --- a/packages/react-native/src/lib/common/config.ts +++ b/packages/react-native/src/lib/common/config.ts @@ -105,8 +105,9 @@ export class RNConfig { // check if the config has expired if ( - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- need to check if expiresAt is set - parsedConfig.workspace.expiresAt && + // A failed first setup stores only the error status, with no workspace, so both can be missing. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- see above + parsedConfig.workspace?.expiresAt && new Date(parsedConfig.workspace.expiresAt) <= new Date() ) { return err(new Error("Config in local storage has expired")); diff --git a/packages/react-native/src/lib/common/setup.ts b/packages/react-native/src/lib/common/setup.ts index 7c76e20..f4addc7 100644 --- a/packages/react-native/src/lib/common/setup.ts +++ b/packages/react-native/src/lib/common/setup.ts @@ -226,7 +226,7 @@ const shouldReturnEarlyForErrorState = ( if (existingConfig?.status.value === "error") { logger.debug("Formbricks was set to an error state."); const expiresAt = existingConfig.status.expiresAt; - if (expiresAt && isNowExpired(expiresAt)) { + if (expiresAt && !isNowExpired(expiresAt)) { logger.debug("Error state is not expired, skipping setup"); return true; } diff --git a/packages/react-native/src/lib/common/tests/config.test.ts b/packages/react-native/src/lib/common/tests/config.test.ts index 2110f16..d6159d2 100644 --- a/packages/react-native/src/lib/common/tests/config.test.ts +++ b/packages/react-native/src/lib/common/tests/config.test.ts @@ -75,6 +75,23 @@ describe("RNConfig", () => { } }); + test("loadFromStorage() reads back the error state a failed first setup writes", async () => { + const expiresAt = new Date(Date.now() + 10 * 60000); + // handleErrorOnFirstSetup stores only the status, with no workspace. + vi.spyOn(AsyncStorage, "getItem").mockResolvedValueOnce( + JSON.stringify({ status: { value: "error", expiresAt } }), + ); + + const result = await configInstance.loadFromStorage(); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.data.status).toEqual({ + value: "error", + expiresAt: expiresAt.toISOString(), + }); + } + }); + test("loadFromStorage() migrates legacy { environmentId, environment } shape", async () => { const { workspaceId, workspace, ...rest } = mockConfig; const legacyStored = { diff --git a/packages/react-native/src/lib/common/tests/setup.test.ts b/packages/react-native/src/lib/common/tests/setup.test.ts index 0ed44f2..f70b44c 100644 --- a/packages/react-native/src/lib/common/tests/setup.test.ts +++ b/packages/react-native/src/lib/common/tests/setup.test.ts @@ -251,62 +251,98 @@ describe("setup.ts", () => { ); }); - test("skips setup if existing config is in error state and not expired", async () => { - const mockConfig = { + describe("error state back-off", () => { + const errorConfig = (expiresAt: Date | string) => ({ get: vi.fn().mockReturnValue({ workspaceId: "env_123", appUrl: "https://my.url", workspace: {}, user: { data: {}, expiresAt: null }, - status: { value: "error", expiresAt: new Date(Date.now() + 10000) }, + status: { value: "error", expiresAt }, }), - }; + }); - getInstanceConfigMock.mockReturnValue( - mockConfig as unknown as Promise, - ); + beforeEach(async () => { + // Exercise the real expiry check instead of pinning a mocked answer. + const actual = + await vi.importActual("@/lib/common/utils"); + (isNowExpired as unknown as Mock).mockImplementation( + actual.isNowExpired, + ); + }); - (isNowExpired as unknown as Mock).mockReturnValue(true); + afterEach(() => { + (isNowExpired as unknown as Mock).mockReset(); + }); - const result = await setup({ - environmentId: "env_123", - appUrl: "https://my.url", + test.each([ + ["a Date", new Date(Date.now() + 5 * 60000)], + // Configs read back from AsyncStorage carry dates as ISO strings. + ["an ISO string", new Date(Date.now() + 5 * 60000).toISOString()], + ])("skips setup while the error state has not expired (%s)", async (_, expiresAt) => { + getInstanceConfigMock.mockReturnValue( + errorConfig(expiresAt) as unknown as Promise, + ); + + const result = await setup({ + workspaceId: "env_123", + appUrl: "https://my.url", + }); + + expect(result.ok).toBe(true); + expect(mockLogger.debug).toHaveBeenCalledWith( + "Formbricks was set to an error state.", + ); + expect(mockLogger.debug).toHaveBeenCalledWith( + "Error state is not expired, skipping setup", + ); + expect(mockLogger.debug).not.toHaveBeenCalledWith("Start setup"); }); - expect(result.ok).toBe(true); - expect(mockLogger.debug).toHaveBeenCalledWith( - "Formbricks was set to an error state.", - ); - expect(mockLogger.debug).toHaveBeenCalledWith( - "Error state is not expired, skipping setup", - ); - }); - test("proceeds if error state is expired", async () => { - const mockConfig = { - get: vi.fn().mockReturnValue({ + test.each([ + ["a Date", new Date(Date.now() - 1000)], + ["an ISO string", new Date(Date.now() - 1000).toISOString()], + ])("continues setup once the error state has expired (%s)", async (_, expiresAt) => { + getInstanceConfigMock.mockReturnValue( + errorConfig(expiresAt) as unknown as Promise, + ); + + const result = await setup({ workspaceId: "env_123", appUrl: "https://my.url", - workspace: {}, - user: { data: {}, expiresAt: null }, - status: { value: "error", expiresAt: new Date(Date.now() - 10000) }, // expired - }), - }; + }); - getInstanceConfigMock.mockReturnValue( - mockConfig as unknown as Promise, - ); + expect(result.ok).toBe(true); + expect(mockLogger.debug).toHaveBeenCalledWith( + "Error state is expired. Continue with setup.", + ); + expect(mockLogger.debug).not.toHaveBeenCalledWith( + "Error state is not expired, skipping setup", + ); + expect(mockLogger.debug).toHaveBeenCalledWith("Start setup"); + }); - const result = await setup({ - environmentId: "env_123", - appUrl: "https://my.url", + test("skips setup inside the window and continues after it", async () => { + vi.useFakeTimers(); + try { + vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); + getInstanceConfigMock.mockReturnValue( + errorConfig( + new Date("2026-01-01T00:10:00Z"), + ) as unknown as Promise, + ); + + vi.setSystemTime(new Date("2026-01-01T00:09:59Z")); + await setup({ workspaceId: "env_123", appUrl: "https://my.url" }); + expect(mockLogger.debug).not.toHaveBeenCalledWith("Start setup"); + + vi.setSystemTime(new Date("2026-01-01T00:10:00Z")); + await setup({ workspaceId: "env_123", appUrl: "https://my.url" }); + expect(mockLogger.debug).toHaveBeenCalledWith("Start setup"); + } finally { + vi.useRealTimers(); + } }); - expect(result.ok).toBe(true); - expect(mockLogger.debug).toHaveBeenCalledWith( - "Formbricks was set to an error state.", - ); - expect(mockLogger.debug).toHaveBeenCalledWith( - "Error state is expired. Continue with setup.", - ); }); test("uses existing config if workspaceId/appUrl match, checks for expiration sync", async () => { diff --git a/packages/react-native/src/lib/common/tests/utils.test.ts b/packages/react-native/src/lib/common/tests/utils.test.ts index c350d77..ea36be0 100644 --- a/packages/react-native/src/lib/common/tests/utils.test.ts +++ b/packages/react-native/src/lib/common/tests/utils.test.ts @@ -9,6 +9,7 @@ import { getDefaultLanguageCode, getLanguageCode, getStyling, + isNowExpired, shouldDisplayBasedOnPercentage, wrapThrowsAsync, } from "@/lib/common/utils"; @@ -48,6 +49,25 @@ describe("utils.ts", () => { }); }); + // --------------------------------------------------------------------------------- + // isNowExpired + // --------------------------------------------------------------------------------- + describe("isNowExpired()", () => { + test("is false before the expiry and true from it on", () => { + expect(isNowExpired(new Date(Date.now() + 60000))).toBe(false); + expect(isNowExpired(new Date(Date.now() - 1))).toBe(true); + }); + + test("reads an ISO string, the shape a date has after AsyncStorage", () => { + expect(isNowExpired(new Date(Date.now() + 60000).toISOString())).toBe( + false, + ); + expect(isNowExpired(new Date(Date.now() - 60000).toISOString())).toBe( + true, + ); + }); + }); + // --------------------------------------------------------------------------------- // wrapThrowsAsync // --------------------------------------------------------------------------------- diff --git a/packages/react-native/src/lib/common/utils.ts b/packages/react-native/src/lib/common/utils.ts index b5f5140..01e1eff 100644 --- a/packages/react-native/src/lib/common/utils.ts +++ b/packages/react-native/src/lib/common/utils.ts @@ -228,8 +228,10 @@ export const shouldDisplayBasedOnPercentage = ( return Math.random() * 100 < displayPercentage; // NOSONAR: Math.random() is sufficient for non-security survey display logic }; -export const isNowExpired = (expirationDate: Date): boolean => { - return new Date() >= expirationDate; +// A date read back from AsyncStorage is an ISO string, so normalise before comparing: +// `new Date() >= "2026-…"` compares a number with NaN and is always false. +export const isNowExpired = (expirationDate: Date | string): boolean => { + return Date.now() >= new Date(expirationDate).getTime(); }; export const delayedResult = async (value: T, ms: number): Promise => {