Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(native-suite): device setting actions refactor #17689

Merged
merged 2 commits into from
Mar 21, 2025

Conversation

BrantalikP
Copy link
Contributor

@BrantalikP BrantalikP commented Mar 15, 2025

Description

Prevent triggering device setting actions unintentionally.

Related Issue

Resolve #17648

Screenshots:

Before

IMG_6529.MOV
IMG_6535.MOV

After

IMG_6534.MOV
IMG_6530.MOV

Copy link

github-actions bot commented Mar 15, 2025

🚀 Expo preview is ready!

  • Project → trezor-suite-preview
  • Platforms → android, ios
  • Scheme → trezorsuitelite
  • Runtime Version → 27
  • More info

Learn more about 𝝠 Expo Github Action

@BrantalikP BrantalikP force-pushed the fix/native/device-setting-actions-trigger branch from a840f77 to 3b8d7fd Compare March 15, 2025 14:32
@BrantalikP BrantalikP marked this pull request as ready for review March 17, 2025 12:24
@BrantalikP BrantalikP requested a review from a team as a code owner March 17, 2025 12:24
@BrantalikP BrantalikP force-pushed the fix/native/device-setting-actions-trigger branch from 3b8d7fd to b48f961 Compare March 17, 2025 12:25
Copy link

coderabbitai bot commented Mar 17, 2025

Walkthrough

The changes refactor device authentication and pin management across several modules. In the device authenticity component, Redux state references and complex logic for checking and reporting authenticity have been removed and replaced with a simpler navigation function to the authenticity route. The device pin action component similarly discards detailed pin handling—including state management, analytics, and error routines—in favor of a straightforward navigation to the pin protection screen. Two new custom hooks have been introduced: one manages device authenticity actions by monitoring connection status and invoking authentication via an external service, while the other manages pin protection actions with defined configurations and feedback for success or failure. Additionally, device change detection now calls a cancellation method from an external library upon real device mismatch, and navigation parameters have been updated with a new type definition to enforce strict handling of pin action routes.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (1)

36-74: Consider handling device disconnection more explicitly.

The checkAuthenticity function correctly handles various error scenarios, but there could be edge cases when the device disconnects during the authentication process. The error handling at lines 64-67 mentions device disconnection in a comment but doesn't explicitly handle it differently from other interruptions.

