Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(mobile): add auth session and sign-in flow
Richie McIlroy92c782304fc3
diff --git a/apps/mobile/src/auth/AuthContext.test.ts b/apps/mobile/src/auth/AuthContext.test.tsnew file mode 100644index 000000000..e0bc13805--- /dev/null+++ b/apps/mobile/src/auth/AuthContext.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";+import { parseAuthRedirect, requireAuthRedirectSession } from "./session";++describe("parseAuthRedirect", () => {+ it("extracts the issued API key and user id", () => {+ expect(+ parseAuthRedirect("cap://auth?api_key=key_123&user_id=user_123"),+ ).toEqual({+ apiKey: "key_123",+ userId: "user_123",+ });+ });++ it("rejects redirects without an API key", () => {+ expect(parseAuthRedirect("cap://auth?user_id=user_123")).toBeNull();+ });++ it("throws a usable message for failed auth callbacks", () => {+ expect(() =>+ requireAuthRedirectSession(+ "cap://auth?error_description=Organization%20not%20found",+ ),+ ).toThrow("Organization not found");+ });++ it("throws when an auth callback omits the mobile API key", () => {+ expect(() =>+ requireAuthRedirectSession("cap://auth?user_id=user_123"),+ ).toThrow("Sign in did not return a mobile session.");+ });+});diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxnew file mode 100644index 000000000..9c97d7ec2--- /dev/null+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -0,0 +1,256 @@+import Constants from "expo-constants";+import * as Linking from "expo-linking";+import * as SecureStore from "expo-secure-store";+import * as WebBrowser from "expo-web-browser";+import {+ createContext,+ type ReactNode,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useState,+} from "react";+import {+ createMobileApiClient,+ createSessionRequestUrl,+ type MobileApiClient,+ type MobileAuthConfigResponse,+ type MobileBootstrapResponse,+} from "@/api/mobile";+import { requireAuthRedirectSession } from "./session";++WebBrowser.maybeCompleteAuthSession();++const sessionKey = "cap.mobile.apiKey";+const userIdKey = "cap.mobile.userId";++type AuthState = {+ status: "loading" | "signedOut" | "signedIn";+ apiKey: string | null;+ userId: string | null;+ authConfig: MobileAuthConfigResponse;+ bootstrap: MobileBootstrapResponse | null;+ client: MobileApiClient;+ requestEmailCode: (email: string) => Promise<void>;+ verifyEmailCode: (email: string, code: string) => Promise<void>;+ signInWithGoogle: () => Promise<void>;+ signInWithSso: (organizationId: string) => Promise<void>;+ signOut: () => Promise<void>;+ refresh: () => Promise<void>;+ setActiveOrganization: (organizationId: string) => Promise<void>;+};++const AuthContext = createContext<AuthState | null>(null);+const fallbackAuthConfig: MobileAuthConfigResponse = {+ googleAuthAvailable: true,+ workosAuthAvailable: true,+};++const getExtraString = (key: string, fallback: string) => {+ const extra = Constants.expoConfig?.extra;+ if (!extra || typeof extra !== "object") return fallback;+ const value = (extra as Record<string, unknown>)[key];+ return typeof value === "string" ? value : fallback;+};++export const apiBaseUrl = getExtraString("apiBaseUrl", "https://cap.so");++export function AuthProvider({ children }: { children: ReactNode }) {+ const [apiKey, setApiKey] = useState<string | null>(null);+ const [userId, setUserId] = useState<string | null>(null);+ const [authConfig, setAuthConfig] =+ useState<MobileAuthConfigResponse>(fallbackAuthConfig);+ const [bootstrap, setBootstrap] = useState<MobileBootstrapResponse | null>(+ null,+ );+ const [loading, setLoading] = useState(true);++ const client = useMemo(+ () =>+ createMobileApiClient({+ baseUrl: apiBaseUrl,+ getToken: () => apiKey,+ }),+ [apiKey],+ );+ const publicClient = useMemo(+ () =>+ createMobileApiClient({+ baseUrl: apiBaseUrl,+ getToken: () => null,+ }),+ [],+ );++ const refresh = useCallback(async () => {+ const response = await client.bootstrap();+ setBootstrap(response);+ }, [client]);++ useEffect(() => {+ let active = true;+ const load = async () => {+ try {+ const [storedKey, storedUserId, nextAuthConfig] = await Promise.all([+ SecureStore.getItemAsync(sessionKey),+ SecureStore.getItemAsync(userIdKey),+ publicClient.getAuthConfig().catch(() => fallbackAuthConfig),+ ]);+ if (!active) return;+ setApiKey(storedKey);+ setUserId(storedKey ? storedUserId : null);+ setAuthConfig(nextAuthConfig);+ if (!storedKey && storedUserId) {+ SecureStore.deleteItemAsync(userIdKey).catch(() => {});+ }+ } finally {+ if (active) setLoading(false);+ }+ };+ load();+ return () => {+ active = false;+ };+ }, [publicClient]);++ useEffect(() => {+ if (!apiKey) {+ setUserId(null);+ setBootstrap(null);+ return;+ }++ refresh().catch(() => {+ setApiKey(null);+ setUserId(null);+ setBootstrap(null);+ SecureStore.deleteItemAsync(sessionKey).catch(() => {});+ SecureStore.deleteItemAsync(userIdKey).catch(() => {});+ });+ }, [apiKey, refresh]);++ const storeSession = useCallback(+ async (session: { apiKey: string; userId: string | null }) => {+ await SecureStore.setItemAsync(sessionKey, session.apiKey);+ if (session.userId) {+ await SecureStore.setItemAsync(userIdKey, session.userId);+ } else {+ await SecureStore.deleteItemAsync(userIdKey);+ }+ setApiKey(session.apiKey);+ setUserId(session.userId);+ },+ [],+ );++ const requestEmailCode = useCallback(+ async (email: string) => {+ await client.requestEmailCode(email);+ },+ [client],+ );++ const verifyEmailCode = useCallback(+ async (email: string, code: string) => {+ const session = await client.verifyEmailCode({ email, code });+ await storeSession({+ apiKey: session.apiKey,+ userId: session.userId,+ });+ },+ [client, storeSession],+ );++ const signInWithGoogle = useCallback(async () => {+ const redirectUri = Linking.createURL("auth");+ const result = await WebBrowser.openAuthSessionAsync(+ createSessionRequestUrl(apiBaseUrl, redirectUri, "google"),+ redirectUri,+ );+ if (result.type !== "success") return;++ await storeSession(requireAuthRedirectSession(result.url));+ }, [storeSession]);++ const signInWithSso = useCallback(+ async (organizationId: string) => {+ const redirectUri = Linking.createURL("auth");+ const result = await WebBrowser.openAuthSessionAsync(+ createSessionRequestUrl(+ apiBaseUrl,+ redirectUri,+ "workos",+ organizationId,+ ),+ redirectUri,+ );+ if (result.type !== "success") return;++ await storeSession(requireAuthRedirectSession(result.url));+ },+ [storeSession],+ );++ const signOut = useCallback(async () => {+ if (apiKey) {+ await client.revokeSession().catch(() => {});+ }+ await Promise.all([+ SecureStore.deleteItemAsync(sessionKey),+ SecureStore.deleteItemAsync(userIdKey),+ ]);+ setApiKey(null);+ setUserId(null);+ setBootstrap(null);+ }, [apiKey, client]);++ const setActiveOrganization = useCallback(+ async (organizationId: string) => {+ const nextBootstrap = await client.setActiveOrganization(organizationId);+ setBootstrap(nextBootstrap);+ },+ [client],+ );++ const value = useMemo<AuthState>(+ () => ({+ status: loading ? "loading" : apiKey ? "signedIn" : "signedOut",+ apiKey,+ userId,+ authConfig,+ bootstrap,+ client,+ requestEmailCode,+ verifyEmailCode,+ signInWithGoogle,+ signInWithSso,+ signOut,+ refresh,+ setActiveOrganization,+ }),+ [+ loading,+ apiKey,+ userId,+ authConfig,+ bootstrap,+ client,+ requestEmailCode,+ verifyEmailCode,+ signInWithGoogle,+ signInWithSso,+ signOut,+ refresh,+ setActiveOrganization,+ ],+ );++ return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;+}++export const useAuth = () => {+ const value = useContext(AuthContext);+ if (!value) throw new Error("useAuth must be used inside AuthProvider");+ return value;+};diff --git a/apps/mobile/src/auth/AuthProvider.test.tsx b/apps/mobile/src/auth/AuthProvider.test.tsxnew file mode 100644index 000000000..0d9c232f2--- /dev/null+++ b/apps/mobile/src/auth/AuthProvider.test.tsx@@ -0,0 +1,172 @@+import React, { type ReactNode } from "react";+import TestRenderer, { act } from "react-test-renderer";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { AuthProvider, useAuth } from "./AuthContext";++type HostProps = {+ children?: ReactNode;+};++const secureStoreMock = vi.hoisted(() => ({+ deleteItemAsync: vi.fn((_key: string) => Promise.resolve()),+ getItemAsync: vi.fn((_key: string) => Promise.resolve(null as string | null)),+ setItemAsync: vi.fn((_key: string, _value: string) => Promise.resolve()),+}));++const apiMock = vi.hoisted(() => ({+ bootstrap: vi.fn(() =>+ Promise.resolve({+ activeOrganizationId: "org_123",+ user: {+ email: "[email protected]",+ name: "Richie",+ },+ }),+ ),+ getAuthConfig: vi.fn(() =>+ Promise.resolve({+ googleAuthAvailable: true,+ workosAuthAvailable: true,+ }),+ ),+}));++vi.mock("react-native", async () => {+ const React = await import("react");++ return {+ View: ({ children }: HostProps) =>+ React.createElement("View", null, children),+ };+});++vi.mock("expo-constants", () => ({+ default: {+ expoConfig: {+ extra: {},+ },+ },+}));++vi.mock("expo-linking", () => ({+ createURL: vi.fn(() => "cap://auth"),+}));++vi.mock("expo-secure-store", () => secureStoreMock);++vi.mock("expo-web-browser", () => ({+ maybeCompleteAuthSession: vi.fn(),+ openAuthSessionAsync: vi.fn(),+}));++vi.mock("@/api/mobile", () => ({+ createMobileApiClient: vi.fn(() => ({+ bootstrap: apiMock.bootstrap,+ getAuthConfig: apiMock.getAuthConfig,+ revokeSession: vi.fn(() => Promise.resolve({ success: true })),+ setActiveOrganization: vi.fn(),+ })),+ createSessionRequestUrl: vi.fn(+ () => "https://cap.so/api/mobile/session/request",+ ),+}));++(+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const flushMicrotasks = async () => {+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+};++const states: Array<{+ apiKey: string | null;+ status: string;+ userId: string | null;+}> = [];++const Probe = () => {+ const auth = useAuth();+ states.push({+ apiKey: auth.apiKey,+ status: auth.status,+ userId: auth.userId,+ });+ return null;+};++describe("AuthProvider", () => {+ beforeEach(() => {+ states.length = 0;+ secureStoreMock.deleteItemAsync.mockClear();+ secureStoreMock.getItemAsync.mockReset();+ secureStoreMock.getItemAsync.mockResolvedValue(null);+ secureStoreMock.setItemAsync.mockClear();+ apiMock.bootstrap.mockReset();+ apiMock.bootstrap.mockResolvedValue({+ activeOrganizationId: "org_123",+ user: {+ email: "[email protected]",+ name: "Richie",+ },+ });+ apiMock.getAuthConfig.mockReset();+ apiMock.getAuthConfig.mockResolvedValue({+ googleAuthAvailable: true,+ workosAuthAvailable: true,+ });+ });++ it("clears an orphaned stored user id when no API key is stored", async () => {+ secureStoreMock.getItemAsync.mockImplementation((key: string) =>+ Promise.resolve(key === "cap.mobile.userId" ? "user_123" : null),+ );++ await act(async () => {+ TestRenderer.create(+ React.createElement(AuthProvider, null, React.createElement(Probe)),+ );+ await flushMicrotasks();+ });++ expect(states.at(-1)).toMatchObject({+ apiKey: null,+ status: "signedOut",+ userId: null,+ });+ expect(secureStoreMock.deleteItemAsync).toHaveBeenCalledWith(+ "cap.mobile.userId",+ );+ });++ it("clears the stored user id when bootstrapping a stored session fails", async () => {+ secureStoreMock.getItemAsync.mockImplementation((key: string) => {+ if (key === "cap.mobile.apiKey") return Promise.resolve("key_123");+ if (key === "cap.mobile.userId") return Promise.resolve("user_123");+ return Promise.resolve(null);+ });+ apiMock.bootstrap.mockRejectedValueOnce(new Error("Session expired"));++ await act(async () => {+ TestRenderer.create(+ React.createElement(AuthProvider, null, React.createElement(Probe)),+ );+ await flushMicrotasks();+ });++ expect(states.at(-1)).toMatchObject({+ apiKey: null,+ status: "signedOut",+ userId: null,+ });+ expect(secureStoreMock.deleteItemAsync).toHaveBeenCalledWith(+ "cap.mobile.apiKey",+ );+ expect(secureStoreMock.deleteItemAsync).toHaveBeenCalledWith(+ "cap.mobile.userId",+ );+ });+});diff --git a/apps/mobile/src/auth/SignInPanel.test.tsx b/apps/mobile/src/auth/SignInPanel.test.tsxnew file mode 100644index 000000000..9970dfb9c--- /dev/null+++ b/apps/mobile/src/auth/SignInPanel.test.tsx@@ -0,0 +1,1234 @@+import React, { type ReactElement, type ReactNode } from "react";+import TestRenderer, {+ act,+ type ReactTestRenderer,+ type ReactTestRendererJSON,+} from "react-test-renderer";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { SignInPanel } from "./SignInPanel";++type HostProps = {+ children?: ReactNode;+ [key: string]: unknown;+};++type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;++const authFns = vi.hoisted(() => ({+ authConfig: {+ googleAuthAvailable: true,+ workosAuthAvailable: true,+ },+ requestEmailCode: vi.fn(() => Promise.resolve()),+ signInWithGoogle: vi.fn(),+ signInWithSso: vi.fn(),+ verifyEmailCode: vi.fn(),+}));++(+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const renderTree = async (node: ReactElement): Promise<JsonNode> => {+ let renderer: ReactTestRenderer | null = null;+ await act(async () => {+ renderer = TestRenderer.create(node);+ });+ return (renderer as ReactTestRenderer | null)?.toJSON() ?? null;+};++const renderPanel = async (): Promise<ReactTestRenderer> => {+ let renderer: ReactTestRenderer | null = null;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(SignInPanel));+ });+ return renderer as unknown as ReactTestRenderer;+};++const getTextNodes = (node: JsonNode): string[] => {+ if (!node) return [];+ if (typeof node === "string") return [node];+ if (Array.isArray(node)) return node.flatMap(getTextNodes);+ return node.children?.flatMap(getTextNodes) ?? [];+};++const hasProp = (node: JsonNode, prop: string, value: unknown): boolean => {+ if (!node || typeof node === "string") return false;+ if (Array.isArray(node))+ return node.some((item) => hasProp(item, prop, value));+ if (node.props[prop] === value) return true;+ return node.children?.some((child) => hasProp(child, prop, value)) ?? false;+};++const hasStyle = (+ node: JsonNode,+ expected: Record<string, unknown>,+): boolean => {+ if (!node || typeof node === "string") return false;+ if (Array.isArray(node)) return node.some((item) => hasStyle(item, expected));+ const styles = Array.isArray(node.props.style)+ ? node.props.style+ : [node.props.style];+ const resolved = Object.assign({}, ...styles.filter(Boolean));+ if (+ Object.entries(expected).every(([key, value]) => resolved[key] === value)+ ) {+ return true;+ }+ return node.children?.some((child) => hasStyle(child, expected)) ?? false;+};++const resolveStyle = (+ style: unknown,+ pressed = false,+): Record<string, unknown> => {+ const resolved = typeof style === "function" ? style({ pressed }) : style;+ const styles = Array.isArray(resolved) ? resolved : [resolved];+ return Object.assign({}, ...styles.filter(Boolean));+};++vi.mock("react-native", async () => {+ const React = await import("react");+ const createHost =+ (name: string) =>+ ({ children, ...props }: HostProps) =>+ React.createElement(name, props, children);+ const TextInput = React.forwardRef<unknown, HostProps>(+ ({ children, ...props }, ref) =>+ React.createElement(+ "TextInput",+ { ...props, ref },+ children as ReactNode,+ ),+ );++ return {+ ActivityIndicator: createHost("ActivityIndicator"),+ Pressable: createHost("Pressable"),+ StyleSheet: {+ create: <T extends Record<string, unknown>>(styles: T) => styles,+ hairlineWidth: 1,+ },+ Text: createHost("Text"),+ TextInput,+ View: createHost("View"),+ };+});++vi.mock("expo-symbols", () => ({+ SymbolView: () => null,+}));++vi.mock("expo-web-browser", () => ({+ openBrowserAsync: vi.fn(),+}));++vi.mock("@/components/GlassSurface", async () => {+ const React = await import("react");+ return {+ GlassSurface: ({ children }: { children?: ReactNode }) =>+ React.createElement("GlassSurface", null, children),+ };+});++vi.mock("react-native-svg", async () => {+ const React = await import("react");+ const Svg = ({ children, ...props }: HostProps) =>+ React.createElement("Svg", props, children);++ return {+ default: Svg,+ Path: (props: HostProps) => React.createElement("Path", props),+ Rect: (props: HostProps) => React.createElement("Rect", props),+ };+});++vi.mock("@/auth/AuthContext", () => ({+ apiBaseUrl: "https://cap.so",+ useAuth: () => ({+ authConfig: authFns.authConfig,+ requestEmailCode: authFns.requestEmailCode,+ signInWithGoogle: authFns.signInWithGoogle,+ signInWithSso: authFns.signInWithSso,+ verifyEmailCode: authFns.verifyEmailCode,+ }),+}));++vi.mock("@/api/mobile", () => ({+ MobileApiError: class MobileApiError extends Error {+ status: number;+ payload: unknown;++ constructor(message: string, status: number, payload: unknown) {+ super(message);+ this.status = status;+ this.payload = payload;+ }+ },+}));++describe("SignInPanel", () => {+ beforeEach(() => {+ authFns.authConfig.googleAuthAvailable = true;+ authFns.authConfig.workosAuthAvailable = true;+ authFns.requestEmailCode.mockReset();+ authFns.requestEmailCode.mockResolvedValue(undefined);+ authFns.verifyEmailCode.mockReset();+ authFns.verifyEmailCode.mockResolvedValue(undefined);+ authFns.signInWithGoogle.mockReset();+ authFns.signInWithGoogle.mockResolvedValue(undefined);+ authFns.signInWithSso.mockReset();+ authFns.signInWithSso.mockResolvedValue(undefined);+ });++ it("renders the Cap web login surface", async () => {+ const tree = await renderTree(React.createElement(SignInPanel));+ const text = getTextNodes(tree);++ expect(text).toContain("Sign in to Cap");+ expect(text).toContain("Your videos, organized and ready to share.");+ expect(hasProp(tree, "viewBox", "0 0 40 40")).toBe(true);+ expect(hasProp(tree, "rx", 8)).toBe(true);+ expect(hasProp(tree, "placeholder", "[email protected]")).toBe(true);+ expect(hasProp(tree, "accessibilityLabel", "Email address")).toBe(true);+ expect(+ hasProp(+ tree,+ "accessibilityHint",+ "Enter your email to request a verification code",+ ),+ ).toBe(true);+ expect(hasProp(tree, "clearButtonMode", "while-editing")).toBe(true);+ expect(hasProp(tree, "enablesReturnKeyAutomatically", true)).toBe(true);+ expect(hasProp(tree, "selectionColor", "#0090ff")).toBe(true);+ expect(+ hasProp(+ tree,+ "accessibilityHint",+ "Enter a valid email address to continue",+ ),+ ).toBe(true);+ expect(text).toContain("Login with email");+ expect(text).toContain("Sign up here");+ expect(+ hasProp(tree, "accessibilityHint", "Opens sign up in a browser sheet"),+ ).toBe(true);+ expect(hasProp(tree, "accessibilityRole", "link")).toBe(true);+ expect(text).toContain("OR");+ expect(text).toContain("Login with Google");+ expect(text).toContain("Login with SAML SSO");+ expect(text).toContain("Terms of Service");+ expect(text).toContain("Privacy Policy");+ expect(+ hasProp(+ tree,+ "accessibilityHint",+ "Opens Terms of Service in a browser sheet",+ ),+ ).toBe(true);+ expect(+ hasProp(+ tree,+ "accessibilityHint",+ "Opens Privacy Policy in a browser sheet",+ ),+ ).toBe(true);+ });++ it("hides unavailable provider options", async () => {+ authFns.authConfig.googleAuthAvailable = false;+ authFns.authConfig.workosAuthAvailable = false;++ const tree = await renderTree(React.createElement(SignInPanel));+ const text = getTextNodes(tree);++ expect(text).toContain("Login with email");+ expect(text).not.toContain("OR");+ expect(text).not.toContain("Login with Google");+ expect(text).not.toContain("Login with SAML SSO");+ });++ it("shows the native SSO organization step", async () => {+ const renderer = await renderPanel();+ const [ssoButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with SAML SSO",+ });+ if (!ssoButton) throw new Error("SSO button was not rendered");++ await act(async () => {+ ssoButton.props.onPress();+ });++ const tree = renderer.toJSON();+ const text = getTextNodes(tree);++ expect(hasProp(tree, "placeholder", "Enter your Organization ID...")).toBe(+ true,+ );+ expect(hasProp(tree, "accessibilityLabel", "Organization ID")).toBe(true);+ expect(+ hasProp(+ tree,+ "accessibilityHint",+ "Enter your organization ID to continue with SSO",+ ),+ ).toBe(true);+ expect(hasProp(tree, "clearButtonMode", "while-editing")).toBe(true);+ expect(hasProp(tree, "selectionColor", "#0090ff")).toBe(true);+ expect(+ hasProp(+ tree,+ "accessibilityHint",+ "Enter your organization ID to continue",+ ),+ ).toBe(true);+ const [continueButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Continue with SSO",+ });+ expect(continueButton?.props.accessibilityValue).toEqual({+ text: "Organization ID required",+ });+ expect(text).toContain("Continue with SSO");+ expect(text).toContain("Back");+ });++ it("locks the SSO back button while starting sign in", async () => {+ let resolveSso: (() => void) | null = null;+ authFns.signInWithSso.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ resolveSso = resolve;+ }),+ );+ const renderer = await renderPanel();+ const [ssoButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with SAML SSO",+ });+ if (!ssoButton) throw new Error("SSO button was not rendered");++ await act(async () => {+ ssoButton.props.onPress();+ });++ const [organizationInput] = renderer.root.findAllByProps({+ accessibilityLabel: "Organization ID",+ });+ if (!organizationInput)+ throw new Error("Organization ID input was not rendered");+ await act(async () => {+ organizationInput.props.onChangeText("acme");+ });++ const [continueButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Continue with SSO",+ });+ if (!continueButton)+ throw new Error("SSO continue button was not rendered");+ expect(continueButton.props.accessibilityHint).toBe(+ "Starts SAML SSO for this organization",+ );+ await act(async () => {+ void continueButton.props.onPress();+ await Promise.resolve();+ });++ const [loadingBackButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Back",+ });+ const [loadingOrganizationInput] = renderer.root.findAllByProps({+ accessibilityLabel: "Organization ID",+ });+ const [loadingContinueButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Continue with SSO",+ });+ expect(loadingBackButton?.props.disabled).toBe(true);+ expect(loadingBackButton?.props.accessibilityState).toEqual({+ disabled: true,+ });+ expect(loadingBackButton?.props.accessibilityHint).toBe(+ "Sign in is in progress",+ );+ expect(loadingBackButton?.props.accessibilityValue).toEqual({+ text: "Starting SAML SSO sign in",+ });+ expect(loadingOrganizationInput?.props.editable).toBe(false);+ expect(loadingOrganizationInput?.props.accessibilityState).toEqual({+ disabled: true,+ });+ expect(loadingOrganizationInput?.props.accessibilityValue).toEqual({+ text: "Starting SAML SSO sign in",+ });+ expect(loadingContinueButton?.props.accessibilityHint).toBe(+ "SAML SSO sign in is starting",+ );+ expect(loadingContinueButton?.props.accessibilityState).toEqual({+ busy: true,+ disabled: true,+ });+ expect(loadingContinueButton?.props.accessibilityValue).toEqual({+ text: "Starting SAML SSO sign in",+ });+ expect(getTextNodes(renderer.toJSON())).toContain("Continue with SSO");+ expect(getTextNodes(renderer.toJSON())).not.toContain("Starting SSO...");++ await act(async () => {+ organizationInput.props.onChangeText("changed");+ });++ const [unchangedOrganizationInput] = renderer.root.findAllByProps({+ accessibilityLabel: "Organization ID",+ });+ expect(unchangedOrganizationInput?.props.value).toBe("acme");++ await act(async () => {+ resolveSso?.();+ await Promise.resolve();+ });+ });++ it("does not request an email code for an invalid email address", async () => {+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("richie");+ });+ expect(emailButton.props.accessibilityHint).toBe(+ "Enter a valid email address to continue",+ );+ const [invalidEmailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ expect(invalidEmailButton?.props.accessibilityValue).toEqual({+ text: "Email address is not valid",+ });+ expect(emailButton.props.accessibilityState).toEqual({+ busy: false,+ disabled: true,+ });+ await act(async () => {+ await emailButton.props.onPress();+ });++ expect(authFns.requestEmailCode).not.toHaveBeenCalled();+ });++ it("locks the email field while requesting a verification code", async () => {+ let resolveRequest: (() => void) | null = null;+ authFns.requestEmailCode.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ resolveRequest = resolve;+ }),+ );+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });+ await act(async () => {+ void emailButton.props.onPress();+ await Promise.resolve();+ });++ const [loadingEmailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [loadingEmailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ expect(loadingEmailInput?.props.editable).toBe(false);+ expect(loadingEmailInput?.props.accessibilityState).toEqual({+ disabled: true,+ });+ expect(loadingEmailInput?.props.accessibilityValue).toEqual({+ text: "Sending verification code",+ });+ expect(loadingEmailButton?.props.accessibilityHint).toBe(+ "Sending verification code",+ );+ expect(loadingEmailButton?.props.accessibilityState).toEqual({+ busy: true,+ disabled: true,+ });+ expect(loadingEmailButton?.props.accessibilityValue).toEqual({+ text: "Sending verification code",+ });+ expect(getTextNodes(renderer.toJSON())).toContain("Login with email");+ expect(getTextNodes(renderer.toJSON())).not.toContain("Sending...");++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });++ const [unchangedEmailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ expect(unchangedEmailInput?.props.value).toBe("[email protected]");++ await act(async () => {+ resolveRequest?.();+ await Promise.resolve();+ });+ });++ it("locks browser links while requesting a verification code", async () => {+ let resolveRequest: (() => void) | null = null;+ authFns.requestEmailCode.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ resolveRequest = resolve;+ }),+ );+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });+ await act(async () => {+ void emailButton.props.onPress();+ await Promise.resolve();+ });++ const WebBrowser = await import("expo-web-browser");+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);+ openBrowserAsync.mockClear();+ const [signupLink, termsLink, privacyLink] = renderer.root.findAllByProps({+ accessibilityRole: "link",+ });+ if (!signupLink || !termsLink || !privacyLink) {+ throw new Error("Browser links were not rendered");+ }++ expect(signupLink.props.accessibilityState).toEqual({ disabled: true });+ expect(signupLink.props.accessibilityHint).toBe("Sign in is in progress");+ expect(signupLink.props.accessibilityValue).toEqual({+ text: "Sending verification code",+ });+ expect(termsLink.props.accessibilityState).toEqual({ disabled: true });+ expect(termsLink.props.accessibilityHint).toBe("Sign in is in progress");+ expect(termsLink.props.accessibilityValue).toEqual({+ text: "Sending verification code",+ });+ expect(privacyLink.props.accessibilityState).toEqual({ disabled: true });+ expect(privacyLink.props.accessibilityHint).toBe("Sign in is in progress");+ expect(privacyLink.props.accessibilityValue).toEqual({+ text: "Sending verification code",+ });++ await act(async () => {+ signupLink.props.onPress();+ termsLink.props.onPress();+ privacyLink.props.onPress();+ });++ expect(openBrowserAsync).not.toHaveBeenCalled();++ await act(async () => {+ resolveRequest?.();+ await Promise.resolve();+ });+ });++ it("deduplicates sign-in actions while a provider request is pending", async () => {+ let resolveGoogle: (() => void) | null = null;+ authFns.signInWithGoogle.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ resolveGoogle = resolve;+ }),+ );+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ if (!emailInput) throw new Error("Email input was not rendered");++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });++ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ const [googleButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with Google",+ });+ const [ssoButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with SAML SSO",+ });+ const [signupLink] = renderer.root.findAllByProps({+ accessibilityHint: "Opens sign up in a browser sheet",+ });+ const [termsLink] = renderer.root.findAllByProps({+ accessibilityHint: "Opens Terms of Service in a browser sheet",+ });+ const [privacyLink] = renderer.root.findAllByProps({+ accessibilityHint: "Opens Privacy Policy in a browser sheet",+ });+ if (+ !emailButton ||+ !googleButton ||+ !ssoButton ||+ !signupLink ||+ !termsLink ||+ !privacyLink+ ) {+ throw new Error("Sign-in actions were not rendered");+ }++ await act(async () => {+ void googleButton.props.onPress();+ await Promise.resolve();+ });++ const [loadingEmailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ const [loadingGoogleButton] = renderer.root.findAll(+ (node) =>+ node.props.accessibilityLabel === "Login with Google" &&+ node.props.accessibilityHint === "Google sign in is starting",+ );+ const [loadingSsoButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with SAML SSO",+ });+ expect(loadingEmailButton?.props.disabled).toBe(true);+ expect(loadingEmailButton?.props.accessibilityHint).toBe(+ "Sign in is in progress",+ );+ expect(loadingEmailButton?.props.accessibilityValue).toEqual({+ text: "Starting Google sign in",+ });+ expect(loadingGoogleButton?.props.accessibilityHint).toBe(+ "Google sign in is starting",+ );+ expect(loadingGoogleButton?.props.accessibilityState).toEqual({+ busy: true,+ disabled: true,+ });+ expect(loadingGoogleButton?.props.accessibilityValue).toEqual({+ text: "Starting Google sign in",+ });+ expect(getTextNodes(renderer.toJSON())).toContain("Login with Google");+ expect(getTextNodes(renderer.toJSON())).not.toContain("Starting Google...");+ expect(loadingSsoButton?.props.disabled).toBe(true);+ expect(loadingSsoButton?.props.accessibilityHint).toBe(+ "Sign in is in progress",+ );+ expect(loadingSsoButton?.props.accessibilityValue).toEqual({+ text: "Starting Google sign in",+ });++ const WebBrowser = await import("expo-web-browser");+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);+ openBrowserAsync.mockClear();++ await act(async () => {+ googleButton.props.onPress();+ emailButton.props.onPress();+ ssoButton.props.onPress();+ signupLink.props.onPress();+ termsLink.props.onPress();+ privacyLink.props.onPress();+ await Promise.resolve();+ });++ expect(authFns.signInWithGoogle).toHaveBeenCalledTimes(1);+ expect(authFns.requestEmailCode).not.toHaveBeenCalled();+ expect(openBrowserAsync).not.toHaveBeenCalled();+ expect(getTextNodes(renderer.toJSON())).not.toContain("Continue with SSO");++ await act(async () => {+ resolveGoogle?.();+ await Promise.resolve();+ });+ });++ it("marks a failed Google sign-in as retryable", async () => {+ authFns.signInWithGoogle.mockRejectedValueOnce(+ new Error("Google unavailable"),+ );+ const renderer = await renderPanel();+ const [googleButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with Google",+ });+ if (!googleButton) throw new Error("Google button was not rendered");++ await act(async () => {+ await googleButton.props.onPress();+ });++ expect(getTextNodes(renderer.toJSON())).toContain("Google unavailable");+ const [retryGoogleButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Retry Google sign in",+ });+ const [errorAlert] = renderer.root.findAllByProps({+ accessibilityRole: "alert",+ });+ expect(retryGoogleButton?.props.accessibilityHint).toBe(+ "Google unavailable",+ );+ expect(retryGoogleButton?.props.accessibilityValue).toEqual({+ text: "Google unavailable",+ });+ expect(errorAlert?.props.accessibilityLabel).toBe(+ "Sign-in error: Google unavailable",+ );++ await act(async () => {+ await retryGoogleButton?.props.onPress();+ });++ expect(authFns.signInWithGoogle).toHaveBeenCalledTimes(2);+ expect(getTextNodes(renderer.toJSON())).not.toContain("Google unavailable");+ expect(+ renderer.root.findAllByProps({+ accessibilityLabel: "Retry Google sign in",+ }),+ ).toHaveLength(0);+ });++ it("marks a failed SSO sign-in on the organization step", async () => {+ authFns.signInWithSso.mockRejectedValueOnce(new Error("SSO unavailable"));+ const renderer = await renderPanel();+ const [ssoButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with SAML SSO",+ });+ if (!ssoButton) throw new Error("SSO button was not rendered");++ await act(async () => {+ ssoButton.props.onPress();+ });++ const [organizationInput] = renderer.root.findAllByProps({+ accessibilityLabel: "Organization ID",+ });+ if (!organizationInput)+ throw new Error("Organization ID input was not rendered");+ await act(async () => {+ organizationInput.props.onChangeText("acme");+ });++ const [continueButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Continue with SSO",+ });+ if (!continueButton)+ throw new Error("SSO continue button was not rendered");+ await act(async () => {+ await continueButton.props.onPress();+ });++ expect(getTextNodes(renderer.toJSON())).toContain("SSO unavailable");+ const [organizationInputAfterError] = renderer.root.findAllByProps({+ accessibilityLabel: "Organization ID",+ });+ const [retrySsoButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Retry SAML SSO sign in",+ });+ const [errorAlert] = renderer.root.findAllByProps({+ accessibilityRole: "alert",+ });+ expect(organizationInputAfterError?.props.accessibilityHint).toBe(+ "SSO unavailable",+ );+ expect(retrySsoButton?.props.accessibilityHint).toBe("SSO unavailable");+ expect(retrySsoButton?.props.accessibilityValue).toEqual({+ text: "SSO unavailable",+ });+ expect(errorAlert?.props.accessibilityLabel).toBe(+ "Sign-in error: SSO unavailable",+ );+ expect(+ hasStyle(renderer.toJSON(), {+ borderColor: "#f4a9aa",+ }),+ ).toBe(true);++ await act(async () => {+ await retrySsoButton?.props.onPress();+ });++ expect(authFns.signInWithSso).toHaveBeenCalledTimes(2);+ expect(getTextNodes(renderer.toJSON())).not.toContain("SSO unavailable");+ expect(+ renderer.root.findAllByProps({+ accessibilityLabel: "Retry SAML SSO sign in",+ }),+ ).toHaveLength(0);+ });++ it("shows the right error when an email is not allowed", async () => {+ const { MobileApiError } = await import("@/api/mobile");+ authFns.requestEmailCode.mockRejectedValueOnce(+ new MobileApiError("Forbidden", 403, null),+ );+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });+ await act(async () => {+ await emailButton.props.onPress();+ });++ expect(getTextNodes(renderer.toJSON())).toContain(+ "This email cannot be used to sign in to Cap.",+ );+ const [emailInputAfterError] = renderer.root.findAllByProps({+ accessibilityLabel: "Email address",+ });+ const [errorAlert] = renderer.root.findAllByProps({+ accessibilityRole: "alert",+ });+ expect(emailInputAfterError?.props.accessibilityHint).toBe(+ "This email cannot be used to sign in to Cap.",+ );+ const [emailButtonAfterError] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ expect(emailButtonAfterError?.props.accessibilityValue).toEqual({+ text: "This email cannot be used to sign in to Cap.",+ });+ expect(errorAlert?.props.accessibilityLabel).toBe(+ "Sign-in error: This email cannot be used to sign in to Cap.",+ );+ expect(errorAlert?.props.accessibilityLiveRegion).toBe("polite");+ expect(+ hasStyle(renderer.toJSON(), {+ borderColor: "#f4a9aa",+ }),+ ).toBe(true);+ expect(+ hasStyle(renderer.toJSON(), {+ backgroundColor: "#fffcfc",+ borderColor: "#fdbdbe",+ }),+ ).toBe(true);+ });++ it("switches to a web-like verification code step after requesting email", async () => {+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });+ await act(async () => {+ await emailButton.props.onPress();+ });++ const tree = renderer.toJSON();+ const text = getTextNodes(tree);++ expect(authFns.requestEmailCode).toHaveBeenCalledWith("[email protected]");+ expect(text).toContain("Back");+ expect(text).toContain("Enter verification code");+ expect(text).toContain("We sent a 6-digit code to [email protected]");+ expect(text).toContain("Verify Code");+ expect(text).toContain("Resend in 30s");+ expect(text).toContain("Terms of Service");+ expect(hasProp(tree, "accessibilityLabel", "Verification code")).toBe(true);+ const [codeTarget] = renderer.root.findAllByProps({+ accessibilityLabel: "Verification code",+ });+ const [verifyButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Verify Code",+ });+ const [resendButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Resend in 30s",+ });+ const [codeInput] = renderer.root.findAllByProps({+ textContentType: "oneTimeCode",+ });+ if (!codeInput) throw new Error("One-time code input was not rendered");+ expect(codeTarget?.props.accessibilityValue).toEqual({+ text: "0 of 6 digits entered",+ });+ expect(verifyButton?.props.accessibilityValue).toEqual({+ text: "0 of 6 digits entered",+ });+ expect(resolveStyle(verifyButton?.props.style)).toMatchObject({+ backgroundColor: "#d9d9d9",+ borderColor: "#d9d9d9",+ });+ expect(resendButton?.props.accessibilityValue).toEqual({+ text: "Wait 30 seconds",+ });+ expect(hasStyle(tree, { gap: 20, paddingTop: 2 })).toBe(true);+ expect(+ hasProp(tree, "accessibilityHint", "Tap to enter the 6-digit code"),+ ).toBe(true);+ expect(+ hasProp(tree, "accessibilityHint", "Enter the 6-digit code to continue"),+ ).toBe(true);+ expect(hasProp(tree, "accessibilityHint", "Returns to email sign in")).toBe(+ true,+ );+ expect(hasProp(tree, "accessibilityElementsHidden", true)).toBe(true);+ expect(hasProp(tree, "accessible", false)).toBe(true);+ expect(+ hasProp(tree, "importantForAccessibility", "no-hide-descendants"),+ ).toBe(true);+ expect(hasProp(tree, "selectionColor", "#0090ff")).toBe(true);+ await act(async () => {+ codeInput.props.onFocus();+ });+ expect(+ hasStyle(renderer.toJSON(), {+ backgroundColor: "#f9f9f9",+ borderColor: "#0090ff",+ shadowOpacity: 0.12,+ }),+ ).toBe(true);+ await act(async () => {+ codeInput.props.onBlur();+ });+ expect(+ hasStyle(renderer.toJSON(), {+ backgroundColor: "#f9f9f9",+ borderColor: "#0090ff",+ shadowOpacity: 0.12,+ }),+ ).toBe(false);+ expect(text).not.toContain("Login with Google");+ });++ it("verifies an autofilled one-time code when all six digits are entered", async () => {+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });+ await act(async () => {+ await emailButton.props.onPress();+ });++ const [codeInput] = renderer.root.findAllByProps({+ textContentType: "oneTimeCode",+ });+ if (!codeInput) throw new Error("One-time code input was not rendered");++ await act(async () => {+ codeInput.props.onChangeText("123-456");+ await Promise.resolve();+ });++ expect(authFns.verifyEmailCode).toHaveBeenCalledWith(+ "[email protected]",+ "123456",+ );+ });++ it("marks invalid verification codes on the visible code target", async () => {+ const { MobileApiError } = await import("@/api/mobile");+ authFns.verifyEmailCode.mockRejectedValueOnce(+ new MobileApiError("Forbidden", 403, null),+ );+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });+ await act(async () => {+ await emailButton.props.onPress();+ });++ const [codeInput] = renderer.root.findAllByProps({+ textContentType: "oneTimeCode",+ });+ if (!codeInput) throw new Error("One-time code input was not rendered");++ await act(async () => {+ codeInput.props.onChangeText("123456");+ await Promise.resolve();+ });++ expect(getTextNodes(renderer.toJSON())).toContain(+ "That code is invalid or expired.",+ );+ const [codeTarget] = renderer.root.findAllByProps({+ accessibilityLabel: "Verification code",+ });+ const [errorAlert] = renderer.root.findAllByProps({+ accessibilityRole: "alert",+ });+ expect(codeTarget?.props.accessibilityHint).toBe(+ "That code is invalid or expired.",+ );+ expect(codeTarget?.props.accessibilityValue).toEqual({+ text: "0 of 6 digits entered",+ });+ expect(errorAlert?.props.accessibilityLabel).toBe(+ "Sign-in error: That code is invalid or expired.",+ );+ expect(+ hasStyle(renderer.toJSON(), {+ backgroundColor: "#fffcfc",+ borderColor: "#f4a9aa",+ }),+ ).toBe(true);+ });++ it("locks the visible code entry target while verifying", async () => {+ let resolveVerify: (() => void) | null = null;+ authFns.verifyEmailCode.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ resolveVerify = resolve;+ }),+ );+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });+ await act(async () => {+ await emailButton.props.onPress();+ });++ const [codeInput] = renderer.root.findAllByProps({+ textContentType: "oneTimeCode",+ });+ if (!codeInput) throw new Error("One-time code input was not rendered");++ await act(async () => {+ codeInput.props.onChangeText("123456");+ await Promise.resolve();+ });++ const [codeTarget] = renderer.root.findAllByProps({+ accessibilityLabel: "Verification code",+ });+ const [loadingBackButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Back",+ });+ const [loadingCodeInput] = renderer.root.findAllByProps({+ textContentType: "oneTimeCode",+ });+ const [loadingVerifyButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Verify Code",+ });+ expect(codeTarget?.props.disabled).toBe(true);+ expect(codeTarget?.props.accessibilityState).toEqual({+ busy: true,+ disabled: true,+ });+ expect(codeTarget?.props.accessibilityHint).toBe("Verifying code");+ expect(codeTarget?.props.accessibilityValue).toEqual({+ text: "Verifying code",+ });+ expect(loadingBackButton?.props.accessibilityHint).toBe(+ "Sign in is in progress",+ );+ expect(loadingBackButton?.props.accessibilityValue).toEqual({+ text: "Verifying code",+ });+ expect(loadingCodeInput?.props.editable).toBe(false);+ expect(loadingVerifyButton?.props.accessibilityHint).toBe("Verifying code");+ expect(loadingVerifyButton?.props.accessibilityValue).toEqual({+ text: "Verifying code",+ });+ expect(loadingVerifyButton?.props.accessibilityState).toEqual({+ busy: true,+ disabled: true,+ });+ expect(getTextNodes(renderer.toJSON())).not.toContain("Verifying...");++ await act(async () => {+ codeInput.props.onChangeText("654321");+ await Promise.resolve();+ });++ const [unchangedCodeInput] = renderer.root.findAllByProps({+ textContentType: "oneTimeCode",+ });+ expect(unchangedCodeInput?.props.value).toBe("123456");+ expect(authFns.verifyEmailCode).toHaveBeenCalledTimes(1);++ await act(async () => {+ resolveVerify?.();+ await Promise.resolve();+ });+ });++ it("prevents repeated email code requests during the resend cooldown", async () => {+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });+ await act(async () => {+ await emailButton.props.onPress();+ });++ const [resendButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Resend in 30s",+ });+ if (!resendButton) throw new Error("Resend control was not rendered");++ expect(resendButton.props.accessibilityState).toEqual({+ busy: false,+ disabled: true,+ });+ expect(resendButton.props.accessibilityHint).toBe(+ "Wait 30 seconds before requesting a new code",+ );+ expect(resendButton.props.accessibilityValue).toEqual({+ text: "Wait 30 seconds",+ });+ expect(resendButton.props.hitSlop).toBe(6);+ expect(+ hasStyle(renderer.toJSON(), {+ color: "#8d8d8d",+ textDecorationLine: "none",+ }),+ ).toBe(true);++ await act(async () => {+ await resendButton.props.onPress();+ });++ expect(authFns.requestEmailCode).toHaveBeenCalledTimes(1);+ expect(getTextNodes(renderer.toJSON())).toContain(+ "Please wait 30 seconds before requesting a new code.",+ );+ });++ it("allows a corrected email to request a code without waiting for the previous cooldown", async () => {+ const renderer = await renderPanel();+ const [emailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [emailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!emailInput || !emailButton) {+ throw new Error("Email sign in controls were not rendered");+ }++ await act(async () => {+ emailInput.props.onChangeText("[email protected]");+ });+ await act(async () => {+ await emailButton.props.onPress();+ });++ const [backButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Back",+ });+ if (!backButton) throw new Error("Back button was not rendered");++ await act(async () => {+ backButton.props.onPress();+ });++ const [correctedEmailInput] = renderer.root.findAllByProps({+ placeholder: "[email protected]",+ });+ const [correctedEmailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ if (!correctedEmailInput || !correctedEmailButton) {+ throw new Error("Corrected email sign in controls were not rendered");+ }++ await act(async () => {+ correctedEmailInput.props.onChangeText("[email protected]");+ });++ const [readyEmailButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Login with email",+ });+ expect(readyEmailButton?.props.accessibilityState).toEqual({+ busy: false,+ disabled: false,+ });++ await act(async () => {+ await readyEmailButton?.props.onPress();+ });++ expect(authFns.requestEmailCode).toHaveBeenNthCalledWith(1, "[email protected]");+ expect(authFns.requestEmailCode).toHaveBeenNthCalledWith(2, "[email protected]");+ });+});diff --git a/apps/mobile/src/auth/SignInPanel.tsx b/apps/mobile/src/auth/SignInPanel.tsxnew file mode 100644index 000000000..27f6f3eae--- /dev/null+++ b/apps/mobile/src/auth/SignInPanel.tsx@@ -0,0 +1,1053 @@+import { SymbolView } from "expo-symbols";+import * as WebBrowser from "expo-web-browser";+import { useEffect, useRef, useState } from "react";+import { Pressable, StyleSheet, Text, TextInput, View } from "react-native";+import Svg, { Path } from "react-native-svg";+import { MobileApiError } from "@/api/mobile";+import { ActionButton } from "@/components/ActionButton";+import { CapLogoBadge } from "@/components/CapLogoBadge";+import { GlassSurface } from "@/components/GlassSurface";+import { colors, fonts, radius, squircle } from "@/theme";+import { apiBaseUrl, useAuth } from "./AuthContext";++type SignInPanelProps = {+ title?: string;+ subtitle?: string;+};++const codePattern = /^\d{6}$/;+const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;+const emailCodeCooldownMs = 30_000;+const codeSlots = ["code-0", "code-1", "code-2", "code-3", "code-4", "code-5"];+type FocusedInput = "code" | "email" | "sso" | null;+type LoadingKind = "email" | "code" | "google" | "sso";+type SignInError = {+ message: string;+ source: LoadingKind | "resend";+};++const getEmailRequestErrorMessage = (error: unknown) => {+ if (error instanceof MobileApiError) {+ if (error.status === 400) return "Enter a valid email address.";+ if (error.status === 403) {+ return "This email cannot be used to sign in to Cap.";+ }+ }+ return error instanceof Error+ ? error.message+ : "Unable to send a code. Try again.";+};++const getCodeVerificationErrorMessage = (error: unknown) => {+ if (error instanceof MobileApiError) {+ if (error.status === 400) return "Enter a valid email and 6-digit code.";+ if (error.status === 403) return "That code is invalid or expired.";+ }+ return error instanceof Error ? error.message : "Unable to verify that code.";+};++const getProviderErrorMessage = (error: unknown, fallback: string) => {+ return error instanceof Error ? error.message : fallback;+};++const openWebPath = (path: string) => {+ void WebBrowser.openBrowserAsync(new URL(path, apiBaseUrl).toString());+};++function GoogleMark() {+ return (+ <Svg width={16} height={16} viewBox="-3 0 262 262">+ <Path+ d="M255.878 133.451c0-10.734-.871-18.567-2.756-26.69H130.55v48.448h71.947c-1.45 12.04-9.283 30.172-26.69 42.356l-.244 1.622 38.755 30.023 2.685.268c24.659-22.774 38.875-56.282 38.875-96.027"+ fill="#4285F4"+ />+ <Path+ d="M130.55 261.1c35.248 0 64.839-11.605 86.453-31.622l-41.196-31.913c-11.024 7.688-25.82 13.055-45.257 13.055-34.523 0-63.824-22.773-74.269-54.25l-1.531.13-40.298 31.187-.527 1.465C35.393 231.798 79.49 261.1 130.55 261.1"+ fill="#34A853"+ />+ <Path+ d="M56.281 156.37c-2.756-8.123-4.351-16.827-4.351-25.82 0-8.994 1.595-17.697 4.206-25.82l-.073-1.73L15.26 71.312l-1.335.635C5.077 89.644 0 109.517 0 130.55s5.077 40.905 13.925 58.602l42.356-32.782"+ fill="#FBBC05"+ />+ <Path+ d="M130.55 50.479c24.514 0 41.05 10.589 50.479 19.438l36.844-35.974C195.245 12.91 165.798 0 130.55 0 79.49 0 35.393 29.301 13.925 71.947l42.211 32.783c10.59-31.477 39.891-54.251 74.414-54.251"+ fill="#EB4335"+ />+ </Svg>+ );+}++export function SignInPanel({+ title = "Sign in to Cap",+ subtitle = "Your videos, organized and ready to share.",+}: SignInPanelProps) {+ const auth = useAuth();+ const codeInputRef = useRef<TextInput>(null);+ const loadingRef = useRef(false);+ const [email, setEmail] = useState("");+ const [code, setCode] = useState("");+ const [organizationId, setOrganizationId] = useState("");+ const [codeSent, setCodeSent] = useState(false);+ const [lastCodeRequestedAt, setLastCodeRequestedAt] = useState<number | null>(+ null,+ );+ const [lastCodeRequestedEmail, setLastCodeRequestedEmail] = useState<+ string | null+ >(null);+ const [nowMs, setNowMs] = useState(() => Date.now());+ const [showSso, setShowSso] = useState(false);+ const [focusedInput, setFocusedInput] = useState<FocusedInput>(null);+ const [loading, setLoading] = useState<LoadingKind | null>(null);+ const [error, setError] = useState<SignInError | null>(null);++ const normalizedEmail = email.trim().toLowerCase();+ const normalizedOrganizationId = organizationId.trim();+ const cooldownEndsAt =+ lastCodeRequestedAt !== null && lastCodeRequestedEmail === normalizedEmail+ ? lastCodeRequestedAt + emailCodeCooldownMs+ : null;+ const cooldownRemainingMs =+ cooldownEndsAt !== null ? Math.max(0, cooldownEndsAt - nowMs) : 0;+ const cooldownRemainingSeconds = Math.ceil(cooldownRemainingMs / 1000);+ const isCodeRequestCoolingDown = cooldownRemainingSeconds > 0;+ const isEmailReady = emailPattern.test(normalizedEmail);+ const isCodeReady = codePattern.test(code);+ const isSsoReady = normalizedOrganizationId.length > 0;+ const canRequestCode =+ isEmailReady && loading === null && !isCodeRequestCoolingDown;+ const canVerifyCode = isCodeReady && loading === null;+ const canStartSso = isSsoReady && loading === null;+ const isCodeStep = codeSent && !showSso;+ const showBackButton = showSso || isCodeStep;+ const showGoogle = auth.authConfig.googleAuthAvailable;+ const showSaml = auth.authConfig.workosAuthAvailable;+ const showProviderOptions = showGoogle || showSaml;+ const errorMessage = error?.message ?? null;+ const emailInputHasError =+ error?.source === "email" && !showSso && !isCodeStep;+ const ssoInputHasError = error?.source === "sso" && showSso;+ const codeEntryHasError = error?.source === "code" && isCodeStep;+ const googleActionHasError =+ error?.source === "google" && !showSso && !isCodeStep;+ const ssoActionHasError = error?.source === "sso" && showSso;+ const backDisabled = loading !== null;+ const codeEntryDisabled = loading !== null;+ const activeCodeSlotIndex = Math.min(code.length, codeSlots.length - 1);+ const linkDisabled = loading !== null;+ const resendDisabled = loading !== null || isCodeRequestCoolingDown;+ const headerTitle = isCodeStep ? "Enter verification code" : title;+ const headerSubtitle = isCodeStep+ ? `We sent a 6-digit code to ${normalizedEmail}`+ : subtitle;+ const resendLabel = isCodeRequestCoolingDown+ ? `Resend in ${cooldownRemainingSeconds}s`+ : "Didn't receive the code? Resend";+ const emailButtonLabel = "Login with email";+ const verifyButtonLabel = "Verify Code";+ const googleButtonLabel = googleActionHasError+ ? "Retry Google"+ : "Login with Google";+ const ssoContinueButtonLabel = ssoActionHasError+ ? "Retry SSO"+ : "Continue with SSO";+ const googleButtonAccessibilityLabel = googleActionHasError+ ? "Retry Google sign in"+ : undefined;+ const ssoContinueButtonAccessibilityLabel = ssoActionHasError+ ? "Retry SAML SSO sign in"+ : undefined;+ const activeSignInAccessibilityText =+ loading === "email"+ ? "Sending verification code"+ : loading === "code"+ ? "Verifying code"+ : loading === "google"+ ? "Starting Google sign in"+ : loading === "sso"+ ? "Starting SAML SSO sign in"+ : null;+ const activeSignInAccessibilityValue = activeSignInAccessibilityText+ ? { text: activeSignInAccessibilityText }+ : undefined;+ const emailButtonAccessibilityValue =+ loading === "email"+ ? activeSignInAccessibilityValue+ : emailInputHasError && errorMessage+ ? { text: errorMessage }+ : normalizedEmail.length > 0 && !isEmailReady+ ? { text: "Email address is not valid" }+ : loading !== null+ ? activeSignInAccessibilityValue+ : undefined;+ const verifyButtonAccessibilityValue =+ loading === "code"+ ? activeSignInAccessibilityValue+ : isCodeStep+ ? { text: `${code.length} of 6 digits entered` }+ : undefined;+ const googleButtonAccessibilityValue =+ loading === "google"+ ? activeSignInAccessibilityValue+ : googleActionHasError && errorMessage+ ? { text: errorMessage }+ : loading !== null+ ? activeSignInAccessibilityValue+ : undefined;+ const samlButtonAccessibilityValue =+ loading !== null ? activeSignInAccessibilityValue : undefined;+ const ssoContinueButtonAccessibilityValue =+ loading === "sso"+ ? activeSignInAccessibilityValue+ : ssoActionHasError && errorMessage+ ? { text: errorMessage }+ : normalizedOrganizationId.length > 0+ ? undefined+ : { text: "Organization ID required" };+ const resendAccessibilityLabel =+ loading === "email" ? "Didn't receive the code? Resend" : resendLabel;+ const resendAccessibilityValue =+ loading === "email"+ ? activeSignInAccessibilityValue+ : loading !== null+ ? activeSignInAccessibilityValue+ : isCodeRequestCoolingDown+ ? { text: `Wait ${cooldownRemainingSeconds} seconds` }+ : undefined;+ const codeEntryAccessibilityValue =+ loading === "code"+ ? activeSignInAccessibilityValue+ : { text: `${code.length} of 6 digits entered` };+ const linkAccessibilityValue =+ loading !== null ? activeSignInAccessibilityValue : undefined;+ const emailInputAccessibilityValue =+ loading !== null ? activeSignInAccessibilityValue : undefined;+ const ssoInputAccessibilityValue =+ loading !== null+ ? activeSignInAccessibilityValue+ : ssoInputHasError && errorMessage+ ? { text: errorMessage }+ : undefined;+ const backButtonAccessibilityValue =+ loading !== null ? activeSignInAccessibilityValue : undefined;+ const resendHint =+ loading !== null+ ? "Sign in is in progress"+ : isCodeRequestCoolingDown+ ? `Wait ${cooldownRemainingSeconds} seconds before requesting a new code`+ : "Requests a new verification code";+ const emailButtonHint =+ loading === "email"+ ? "Sending verification code"+ : loading !== null+ ? "Sign in is in progress"+ : !isEmailReady+ ? "Enter a valid email address to continue"+ : "Sends a verification code to this email";+ const verifyButtonHint =+ loading === "code"+ ? "Verifying code"+ : loading !== null+ ? "Sign in is in progress"+ : !isCodeReady+ ? "Enter the 6-digit code to continue"+ : "Verifies the 6-digit code";+ const googleButtonHint =+ loading === "google"+ ? "Google sign in is starting"+ : loading !== null+ ? "Sign in is in progress"+ : googleActionHasError && errorMessage+ ? errorMessage+ : "Starts Google sign in";+ const samlButtonHint =+ loading !== null+ ? "Sign in is in progress"+ : "Shows the SSO organization step";+ const ssoButtonHint =+ loading === "sso"+ ? "SAML SSO sign in is starting"+ : loading !== null+ ? "Sign in is in progress"+ : ssoActionHasError && errorMessage+ ? errorMessage+ : !isSsoReady+ ? "Enter your organization ID to continue"+ : "Starts SAML SSO for this organization";+ const emailInputHint =+ emailInputHasError && errorMessage+ ? errorMessage+ : "Enter your email to request a verification code";+ const ssoInputHint =+ ssoInputHasError && errorMessage+ ? errorMessage+ : "Enter your organization ID to continue with SSO";+ const codeEntryHint =+ codeEntryHasError && errorMessage+ ? errorMessage+ : loading === "code"+ ? "Verifying code"+ : loading !== null+ ? "Sign in is in progress"+ : "Tap to enter the 6-digit code";+ const signupLinkHint =+ loading !== null+ ? "Sign in is in progress"+ : "Opens sign up in a browser sheet";+ const termsLinkHint =+ loading !== null+ ? "Sign in is in progress"+ : "Opens Terms of Service in a browser sheet";+ const privacyLinkHint =+ loading !== null+ ? "Sign in is in progress"+ : "Opens Privacy Policy in a browser sheet";+ const backButtonHint =+ loading !== null+ ? "Sign in is in progress"+ : isCodeStep+ ? "Returns to email sign in"+ : "Returns to sign in options";++ const beginLoading = (nextLoading: LoadingKind) => {+ if (loadingRef.current || loading !== null) return false;+ loadingRef.current = true;+ setLoading(nextLoading);+ return true;+ };++ const endLoading = () => {+ loadingRef.current = false;+ setLoading(null);+ };++ const isAuthBusy = () => loadingRef.current || loading !== null;++ useEffect(() => {+ if (!isCodeRequestCoolingDown) return;+ const interval = setInterval(() => setNowMs(Date.now()), 1000);+ return () => clearInterval(interval);+ }, [isCodeRequestCoolingDown]);++ const goBack = () => {+ if (isAuthBusy()) return;+ if (showSso) setShowSso(false);+ if (isCodeStep) {+ setCodeSent(false);+ setCode("");+ }+ setFocusedInput(null);+ setError(null);+ };++ const updateOrganizationId = (value: string) => {+ if (isAuthBusy()) return;+ setOrganizationId(value.trim());+ setError(null);+ };++ const updateEmail = (value: string) => {+ if (isAuthBusy()) return;+ setEmail(value.toLowerCase());+ setCodeSent(false);+ setCode("");+ setError(null);+ };++ const requestCode = async () => {+ if (!emailPattern.test(normalizedEmail)) return;+ if (isCodeRequestCoolingDown) {+ setError({+ message: `Please wait ${cooldownRemainingSeconds} seconds before requesting a new code.`,+ source: "resend",+ });+ return;+ }+ if (!beginLoading("email")) return;+ setError(null);+ try {+ await auth.requestEmailCode(normalizedEmail);+ const requestedAt = Date.now();+ setEmail(normalizedEmail);+ setCode("");+ setCodeSent(true);+ setLastCodeRequestedAt(requestedAt);+ setLastCodeRequestedEmail(normalizedEmail);+ setNowMs(requestedAt);+ } catch (requestError) {+ setError({+ message: getEmailRequestErrorMessage(requestError),+ source: "email",+ });+ } finally {+ endLoading();+ }+ };++ const verifyCode = async (codeToVerify = code) => {+ if (!codePattern.test(codeToVerify)) return;+ if (!beginLoading("code")) return;+ setError(null);+ try {+ await auth.verifyEmailCode(normalizedEmail, codeToVerify);+ } catch (verifyError) {+ setError({+ message: getCodeVerificationErrorMessage(verifyError),+ source: "code",+ });+ setCode("");+ } finally {+ endLoading();+ }+ };++ const updateCode = (value: string) => {+ if (isAuthBusy()) return;+ const nextCode = value.replace(/\D/g, "").slice(0, 6);+ setCode(nextCode);+ setError(null);+ if (codePattern.test(nextCode)) void verifyCode(nextCode);+ };++ const submitCode = () => {+ void verifyCode();+ };++ const focusCodeInput = () => {+ if (codeEntryDisabled) return;+ setFocusedInput("code");+ codeInputRef.current?.focus();+ };++ const openWebPathIfIdle = (path: string) => {+ if (isAuthBusy()) return;+ openWebPath(path);+ };++ const signInWithGoogle = async () => {+ if (!beginLoading("google")) return;+ setError(null);+ try {+ await auth.signInWithGoogle();+ } catch (googleError) {+ setError({+ message: getProviderErrorMessage(+ googleError,+ "Unable to start Google sign in.",+ ),+ source: "google",+ });+ } finally {+ endLoading();+ }+ };++ const signInWithSso = async () => {+ if (normalizedOrganizationId.length === 0) return;+ if (!beginLoading("sso")) return;+ setError(null);+ try {+ await auth.signInWithSso(normalizedOrganizationId);+ } catch (ssoError) {+ setError({+ message: getProviderErrorMessage(+ ssoError,+ "Unable to start SSO sign in.",+ ),+ source: "sso",+ });+ } finally {+ endLoading();+ }+ };++ const showSsoStep = () => {+ if (isAuthBusy()) return;+ setShowSso(true);+ setCodeSent(false);+ setCode("");+ setError(null);+ };++ return (+ <View style={styles.shell}>+ <GlassSurface+ fallbackStyle={styles.cardFallback}+ glassEffectStyle="regular"+ isInteractive+ style={styles.card}+ tintColor={colors.gray3}+ >+ {showBackButton ? (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Back"+ accessibilityHint={backButtonHint}+ accessibilityState={{ disabled: backDisabled }}+ accessibilityValue={backButtonAccessibilityValue}+ disabled={backDisabled}+ hitSlop={6}+ onPress={goBack}+ style={({ pressed }) => [+ styles.backPill,+ pressed && !backDisabled && styles.backPillPressed,+ backDisabled && styles.backPillDisabled,+ ]}+ >+ <SymbolView+ name="arrow.left"+ size={11}+ tintColor={backDisabled ? colors.gray9 : colors.gray12}+ weight="semibold"+ />+ <Text+ style={[+ styles.backPillText,+ backDisabled && styles.backPillTextDisabled,+ ]}+ >+ Back+ </Text>+ </Pressable>+ ) : null}+ <View style={styles.brandBlock}>+ <CapLogoBadge />+ </View>+ <View style={styles.header}>+ <Text style={[styles.title, isCodeStep && styles.codeTitle]}>+ {headerTitle}+ </Text>+ <Text style={[styles.subtitle, isCodeStep && styles.codeSubtitle]}>+ {headerSubtitle}+ </Text>+ </View>+ <View style={styles.formStack}>+ {showSso ? (+ <View style={styles.ssoStack}>+ <TextInput+ accessibilityHint={ssoInputHint}+ accessibilityLabel="Organization ID"+ accessibilityState={{ disabled: loading !== null }}+ accessibilityValue={ssoInputAccessibilityValue}+ value={organizationId}+ onChangeText={updateOrganizationId}+ autoCapitalize="none"+ autoCorrect={false}+ autoFocus+ clearButtonMode="while-editing"+ editable={loading === null}+ enablesReturnKeyAutomatically+ placeholder="Enter your Organization ID..."+ placeholderTextColor={colors.gray9}+ returnKeyType="go"+ selectionColor={colors.blue9}+ onBlur={() => setFocusedInput(null)}+ onFocus={() => setFocusedInput("sso")}+ onSubmitEditing={signInWithSso}+ style={[+ styles.input,+ focusedInput === "sso" && styles.inputFocused,+ ssoInputHasError && styles.inputError,+ ]}+ />+ <ActionButton+ label={ssoContinueButtonLabel}+ accessibilityLabel={ssoContinueButtonAccessibilityLabel}+ accessibilityHint={ssoButtonHint}+ accessibilityValue={ssoContinueButtonAccessibilityValue}+ onPress={signInWithSso}+ loading={loading === "sso"}+ disabled={!canStartSso}+ size="md"+ symbol="arrow.up.right"+ variant="dark"+ />+ </View>+ ) : isCodeStep ? (+ <View style={styles.codeSection}>+ <Pressable+ accessibilityLabel="Verification code"+ accessibilityRole="button"+ accessibilityHint={codeEntryHint}+ accessibilityState={{+ busy: loading === "code",+ disabled: codeEntryDisabled,+ }}+ accessibilityValue={codeEntryAccessibilityValue}+ disabled={codeEntryDisabled}+ onPress={focusCodeInput}+ style={[+ styles.codeBoxes,+ codeEntryDisabled && styles.codeBoxesDisabled,+ ]}+ >+ {codeSlots.map((slot, index) => (+ <View+ key={slot}+ style={[+ styles.codeBox,+ activeCodeSlotIndex === index && styles.codeBoxActive,+ focusedInput === "code" &&+ activeCodeSlotIndex === index &&+ styles.codeBoxFocused,+ codeEntryHasError && styles.codeBoxError,+ ]}+ >+ <Text style={styles.codeDigit}>{code[index] ?? ""}</Text>+ </View>+ ))}+ <TextInput+ ref={codeInputRef}+ accessibilityElementsHidden+ accessible={false}+ value={code}+ onChangeText={updateCode}+ autoComplete="one-time-code"+ autoFocus+ editable={loading === null}+ enablesReturnKeyAutomatically+ keyboardType="number-pad"+ returnKeyType="done"+ onBlur={() => setFocusedInput(null)}+ onFocus={() => setFocusedInput("code")}+ onSubmitEditing={submitCode}+ maxLength={6}+ importantForAccessibility="no-hide-descendants"+ selectionColor={colors.blue9}+ textContentType="oneTimeCode"+ style={styles.codeInput}+ />+ </Pressable>+ <ActionButton+ label={verifyButtonLabel}+ accessibilityHint={verifyButtonHint}+ accessibilityValue={verifyButtonAccessibilityValue}+ onPress={submitCode}+ loading={loading === "code"}+ disabled={!canVerifyCode}+ size="md"+ variant="primary"+ />+ </View>+ ) : (+ <>+ <TextInput+ accessibilityHint={emailInputHint}+ accessibilityLabel="Email address"+ accessibilityState={{ disabled: loading !== null }}+ accessibilityValue={emailInputAccessibilityValue}+ value={email}+ onChangeText={updateEmail}+ autoCapitalize="none"+ autoComplete="email"+ autoCorrect={false}+ autoFocus+ clearButtonMode="while-editing"+ editable={loading === null}+ enablesReturnKeyAutomatically+ keyboardType="email-address"+ placeholder="[email protected]"+ placeholderTextColor={colors.gray9}+ returnKeyType="send"+ selectionColor={colors.blue9}+ textContentType="emailAddress"+ onBlur={() => setFocusedInput(null)}+ onFocus={() => setFocusedInput("email")}+ onSubmitEditing={requestCode}+ style={[+ styles.input,+ focusedInput === "email" && styles.inputFocused,+ emailInputHasError && styles.inputError,+ ]}+ />+ <ActionButton+ label={emailButtonLabel}+ accessibilityHint={emailButtonHint}+ accessibilityValue={emailButtonAccessibilityValue}+ onPress={requestCode}+ loading={loading === "email"}+ disabled={!canRequestCode}+ size="md"+ symbol="envelope"+ variant="dark"+ />+ </>+ )}+ {errorMessage ? (+ <View+ accessibilityLabel={`Sign-in error: ${errorMessage}`}+ accessibilityLiveRegion="polite"+ accessibilityRole="alert"+ style={styles.errorBanner}+ >+ <SymbolView+ name="exclamationmark.triangle"+ size={14}+ tintColor={colors.red9}+ weight="medium"+ />+ <Text style={styles.errorText}>{errorMessage}</Text>+ </View>+ ) : null}+ {isCodeStep ? (+ <View style={styles.codeLinks}>+ <Pressable+ accessibilityLabel={resendAccessibilityLabel}+ accessibilityRole="button"+ accessibilityHint={resendHint}+ accessibilityState={{+ busy: loading === "email",+ disabled: resendDisabled,+ }}+ accessibilityValue={resendAccessibilityValue}+ disabled={resendDisabled}+ hitSlop={6}+ onPress={requestCode}+ style={styles.resendButton}+ >+ <Text+ style={[+ styles.resendText,+ resendDisabled && styles.resendTextDisabled,+ ]}+ >+ {resendLabel}+ </Text>+ </Pressable>+ </View>+ ) : null}+ {showSso || isCodeStep ? null : (+ <>+ <Text style={styles.signupText}>+ Don't have an account?{" "}+ <Text+ accessibilityHint={signupLinkHint}+ accessibilityRole="link"+ accessibilityState={{ disabled: linkDisabled }}+ accessibilityValue={linkAccessibilityValue}+ style={[+ styles.signupLink,+ linkDisabled && styles.linkDisabled,+ ]}+ onPress={() => openWebPathIfIdle("signup")}+ >+ Sign up here+ </Text>+ </Text>+ {showProviderOptions ? (+ <>+ <View style={styles.dividerRow}>+ <View style={styles.divider} />+ <Text style={styles.dividerText}>OR</Text>+ <View style={styles.divider} />+ </View>+ {showGoogle ? (+ <ActionButton+ label={googleButtonLabel}+ accessibilityLabel={googleButtonAccessibilityLabel}+ accessibilityHint={googleButtonHint}+ accessibilityValue={googleButtonAccessibilityValue}+ leading={<GoogleMark />}+ onPress={signInWithGoogle}+ loading={loading === "google"}+ disabled={loading !== null}+ variant="gray"+ size="md"+ />+ ) : null}+ {showSaml ? (+ <ActionButton+ label="Login with SAML SSO"+ accessibilityHint={samlButtonHint}+ accessibilityValue={samlButtonAccessibilityValue}+ onPress={showSsoStep}+ disabled={loading !== null}+ variant="gray"+ size="md"+ symbol="arrow.up.right"+ />+ ) : null}+ </>+ ) : null}+ </>+ )}+ <Text style={styles.legalText}>+ {isCodeStep+ ? "By entering your email, you acknowledge that you have both read and agree to Cap's "+ : "By typing your email and clicking continue, you acknowledge that you have both read and agree to Cap's "}+ <Text+ accessibilityHint={termsLinkHint}+ accessibilityRole="link"+ accessibilityState={{ disabled: linkDisabled }}+ accessibilityValue={linkAccessibilityValue}+ style={[styles.legalLink, linkDisabled && styles.linkDisabled]}+ onPress={() => openWebPathIfIdle("terms")}+ >+ Terms of Service+ </Text>{" "}+ and{" "}+ <Text+ accessibilityHint={privacyLinkHint}+ accessibilityRole="link"+ accessibilityState={{ disabled: linkDisabled }}+ accessibilityValue={linkAccessibilityValue}+ style={[styles.legalLink, linkDisabled && styles.linkDisabled]}+ onPress={() => openWebPathIfIdle("privacy")}+ >+ Privacy Policy+ </Text>+ .+ </Text>+ </View>+ </GlassSurface>+ </View>+ );+}++const styles = StyleSheet.create({+ shell: {+ flex: 1,+ justifyContent: "center",+ paddingVertical: 22,+ },+ card: {+ width: "100%",+ maxWidth: 432,+ alignSelf: "center",+ borderRadius: radius.lg,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray5,+ paddingHorizontal: 28,+ paddingVertical: 28,+ gap: 28,+ ...squircle,+ },+ cardFallback: {+ backgroundColor: colors.gray3,+ },+ backPill: {+ position: "absolute",+ left: 20,+ top: 20,+ zIndex: 2,+ minHeight: 30,+ flexDirection: "row",+ alignItems: "center",+ gap: 8,+ borderRadius: radius.full,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray4,+ paddingHorizontal: 12,+ backgroundColor: "transparent",+ ...squircle,+ },+ backPillPressed: {+ backgroundColor: colors.gray1,+ },+ backPillDisabled: {+ opacity: 0.55,+ },+ backPillText: {+ fontFamily: fonts.regular,+ fontSize: 12,+ lineHeight: 17,+ color: colors.gray12,+ },+ backPillTextDisabled: {+ color: colors.gray9,+ },+ brandBlock: {+ alignItems: "center",+ },+ header: {+ alignItems: "center",+ gap: 8,+ },+ title: {+ fontFamily: fonts.medium,+ fontSize: 24,+ lineHeight: 30,+ color: colors.gray12,+ textAlign: "center",+ },+ codeTitle: {+ fontSize: 20,+ lineHeight: 26,+ },+ subtitle: {+ fontFamily: fonts.regular,+ fontSize: 16,+ lineHeight: 22,+ color: colors.gray10,+ textAlign: "center",+ },+ codeSubtitle: {+ fontSize: 14,+ lineHeight: 20,+ },+ formStack: {+ gap: 12,+ },+ input: {+ minHeight: 44,+ borderRadius: radius.md,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray4,+ backgroundColor: colors.gray1,+ paddingHorizontal: 14,+ fontFamily: fonts.regular,+ fontSize: 16,+ color: colors.gray12,+ ...squircle,+ },+ inputFocused: {+ backgroundColor: colors.gray2,+ borderWidth: 1,+ borderColor: colors.gray5,+ shadowColor: colors.gray12,+ shadowOffset: { width: 0, height: 0 },+ shadowOpacity: 0.12,+ shadowRadius: 1,+ },+ inputError: {+ backgroundColor: colors.red1,+ borderWidth: 1,+ borderColor: colors.red7,+ },+ codeSection: {+ gap: 20,+ paddingTop: 2,+ },+ codeBoxes: {+ flexDirection: "row",+ gap: 8,+ justifyContent: "space-between",+ position: "relative",+ },+ codeBoxesDisabled: {+ opacity: 0.68,+ },+ codeBox: {+ flex: 1,+ height: 52,+ borderRadius: radius.sm,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray5,+ backgroundColor: colors.gray1,+ alignItems: "center",+ justifyContent: "center",+ ...squircle,+ },+ codeBoxActive: {+ borderColor: colors.blue9,+ },+ codeBoxFocused: {+ backgroundColor: colors.gray2,+ borderWidth: 1,+ shadowColor: colors.gray12,+ shadowOffset: { width: 0, height: 0 },+ shadowOpacity: 0.12,+ shadowRadius: 1,+ },+ codeBoxError: {+ backgroundColor: colors.red1,+ borderColor: colors.red7,+ },+ codeDigit: {+ fontFamily: fonts.medium,+ fontSize: 22,+ lineHeight: 27,+ color: colors.gray12,+ textAlign: "center",+ },+ ssoStack: {+ gap: 10,+ },+ codeInput: {+ position: "absolute",+ width: 1,+ height: 1,+ opacity: 0,+ },+ codeLinks: {+ alignItems: "center",+ marginTop: 2,+ },+ resendButton: {+ minHeight: 30,+ justifyContent: "center",+ paddingHorizontal: 4,+ },+ resendText: {+ fontFamily: fonts.regular,+ fontSize: 14,+ lineHeight: 20,+ color: colors.gray10,+ textDecorationLine: "underline",+ },+ resendTextDisabled: {+ color: colors.gray9,+ textDecorationLine: "none",+ },+ errorBanner: {+ minHeight: 42,+ flexDirection: "row",+ alignItems: "center",+ gap: 8,+ borderRadius: radius.md,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.red6,+ backgroundColor: colors.red1,+ paddingHorizontal: 12,+ paddingVertical: 10,+ ...squircle,+ },+ dividerRow: {+ flexDirection: "row",+ alignItems: "center",+ gap: 10,+ paddingVertical: 3,+ },+ divider: {+ flex: 1,+ height: StyleSheet.hairlineWidth,+ backgroundColor: colors.gray5,+ },+ dividerText: {+ fontFamily: fonts.medium,+ fontSize: 12,+ textTransform: "uppercase",+ color: colors.gray9,+ },+ legalText: {+ fontFamily: fonts.regular,+ fontSize: 12,+ lineHeight: 18,+ color: colors.gray9,+ textAlign: "center",+ },+ legalLink: {+ fontFamily: fonts.medium,+ color: colors.gray12,+ },+ linkDisabled: {+ opacity: 0.55,+ },+ signupText: {+ fontFamily: fonts.regular,+ fontSize: 12,+ lineHeight: 18,+ color: colors.gray9,+ textAlign: "center",+ },+ signupLink: {+ fontFamily: fonts.medium,+ color: colors.blue9,+ },+ errorText: {+ flex: 1,+ fontFamily: fonts.medium,+ fontSize: 14,+ lineHeight: 20,+ color: colors.red9,+ },+});diff --git a/apps/mobile/src/auth/session.ts b/apps/mobile/src/auth/session.tsnew file mode 100644index 000000000..be8f9b87f--- /dev/null+++ b/apps/mobile/src/auth/session.ts@@ -0,0 +1,20 @@+export const parseAuthRedirect = (url: string) => {+ const parsed = new URL(url);+ const error = parsed.searchParams.get("error_description");+ if (error) throw new Error(error);++ const apiKey = parsed.searchParams.get("api_key");+ const userId = parsed.searchParams.get("user_id");++ if (!apiKey) return null;+ return {+ apiKey,+ userId,+ };+};++export const requireAuthRedirectSession = (url: string) => {+ const session = parseAuthRedirect(url);+ if (!session) throw new Error("Sign in did not return a mobile session.");+ return session;+};diff --git a/apps/mobile/src/auth/signInDestination.test.ts b/apps/mobile/src/auth/signInDestination.test.tsnew file mode 100644index 000000000..8ca3f9b70--- /dev/null+++ b/apps/mobile/src/auth/signInDestination.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from "vitest";+import { signInTitleForSegments } from "./signInDestination";++describe("signInTitleForSegments", () => {+ it("uses contextual auth titles for deep-linked mobile surfaces", () => {+ expect(signInTitleForSegments(["(tabs)", "upload"])).toBe(+ "Sign in to import",+ );+ expect(signInTitleForSegments(["caps", "[id]"])).toBe("Sign in to view");+ expect(signInTitleForSegments(["(tabs)"])).toBe("Sign in to Cap");+ });+});diff --git a/apps/mobile/src/auth/signInDestination.ts b/apps/mobile/src/auth/signInDestination.tsnew file mode 100644index 000000000..033439d14--- /dev/null+++ b/apps/mobile/src/auth/signInDestination.ts@@ -0,0 +1,5 @@+export const signInTitleForSegments = (segments: readonly string[]) => {+ if (segments.includes("upload")) return "Sign in to import";+ if (segments.includes("caps")) return "Sign in to view";+ return "Sign in to Cap";+};