Consider enhancing error handling with more specific handling for device disconnection:

 } else if (errorCode === 'Method_Interrupted' || errorCode === undefined) {
     // navigation.goBack() already called via the X button (or the device was disconnected)
     reportCheckResult('cancelled');
+} else if (errorCode === 'Device_Disconnected') {
+    reportCheckResult('deviceDisconnected');
+    // Optional: Show specific message about device being disconnected
 } else {
suite-native/module-device-settings/src/hooks/usePinAction.tsx (1)

93-130: Consider adding a timeout handling mechanism.

The handlePinAction function handles various error cases well, but it might benefit from a timeout mechanism for cases where the device doesn't respond in a timely manner.

Consider implementing a timeout handler:

const handlePinAction = useCallback(async () => {
    analytics.report({
        type: EventType.DeviceSettingsPinProtectionChange,
        payload: { action: type },
    });

    const { param, successMessageKey, canceledMessageKey } = actionConfigMap[type];

+   // Create a timeout promise
+   const timeoutPromise = new Promise((_, reject) => {
+       const id = setTimeout(() => {
+           clearTimeout(id);
+           reject(new Error('Operation timed out'));
+       }, 60000); // 60-second timeout
+   });

    const result = await requestPrioritizedDeviceAccess({
        deviceCallback: () =>
            TrezorConnect.changePin({
                device: {
                    path: device?.path,
                },
                remove: param,
            }),
    });
    dispatch(removeButtonRequests({ device }));

    // Error handling logic...
}, [device, dispatch, navigation, showError, showSuccess, type]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac514a7 and 3b8d7fd.

📒 Files selected for processing (8)
  • suite-native/module-device-settings/src/components/DeviceAuthenticityCard.tsx (3 hunks)
  • suite-native/module-device-settings/src/components/DevicePinActionButton.tsx (2 hunks)
  • suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (1 hunks)
  • suite-native/module-device-settings/src/hooks/useDeviceChangedCheck.ts (2 hunks)
  • suite-native/module-device-settings/src/hooks/usePinAction.tsx (1 hunks)
  • suite-native/module-device-settings/src/navigation/DeviceAuthenticityStackNavigator.tsx (1 hunks)
  • suite-native/module-device-settings/src/navigation/DevicePinProtectionStackNavigator.tsx (2 hunks)
  • suite-native/navigation/src/navigators.ts (2 hunks)
🔇 Additional comments (19)
suite-native/module-device-settings/src/hooks/useDeviceChangedCheck.ts (2)

16-16: Good addition of TrezorConnect import

The import of TrezorConnect is necessary for the new functionality.


39-39: Good implementation of device change handling

Adding TrezorConnect.cancel() ensures that pending operations are properly terminated when a device mismatch is detected, preventing unexpected behaviors.

suite-native/module-device-settings/src/navigation/DeviceAuthenticityStackNavigator.tsx (2)

9-9: Good addition of useDeviceAuthenticityAction hook

The import of the new hook aligns with the refactoring goal of managing device authentication.


17-17: Good implementation of the hook

Adding useDeviceAuthenticityAction() before the device connection check is appropriate as it centralizes the device authenticity logic in a dedicated hook.

suite-native/module-device-settings/src/navigation/DevicePinProtectionStackNavigator.tsx (2)

14-14: Good addition of usePinAction hook

The import of the new hook aligns with the refactoring goal of managing pin protection actions.


25-25: Good implementation of the hook

Adding usePinAction() before checking device connection status helps centralize pin-related logic in a dedicated hook, improving code organization and maintainability.

suite-native/navigation/src/navigators.ts (2)

151-152: Good addition of PinActionType

Creating a dedicated type for pin actions improves type safety and makes the codebase more maintainable by clearly defining the allowed values.


174-176: Good implementation of type enforcement

Updating the device pin protection route parameters to require a specific action type improves type safety and prevents unintentional triggering of device setting actions.

suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (2)

23-36: Well-implemented hook with good analytics integration.

The hook is well-structured with a clean separation of concerns. The reportCheckResult function is properly memoized with useCallback to prevent unnecessary re-renders.


76-80: Good use of useEffect for triggering the authentication flow.

The effect hook appropriately triggers the authentication process when the device is connected, which aligns with the PR objective of preventing unintentional triggering of device setting actions. The disabled eslint rule is justified in this case.

suite-native/module-device-settings/src/hooks/usePinAction.tsx (3)

35-51: Well-structured action configuration mapping.

The actionConfigMap cleanly maps pin action types to their respective configurations. The use of as const satisfies ensures type safety while providing strong typing. This approach makes it easy to maintain and extend the configuration in the future.


64-91: Well-implemented UI feedback functions.

Both showSuccess and showError functions are properly memoized with useCallback and have clear, well-defined purposes. The error function provides good user options with retry functionality, improving the user experience when errors occur.


132-136: Good use of useEffect for device connection monitoring.

The effect hook appropriately triggers the pin action when the device is connected, which aligns with the PR objective of preventing unintentional triggering of device setting actions.

suite-native/module-device-settings/src/components/DeviceAuthenticityCard.tsx (3)

6-6: Streamlined import statement.

The removal of selectSelectedDevice and addition of selectIsDeviceDiscoveryActive aligns with the PR objective of simplifying device setting actions. This change moves the device state management responsibility to the dedicated hook.


31-33: Simplified navigation function.

The navigateToDeviceAuthenticityStack function elegantly replaces the complex checkAuthenticity function with a simple navigation action. This change aligns with the PR's goal to prevent unintentional triggering of device setting actions.


55-57: Updated callback dependencies.

The onPressPrimaryButton now uses the simplified navigation function, and the dependency array has been correctly updated to include it. This change improves the component's maintainability.

suite-native/module-device-settings/src/components/DevicePinActionButton.tsx (3)

2-13: Streamlined imports and updated types.

The import statements have been simplified to include only what's necessary, and ActionType has been replaced with PinActionType. This change aligns with the PR objective and improves code clarity.


35-39: Simplified navigation function.

The navigateToPinStack function replaces the more complex changePin function with a simple navigation action. This refactoring moves the pin handling logic to the dedicated hook and prevents unintentional triggering of device setting actions.


42-44: Updated button callback.

The button's onPress event now uses the simplified navigation function, which aligns with the PR's goal of refactoring device setting actions to prevent unintentional triggering.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (1)

36-74: Comprehensive authentication flow with proper error handling

The checkAuthenticity function is well-structured with clear navigation paths for different authentication outcomes. Error handling is comprehensive, covering various failure scenarios.

One minor suggestion - consider adding a comment explaining what happens if payload.error === 'CA_PUBKEY_NOT_FOUND' && !payload.configExpired, as it's not immediately obvious how this case is handled.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b8d7fd and b48f961.

📒 Files selected for processing (8)
  • suite-native/module-device-settings/src/components/DeviceAuthenticityCard.tsx (3 hunks)
  • suite-native/module-device-settings/src/components/DevicePinActionButton.tsx (2 hunks)
  • suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (1 hunks)
  • suite-native/module-device-settings/src/hooks/useDeviceChangedCheck.ts (2 hunks)
  • suite-native/module-device-settings/src/hooks/usePinAction.tsx (1 hunks)
  • suite-native/module-device-settings/src/navigation/DeviceAuthenticityStackNavigator.tsx (1 hunks)
  • suite-native/module-device-settings/src/navigation/DevicePinProtectionStackNavigator.tsx (2 hunks)
  • suite-native/navigation/src/navigators.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • suite-native/module-device-settings/src/navigation/DeviceAuthenticityStackNavigator.tsx
  • suite-native/module-device-settings/src/navigation/DevicePinProtectionStackNavigator.tsx
  • suite-native/module-device-settings/src/hooks/usePinAction.tsx
  • suite-native/navigation/src/navigators.ts
  • suite-native/module-device-settings/src/hooks/useDeviceChangedCheck.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: EAS Update
  • GitHub Check: Analyze with CodeQL (javascript)
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: prepare_android_test_app
🔇 Additional comments (14)
suite-native/module-device-settings/src/components/DevicePinActionButton.tsx (4)

2-2: Simplified imports align with the new refactored approach.

The import statements have been updated to only include necessary dependencies. The transition from ActionType to PinActionType suggests a more specialized type interface for PIN-related actions, which improves type safety and better represents the component's purpose.

Also applies to: 6-6, 11-11


22-22: Updated prop type to match import changes.

The type definition is now more specific and aligns with the navigation parameters, improving type safety and clarity of the component's API.


35-39: Simplified navigation logic enhances maintainability.

The navigation logic has been significantly simplified by removing complex error handling, analytics, and device access request logic from this component. This refactor aligns with the PR objective to prevent unintentional triggering of device settings actions by moving the action execution logic outside this component and focusing solely on navigation.

The useCallback optimization is correctly implemented with proper dependencies.


43-43: Updated button handler to use the new navigation function.

The button now uses the simplified navigation function, ensuring consistency with the component's new approach. This change helps prevent unintentional triggering of device settings by introducing a separate confirmation screen.

suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (5)

1-17: Good organization of imports

The imports are well-structured, separated by type (React, navigation, application modules), which enhances readability.


18-22: Good use of TypeScript for navigation typing

Strong typing for navigation props ensures type safety throughout the navigation flow.


23-35: Well-structured hook initialization and analytics reporting

The hook properly initializes navigation and selectors from Redux. The analytics reporting function is correctly memoized with useCallback.


76-81: Verify dependency array in useEffect

The useEffect only includes isDeviceConnected in its dependency array but uses checkAuthenticity inside. While the ESLint rule is disabled, this could potentially lead to stale closure issues if the dependencies of checkAuthenticity change.

Consider either:

  1. Including checkAuthenticity in the dependency array, or
  2. Adding a comment explaining why it's intentionally excluded

1-81: Overall implementation aligns well with PR objectives

This hook successfully refactors device authenticity checks to prevent unintentional triggering, as stated in the PR objectives. The implementation provides a clear, controlled flow for authentication that navigates appropriately based on the device state and authentication results.

suite-native/module-device-settings/src/components/DeviceAuthenticityCard.tsx (5)

6-6: Import dependencies have been simplified.

The code now imports only the selectIsDeviceDiscoveryActive selector, removing the previous selectSelectedDevice import. This aligns with the refactoring goal of simplifying this component's responsibilities.


31-33: Simplified navigation approach approved.

The new navigateToDeviceAuthenticityStack function provides a cleaner, more direct approach to navigation than the previous implementation. This aligns with the PR objective of preventing unintentional triggering of device setting actions by moving the authentication logic out of this component.


55-55: Alert action now uses simplified navigation.

The alert's primary button now triggers simple navigation instead of the previously complex authentication logic, which aligns with the refactoring objectives.


57-57: Dependency array properly updated.

The dependency array has been correctly updated to include the new navigation function, ensuring the callback is properly memoized.


25-81:

❓ Verification inconclusive

Verify error handling in the new architecture.

The component has been simplified by removing device authentication logic, analytics tracking, and error handling. Please confirm that these responsibilities are properly handled in the new useDeviceAuthenticityAction hook mentioned in the summary.


🏁 Script executed:

#!/bin/bash
# Search for the new hook implementation to verify error handling
echo "Searching for useDeviceAuthenticityAction hook implementation..."
rg -A 10 "export const useDeviceAuthenticityAction" --type typescript

Length of output: 245


Manual Verification Required: Confirm Error Handling is Implemented via useDeviceAuthenticityAction

The review comment noted that the component has been simplified by removing direct error handling, with the expectation that the new useDeviceAuthenticityAction hook now covers this responsibility. The initial automated search using the file type "typescript" failed due to an unrecognized file type. To further verify the hook’s implementation, please re-run the following command which restricts the search to common TypeScript file extensions:

Once the hook’s code is located, confirm that it handles error cases (for example, by catching exceptions or managing error states) to ensure the responsibilities removed from the component are properly migrated.


🏁 Script executed:

#!/bin/bash
echo "Searching for useDeviceAuthenticityAction hook implementation in TypeScript files..."
rg -A 10 "export const useDeviceAuthenticityAction" -g "*.{ts,tsx}"

Length of output: 1690


Manual Verification Required: Confirm Error Handling in useDeviceAuthenticityAction

The search located the useDeviceAuthenticityAction hook in the codebase, but we still need to verify that it implements proper error handling (e.g., using try/catch or handling error states) rather than simply delegating actions. Please run additional verification to ensure error handling is implemented as intended. For example, search the hook for try/catch blocks or error state management.

Once confirmed, please update or comment accordingly.


🏁 Script executed:

#!/bin/bash
echo "Searching for try/catch error handling in useDeviceAuthenticityAction..."
rg -A 10 -B 10 "try\s*{" suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts

Length of output: 458


Action Required: Verify Error Handling in useDeviceAuthenticityAction

  • The new useDeviceAuthenticityAction hook is implemented in suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts.
  • An initial inspection (via regex-based searches) did not reveal explicit error handling constructs (e.g., try/catch blocks or .catch callbacks) within the hook.
  • Please confirm that error handling responsibilities removed from the component are either managed within this hook (possibly via alternate mechanisms) or are addressed by a higher-level error boundary in the new architecture.

@BrantalikP BrantalikP force-pushed the fix/native/device-setting-actions-trigger branch from b48f961 to e06dbdc Compare March 17, 2025 13:32
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (4)

47-49: Consider handling the unsuccessful result case.

When result.success is false, the function returns early without notifying the user or reporting to analytics.

if (!result.success) {
+   reportCheckResult('failed');
+   navigation.goBack();
    return;
}

60-73: Consider using constants for error codes.

Error codes like 'Failure_ActionCancelled' are hardcoded as string literals. Consider defining them as constants for better maintainability.

+ const ERROR_ACTION_CANCELLED = 'Failure_ActionCancelled';
+ const ERROR_PIN_CANCELLED = 'Failure_PinCancelled';
+ const ERROR_INTERRUPTED = 'Method_Interrupted';

const errorCode = payload.code;
- if (errorCode === 'Failure_ActionCancelled' || errorCode === 'Failure_PinCancelled') {
+ if (errorCode === ERROR_ACTION_CANCELLED || errorCode === ERROR_PIN_CANCELLED) {
    navigation.goBack();
    reportCheckResult('cancelled');
- } else if (errorCode === 'Method_Interrupted' || errorCode === undefined) {
+ } else if (errorCode === ERROR_INTERRUPTED || errorCode === undefined) {

76-81: Consider adding missing dependencies to the useEffect.

The ESLint disable comment suggests that the dependencies array might be incomplete. The effect uses checkAuthenticity which depends on device, navigation, and reportCheckResult.

useEffect(() => {
    if (isDeviceConnected) void checkAuthenticity();

-   // eslint-disable-next-line react-hooks/exhaustive-deps
-}, [isDeviceConnected]);
+}, [isDeviceConnected, checkAuthenticity]);

If you only want the effect to run when device connection changes (and not on other dependency changes), consider extracting the authenticity check logic to a separate function within the effect.


36-74: Properly handle unhandled promise rejections from checkAuthenticity.

The checkAuthenticity function is called with void operator in the useEffect, but there's no error handling for potential rejections.

const checkAuthenticity = useCallback(async () => {
    try {
        navigation.navigate(DeviceStackRoutes.DeviceAuthenticity);

        const result = await requestPrioritizedDeviceAccess({
            deviceCallback: () =>
                TrezorConnect.authenticateDevice({
                    device: {
                        path: device?.path,
                    },
                }),
        });
        // Rest of the function remains the same
+   } catch (error) {
+       console.error('Device authenticity check failed:', error);
+       reportCheckResult('failed');
+       navigation.goBack();
+   }
}, [device, navigation, reportCheckResult]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b48f961 and e06dbdc.

📒 Files selected for processing (6)
  • suite-native/module-device-settings/src/components/DeviceAuthenticityCard.tsx (3 hunks)
  • suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (1 hunks)
  • suite-native/module-device-settings/src/hooks/useDeviceChangedCheck.ts (2 hunks)
  • suite-native/module-device-settings/src/hooks/usePinAction.tsx (1 hunks)
  • suite-native/module-device-settings/src/navigation/DeviceAuthenticityStackNavigator.tsx (1 hunks)
  • suite-native/module-device-settings/src/screens/FirmwareInstallationScreen.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • suite-native/module-device-settings/src/navigation/DeviceAuthenticityStackNavigator.tsx
  • suite-native/module-device-settings/src/hooks/useDeviceChangedCheck.ts
  • suite-native/module-device-settings/src/hooks/usePinAction.tsx
🔇 Additional comments (11)
suite-native/module-device-settings/src/screens/FirmwareInstallationScreen.tsx (1)

20-22: Type assertion improves navigation type safety.

The addition of the type assertion as DeviceStackRoutes.DeviceSettings enhances type safety by explicitly specifying the expected route type. This change aligns with the broader navigation refactoring in the PR and ensures consistent type handling across the navigation system without changing the actual behavior of the function.

suite-native/module-device-settings/src/components/DeviceAuthenticityCard.tsx (5)

6-6: Import change reflects simplified component responsibility.

The removal of selectSelectedDevice and addition of only selectIsDeviceDiscoveryActive import shows this component no longer directly handles device selection, aligning with the PR's goal of preventing unintentional device setting actions.


31-33: Simplified navigation improves user flow.

The introduction of navigateToDeviceAuthenticityStack simplifies the component by replacing the previous complex checkAuthenticity function with a straightforward navigation action. This enhances maintainability and helps prevent accidental triggering of authenticity checks.


55-55: Clean integration with alert system.

Using the new navigation function as the primary button handler maintains the same user flow while removing direct authenticity checking logic from this component.


57-57: Updated dependency array ensures proper memoization.

The dependency array correctly includes both the alert function and the navigation callback, ensuring the memoized function is updated when either dependency changes.


25-81: Successful separation of concerns in component architecture.

The refactored component now follows a cleaner separation of concerns - it's solely responsible for displaying information and navigating to the appropriate route, while the actual device authenticity checking logic has been moved elsewhere (likely to the new useDeviceAuthenticityAction hook mentioned in the summary).

This architectural change aligns with the PR's goal of preventing unintentional device setting actions by ensuring that more complex operations happen in dedicated screens rather than being triggered directly from this settings card.

suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (5)

1-17: Clean and comprehensive imports for device authenticity functionality.

The imports cover all necessary dependencies including React hooks, Redux, navigation, device selectors, analytics, and device communication.


18-22: Well-typed navigation props for stack-to-stack navigation.

The type definition properly specifies the composite navigation properties needed for navigating between stacks.


23-35: Efficient setup for device authenticity action hook.

The hook correctly uses selectors to get device connection status and the selected device. The analytics reporting function is properly memoized with useCallback.


36-46: Clean implementation of device authenticity check initiation.

The navigation to the Device Authenticity screen and subsequent device authentication via TrezorConnect is implemented effectively.


51-59: Good handling of successful authenticity check results.

The code correctly processes different success scenarios, including valid devices and expired configurations.

@matejkriz matejkriz added the mobile Suite Lite issues and PRs label Mar 19, 2025
Copy link
Member

@matejkriz matejkriz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Few nits so far, I would like to test and think about the TrezorConnect.cancel() placement.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (1)

36-74: Consider adding error logging for debugging purposes

While the error handling is comprehensive, adding detailed logging for unexpected errors would help with debugging in production. Currently, errors are handled for navigation but not logged.

} else {
    const errorCode = payload.code;
    if (errorCode === 'Failure_ActionCancelled' || errorCode === 'Failure_PinCancelled') {
        navigation.goBack();
        reportCheckResult('cancelled');
    } else if (errorCode === 'Method_Interrupted' || errorCode === 'Method_PermissionsNotGranted') {
        // navigation.goBack() already called via the X button (or the device was disconnected)
        reportCheckResult('cancelled');
    } else {
+       console.error('Device authenticity check failed with error:', payload);
        navigation.navigate(DeviceAuthenticityStackRoutes.AuthenticitySummary, {
            checkResult: 'compromised',
        });
        reportCheckResult('failed');
    }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d5164a and fe43c74.

📒 Files selected for processing (2)
  • suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (1 hunks)
  • suite-native/module-device-settings/src/hooks/usePinAction.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • suite-native/module-device-settings/src/hooks/usePinAction.tsx
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: EAS Update
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: prepare_android_test_app
  • GitHub Check: Analyze with CodeQL (javascript)
🔇 Additional comments (4)
suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (4)

23-82: Well-structured hook implementation with clear separation of concerns

The hook effectively manages device authenticity checks through clean separation of navigation, state management, device interaction, and analytics. The error handling is comprehensive, covering various edge cases like cancellation scenarios and configuration expiry.


77-77: Use of void operator with async function

The void operator is used here to explicitly indicate that there's no need to await this async function's completion. This addresses the ESLint warning about unhandled promises.


79-81: Comment explaining dependency exclusion

Good practice to include this comment explaining why checkAuthenticity is excluded from dependencies, as it prevents unintended effect triggers when the device object changes.


51-73: Comprehensive success/error handling

The implementation thoroughly handles various success and error cases, with appropriate navigation and analytics reporting for each scenario. The special handling for expired configurations is a nice touch.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fe43c74 and 29f47ee.

📒 Files selected for processing (2)
  • suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (1 hunks)
  • suite-native/module-device-settings/src/hooks/usePinAction.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • suite-native/module-device-settings/src/hooks/usePinAction.tsx
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: EAS Update
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: prepare_android_test_app
  • GitHub Check: Analyze with CodeQL (javascript)
🔇 Additional comments (4)
suite-native/module-device-settings/src/hooks/useDeviceAuthenticityAction.ts (4)

1-35: Well-structured hook initialization with proper separation of concerns.

The hook is initialized with clean imports and appropriate type definitions. Using useCallback for the reportCheckResult function ensures it's not recreated on each render.


36-74: Comprehensive error handling with appropriate navigation flows.

The checkAuthenticity function handles different scenarios well:

  • Proper device authentication flow
  • Handling of success and failure cases
  • Special case handling for expired configurations
  • Various cancellation scenarios with appropriate navigation responses

This implementation aligns well with the PR objective of preventing unintentional triggering of device setting actions.


76-81: Properly documented dependency exclusion.

The comment explaining why checkAuthenticity is excluded from the dependencies is helpful and aligns with the discussion in the past review comments. This prevents unintentional triggering of the effect when the device object changes.


76-77: Verify the initial load behavior.

When the component mounts and isDeviceConnected is already true, checkAuthenticity will run immediately. Confirm this is the intended behavior as it will navigate to the device authenticity screen on component mount if a device is connected.

Comment on lines +42 to +44
device: {
path: device?.path,
},
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Consider handling undefined device path.

While the optional chaining with device?.path handles null devices, what happens if the device object exists but has no path property? Consider adding a guard to prevent authenticating a device without a valid path.


🏁 Script executed:

#!/bin/bash
# Check if there are any instances where device authentication is attempted with a potentially undefined path
rg -A 5 "TrezorConnect\.authenticateDevice" --type ts

Length of output: 3553


Action: Add an explicit guard to ensure the device object has a valid path before calling TrezorConnect.authenticateDevice.

The current code:

                    device: {
                        path: device?.path,
                    },

relies on optional chaining, which only protects against a null or undefined device but not against an existing device lacking a path property. Notably, in suite-common/device-authenticity/src/deviceAuthenticityThunks.ts the call passes device.path directly—suggesting that a valid path is required. To maintain consistency and prevent potential issues, add a guard (e.g., an early return or error handling) that confirms device?.path is defined and valid before proceeding with device authentication.

Copy link
Member

@matejkriz matejkriz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great job, works smooth for me 🎉

@matejkriz
Copy link
Member

/rebase

Copy link

@trezor-ci trezor-ci force-pushed the fix/native/device-setting-actions-trigger branch from 29f47ee to f109226 Compare March 21, 2025 08:25
@matejkriz
Copy link
Member

android E2E is failing on the same thing as on develop https://github.com/trezor/trezor-suite/actions/runs/13981866909/job/39148822012

@matejkriz matejkriz merged commit 0932a5e into develop Mar 21, 2025
15 of 16 checks passed
@matejkriz matejkriz deleted the fix/native/device-setting-actions-trigger branch March 21, 2025 11:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
mobile Suite Lite issues and PRs
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Unexpected PIN Change Prompt
2 participants