Files
de37001833 feat(Hypernative): assessment integration (#6891)
* feat(Hypernative): OAuth login flow (#6759)

* feat: add global Hypernative OAuth auth Redux slice

Implement per-user authentication state management for Hypernative OAuth flow.
Creates a new global Redux slice (hnAuthSlice) to store OAuth tokens that are
shared across all Safe accounts.

- Create hnAuthSlice with setAuthToken and clearAuthToken actions
- Add token expiry handling with automatic validation in selectors
- Register slice in Redux store with localStorage persistence
- Export slice from hypernative store index

The slice stores:
- authToken: OAuth access token
- authTokenExpiry: timestamp for token expiration
- isAuthenticated: boolean flag for quick auth checks

* feat(hypernative): add OAuth configuration with mocked endpoints

- Create OAuth configuration module with all endpoint URLs
- Support environment variable overrides for all config values
- Add getRedirectUri() helper for dynamic redirect URI construction
- Default to mocked endpoints for development until real HN endpoints available
- Add MOCK_AUTH_ENABLED flag for simplified testing flow
- Include comprehensive test coverage

* feat(hypernative): add useHypernativeOAuth hook for OAuth flow management

- Create useHypernativeOAuth hook with full PKCE flow support
- Generate cryptographically secure code verifier and SHA-256 challenge
- Support dual mode: mock authentication for development, real OAuth for production
- Implement popup-first approach with automatic fallback to new tab
- Add secure postMessage communication with OAuth callback page
- Store PKCE verifier and OAuth state in sessionStorage
- Include origin validation for security
- Auto-cleanup popup windows after authentication
- Provide initiateLogin() and logout() control functions
- Export HN_AUTH_SUCCESS_EVENT and HN_AUTH_ERROR_EVENT constants
- Add comprehensive test coverage

Features:
- Mock mode: instant token generation with 1-second simulated delay
- Real mode: full OAuth Authorization Code + PKCE flow
- Popup dimensions: 600x800px centered on screen
- Security: origin validation, CSRF protection via state parameter
- Error handling: graceful fallback and error logging

* feat: implement Hypernative OAuth callback page with full test coverage

Implement OAuth callback page that handles the authorization redirect:
- Extract authorization code and state from URL query parameters
- Verify OAuth state parameter for CSRF protection
- Retrieve PKCE code verifier from sessionStorage
- Exchange authorization code for access token via token endpoint
- Store token in Redux and communicate with parent window via postMessage
- Auto-close popup window after successful authentication
- Display loading, success, and error states with MUI components

* feat: add MSW mock handler for Hypernative OAuth token exchange

Implement Mock Service Worker handler for OAuth token endpoint to enable
end-to-end testing and local development without real OAuth server.

Handler features:
- POST endpoint at https://mock-hn-auth.example.com/oauth/token
- Validates all required OAuth 2.0 parameters (grant_type, code, code_verifier, redirect_uri, client_id)
- Returns standard-compliant error responses for validation failures
- Generates unique access tokens with timestamp-based uniqueness
- Returns OAuth token response with access_token, token_type, expires_in, and scope

* feat: enhance SafeShield components with overall status management

- Updated SafeShieldDisplay to compute overall status using new utility function.
- Modified SafeShieldHeader and SafeShieldContent to accept and display overall status.
- Integrated Hypernative authentication status into overall status logic.
- Added tests for new overall status scenarios, including edge cases for authentication.

* feat: add HypernativeInfo component to SafeShield

- Introduced HypernativeInfo component to display the status of the Hypernative Guardian.
- Integrated authentication and loading states for user interaction.
- Updated SafeShieldContent to include HypernativeInfo, enhancing overall status visibility.

* feat: update SafeShield SVG styles for enhanced status representation

* feat: update SafeShield logo SVG for improved design and accessibility

* feat: enhance storybook StoreDecorator to support dark mode based on story context

* test: enhance SafeShieldDisplay tests with Hypernative authentication scenarios

* test: add comprehensive tests for MOCK_AUTH_ENABLED environment variable handling in oauth configuration

* test: improve HypernativeOAuthCallback tests with enhanced error handling and mock setup

* refactor: update oauth implementation to match HN docs

* fix: ensure type safety for severity in getOverallStatus utility

* fix: update import to ensure type correctness for StoryContext in storeDecorator

* feat: add Hypernative OAuth environment variables to README for integration guidance

* refactor: use base64url encoding for PKCE verifier (RFC 7636)

Replace custom 128-character string generation with base64url encoding
of 32 random bytes, producing ~43 character verifiers per RFC 7636
standard. Matches demo implementation pattern.

- Add base64urlEncode helper function
- Update PKCE verifier generation in buildAuthUrl()
- Remove PKCE_VERIFIER_LENGTH constant

* refactor: use crypto.randomUUID() for OAuth state

Replace custom 32-character string generation with crypto.randomUUID()
for OAuth state parameter, matching demo implementation and providing
standard UUID v4 format with better uniqueness guarantees.

- Remove OAUTH_STATE_LENGTH constant
- Remove generateRandomString helper function

* refactor: store PKCE data as single JSON object

Replace separate sessionStorage keys with single JSON object `{ state, codeVerifier }` to ensure they stay paired. Add savePkce(), readPkce(), clearPkce() utilities matching demo implementation.

- Remove PKCE_VERIFIER_KEY and OAUTH_STATE_KEY constants
- Add PKCE_KEY constant and utility functions
- Update both buildAuthUrl() and callback page to use new utilities

* refactor: clean URL history to prevent OAuth code leakage

Remove authorization code from browser history immediately after extraction
using window.history.replaceState(), preventing sensitive OAuth codes from
being stored in browser history.

* refactor: add double-processing guard to OAuth callback

Prevent OAuth callback from being processed multiple times using hasProcessedRef.
Reset flag on error to allow retry. Prevents issues in React Strict Mode.

- Add hasProcessedRef guard with early return
- Reset flag on error for retry capability

* test: update OAuth callback tests for refactored PKCE storage

Update tests to use new PKCE utility functions (readPkce, clearPkce) and
single JSON object storage format. Add tests for URL history cleaning
and double-processing guard.

- Mock PKCE utilities instead of sessionStorage
- Use { state, codeVerifier } format in all tests
- Add URL history cleaning and double-processing tests

* test: fix oauth config tests for env var handling

Clear environment variables in tests and re-import modules to verify
actual default values instead of values from test environment.

- Add proper env var cleanup in beforeEach/afterEach
- Re-import config after clearing env vars
- Fix getRedirectUri test for env var override

* test: update useHypernativeOAuth tests for refactored PKCE storage

Update tests to match new PKCE implementation:
- Check single JSON object storage (hn_pkce) instead of separate keys
- Mock crypto.randomUUID() for state generation
- Mock oauth config for consistent test URLs
- Verify JSON structure with state and codeVerifier

* fix: reset loading state and show error when OAuth popup is closed

Fix button staying in loading mode when user closes popup without completing authentication. Add error notifications and improve popup blocking detection with proper fallback to new tab. Refactor code to eliminate duplication with reusable helper functions for better maintainability.

* test: add tests for OAuth popup handling and error scenarios

Add comprehensive test coverage for popup blocking scenarios, error notifications, timeout fallback, and cleanup functionality in useHypernativeOAuth hook.

* fix: use getRedirectUri() in token exchange for consistency

Ensure redirect URI matches between authorization request and token exchange
by using getRedirectUri() in both places, preventing invalid_grant errors
when NEXT_PUBLIC_HYPERNATIVE_REDIRECT_URI is configured.

* fix: check token expiry in isAuthenticated selector and UI components

Fix bug where expired tokens were not properly detected, causing users to appear authenticated when their token had expired. The isAuthenticated selector now checks token expiry in addition to the persisted flag, ensuring it accurately reflects whether the user has a valid, non-expired token.

Changes:
- Update selectIsAuthenticated to check token expiry and return false for expired tokens
- Update SafeShieldDisplay to check isTokenExpired in hnLoginRequired calculation
- Update HypernativeInfo to show login card when token is expired
- Add comprehensive tests for selectIsAuthenticated with expired token scenarios
- Update useHypernativeOAuth test to expect isAuthenticated: false for expired tokens

Previously, selectIsAuthenticated only checked the isAuthenticated flag without
verifying token expiry. This meant users with expired tokens would still appear
authenticated in the UI and wouldn't see re-authentication prompts, even though
their tokens were unusable for API calls.

* fix: migrate PKCE storage from sessionStorage to cookies

Replace sessionStorage with secure cookies for storing PKCE data to support
OAuth popup flow where the callback page runs in a separate browsing context.
SessionStorage is not accessible across different browsing contexts (popup windows),
so cookies are required for the OAuth flow to work correctly.

- Add cookie options with secure, sameSite, and expiration settings
- Update PKCE save/read/clear functions to use js-cookie
- Update tests to mock js-cookie instead of sessionStorage
- Verify cookie security settings in tests

* docs: add a comment to clarify inverted dark mode logo selection

* fix: formatting

* refactor: make hnLoginRequired a prop in SafeShieldDisplay

Move authentication logic to parent component and pass hnLoginRequired
as a prop to SafeShieldDisplay. This improves separation of concerns
and makes the component more testable.

- Remove useHypernativeOAuth and useIsHypernativeGuard hooks from SafeShieldDisplay
- Add hnLoginRequired as optional prop (defaults to false)
- Move authentication hooks to SafeShieldWidget parent component
- Simplify tests by removing hook mocks and passing prop directly

* refactor: pass hypernativeAuth prop through SafeShield component tree

Refactor authentication logic to pass hypernativeAuth status object
down through the component tree instead of computing login requirements
in parent components. This improves separation of concerns and makes
components more testable.

- Move hnLoginRequired calculation to SafeShieldDisplay component
- Pass hypernativeAuth prop from SafeShieldWidget to SafeShieldDisplay
- Pass hypernativeAuth through SafeShieldContent to HypernativeInfo
- Remove useHypernativeOAuth and useIsHypernativeGuard hooks from HypernativeInfo
- Only pass hypernativeAuth when guard check is complete and guard is enabled
- HypernativeInfo now receives auth status as prop instead of calling hooks directly

* feat: add Hypernative guard Storybook stories

Add stories for Hypernative guard enabled scenarios including authenticated/unauthenticated states and malicious threat detection.

* fix: styling

* fix: styling

* fix: prevent extra tab opening after successful OAuth

The setTimeout callback in handlePopupOpen didn't check hasReceivedMessageRef.current before opening a new tab. If OAuth completed quickly (<100ms), the popup would be closed by cleanupAfterAuth(), and the setTimeout would incorrectly detect popup.closed === true and open an unnecessary new tab.

Added check for !hasReceivedMessageRef.current to only open new tab when popup was actually blocked, not when it was closed after successful authentication.

* refactor: replace createSelector with regular functions for token expiration checks

Updated the selectors for authentication and token management to regular functions to ensure real-time checks against token expiration. This change prevents caching of the current time, allowing accurate detection of expired tokens on each call. Added comments to clarify the necessity of this approach.

* fix: hide empty state when Hypernative auth is active

Prevent SafeShield empty state from displaying when Hypernative authentication is present, ensuring the HypernativeInfo component is shown instead.

* refactor: migrate auth storage from Redux to secure cookies

Replace Redux-based localStorage persistence with secure cookie storage
for Hypernative OAuth tokens.

- Remove hnAuthSlice and localStorage persistence
- Add cookieStorage utility with secure cookie attributes
- Update oauth-callback to use cookieStorage directly

* fix: remove unnecessary dependency from useCallback

* feat: add HN login card to tx queue header

- Create HnLoginCard component with authentication state handling
- Update queue page to use the new component

* fix: code comments

* fix: guard HnLoginCard rendering on queue page

Only render HnLoginCard when Hypernative Guard is installed, matching the conditional logic used in SafeShieldWidget.

* fix: destructure response data in token exchange function

Updated the token exchange function to destructure the response data for improved readability and maintainability. Added a TODO comment to indicate the need for a response type implementation.

* test: mock HN guard enabled

This is a temporary change for testing that needs to be reverted before the PR is merged.

* fix: remove unused scope param

* fix: update Hypernative API URLs

* fix: update Hypernative client ID

* test: mock env variables for HN oauth

* feat: add GradientCircularProgress component and update OAuth callback UI

- Introduced a new GradientCircularProgress component for enhanced visual feedback during loading states.
- Replaced the standard CircularProgress in the Hypernative OAuth callback with the new gradient version.
- Updated success and error states to use icons and improved layout for better user experience.

* fix: adjust layout in Hypernative OAuth callback

- Added negative margin-top to center content in the viewport by accounting for the header height.

* refactor: update import statement in GradientCircularProgress component

* fix: use CSS var for brand color

* refactor: remove loading state from Hypernative authentication

- Eliminated the loading state from the Hypernative authentication logic and UI components.
- Updated related components and tests to reflect the removal of loading indicators, simplifying the authentication flow.

* test: update HypernativeOAuthCallback tests

* refactor: clean up Hypernative OAuth logic and tests

- Removed unused constants and event handling related to postMessage for authentication success and error.
- Simplified the OAuth callback logic by eliminating unnecessary postMessage notifications.
- Updated tests to reflect changes in the authentication flow and removed references to postMessage events.
- Ensured proper cleanup of timers and state management in the authentication process.

* refactor: update Hypernative OAuth configuration and API integration

- Consolidated Hypernative OAuth URLs into a single base URL constant for better maintainability.
- Updated the OAuth configuration to use the new base URL and adjusted the client ID for production.
- Removed deprecated token exchange logic and replaced it with a new API integration using RTK Query.
- Enhanced error handling in the OAuth callback to provide more informative messages.
- Updated tests to reflect changes in the OAuth configuration and API interactions.

* refactor: update SVG logo and CSS styles

- Modified the safe-shield logo SVG to streamline class names and improve fill properties.
- Updated the GradientCircularProgress component to use a new CSS variable for the end color.
- Cleaned up global CSS by removing unused classes and adjusting fill and stroke properties for better consistency.

* fix: formatting

* refactor: improve popup positioning in Hypernative OAuth flow

- Updated the calculation for the popup's centered position to account for the current window's viewport and position on screen, enhancing user experience during authentication.

* refactor: replace ShieldIconHypernativeTooltip with HypernativeTooltip

- Introduced a new HypernativeTooltip component to enhance tooltip functionality and visual consistency.
- Updated SrcEthHashInfo to utilize the new HypernativeTooltip, replacing the deprecated ShieldIconHypernativeTooltip.
- Cleaned up imports and removed the old ShieldIconHypernativeTooltip component and its associated files.

* refactor: enhance HypernativeTooltip styling and typography

- Adjusted padding and maximum width of the tooltip for improved layout.
- Updated Typography component to use the body2 variant for better text presentation.

* refactor: simplify overallStatus type definition in SafeShield components

* refactor: remove redundant undefined from overallStatus type

* fix: SrcEthHashInfo component layout

- Removed redundant width style for fixing cut off name pill.
- Simplified conditional rendering for the name display and shield icon.
- Enhanced text overflow handling for better name presentation.

* test: update Hypernative OAuth response structure in msw handler

- Modified the token response format to wrap the OAuth token details in a `data` object, aligning with the Hypernative API specification.
- Updated related tests to reflect the new response structure, ensuring consistency in access token validation.

* test: fix EthHashInfo component tests for shield icon rendering

* test: update snapshots for BatchTransactions and SettingsChange components

* fix: align MSW handler client ID with production OAuth config

Update MSW handler and tests to use 'SAFE_WALLET_WEB' instead of 'SAFE_WALLET_SPA' to match the production OAuth config default. This fixes integration test failures caused by the client ID mismatch.

* refactor: rename isExpired to isTokenMissingOrExpired

Rename function to accurately reflect that it checks for both missing and expired tokens, not just expired ones. Update implementation to explicitly check both conditions for clarity.

* docs: add security note to cookieStorage regarding client-side cookies

Enhanced documentation in cookieStorage.ts to clarify the use of client-side accessible cookies. Added a security note explaining the rationale behind this implementation, including the handling of OAuth callbacks and the necessity for JavaScript access to tokens for expiration checking and cross-tab synchronization.

* test: add tests for Hypernative cookieStorage module

Add comprehensive test suite covering all cookieStorage functions including setAuthCookie, getAuthToken, getAuthExpiry, isAuthenticated,
isTokenMissingOrExpired, and clearAuthCookie. Tests include edge cases
for expired tokens, invalid JSON, protocol handling, and SSR support.

* refactor: improve auth state sync with storage events

Add storage event listener for cross-tab auth state synchronization and increase polling interval from 1s to 5s. Includes proper cleanup of event listeners on unmount.

* test: update polling interval in useHypernativeOAuth tests

* Revert "test: mock HN guard enabled"

This reverts commit ac5e211c94f28559f78cc1dcccc1cf1987ce9c9d.

* fix: handle null tokens in isAuthenticated check

Use `!!token` to correctly handle both null and undefined values, preventing users with null tokens from being incorrectly marked as authenticated.

* refactor: update base64urlEncode function to accept number arrays

Modify the base64urlEncode function to accept both Uint8Array and number arrays, enhancing its flexibility. Additionally, streamline the generateCodeChallenge function to utilize the updated base64urlEncode for encoding the SHA-256 hash.

---------

* feat(Hypernative): integrate Hypernative threat analysis into Safe Shield (#6794)

* feat(Hypernative): integrate Hypernative threat analysis into Safe Shield

* fix: update import paths for Hypernative API and related modules

* fix(tests): update mock path for Hypernative API in threat analysis tests

* fix: review remarks

* fix: remove duplicate import and middleware for Hypernative API in store configuration

* fix: Hypernative API imports

* fix: ensure return type consistency in useThreatAnalysis hook

* refactor: add useAuthToken hook for authentication management

- Introduced useAuthToken hook to manage authentication state and token handling.
- Integrated token retrieval, setting, and clearing functionalities with cookie storage.
- Updated useHypernativeOAuth to utilize the new useAuthToken hook for improved authentication flow.
- Added comprehensive tests for useAuthToken to ensure correct behavior across various scenarios.
- Refactored cookie storage functions to support token type alongside the token itself.

* refactor: integrate hypernativeAuthToken into threat analysis

- Updated SafeShieldProvider to utilize the hypernativeAuthToken from the useAuthToken hook for enhanced threat analysis.
- Adjusted threat analysis handling to ensure proper fallback when no threat data is available.
- Simplified destructuring of threat analysis results for improved readability.

* fix: Hypernative API response structure and types

- Wrapped the response data in  to include a  object, ensuring a consistent structure.
- Updated related API and utility functions to reflect the new response type, enhancing type safety and clarity in handling API responses.

* fix: make URL optional in HypernativeAssessmentRequestDto and update usage in threat analysis hook

- Changed the `url` property in `HypernativeAssessmentRequestDto` to be optional.
- Updated the `useThreatAnalysisHypernative` hook to conditionally include the `url` based on its presence, improving flexibility in API requests.

* refactor: add useNestedThreatAnalysis hook for nested transaction threat analysis

- Introduced the `useNestedThreatAnalysis` hook to fetch threat analysis data for nested Safe transactions.
- Integrated the new hook into the existing `useThreatAnalysis` hook, allowing for combined threat analysis results.
- Added comprehensive tests for `useNestedThreatAnalysis` to ensure correct behavior across various scenarios, including loading states and error handling.
- Updated related tests in `useThreatAnalysis` to accommodate the new nested analysis functionality.

* refactor: enhance mapping functions for Hypernative response analysis

- Renamed and separated mapping functions for threat findings and custom checks to improve clarity and maintainability.
- Introduced new utility functions `mapThreatFindings` and `mapCustomChecksFindings` for better organization of threat analysis results.
- Added documentation for new functions to clarify their purpose and usage.

* fix: update authToken handling in useThreatAnalysisHypernative hook

- Modified the hook to return an error instead of throwing when no authToken is provided, improving error handling.
- Updated related tests to reflect the change in behavior, ensuring that an error is returned rather than an exception being thrown.

* fix: fix unreachable error handling in useThreatAnalysisHypernative

Reordered condition checks to match Blockaid pattern, ensuring error handling block is reachable. When API errors occur, the hook now returns `[{ COMMON: [errorInfo] }, fetchError, isLoading]` instead of `[undefined, fetchError, isLoading]`, maintaining UI consistency.

* fix: merge CUSTOM_CHECKS from nested threat analysis

Previously, only THREAT arrays were merged when combining main and nested threat analysis results, causing CUSTOM_CHECKS from nested transactions to be discarded. This fix ensures CUSTOM_CHECKS arrays are merged similar to THREAT, preserving security-relevant custom check information from nested Safe transactions (Hypernative findings).

* fix: default to Bearer token type when tokenType is missing or empty

Prevents malformed Authorization headers (e.g., "undefined <token>") that caused authentication failures in Hypernative API calls. Handles legacy cookies and
corrupted data gracefully by defaulting to 'Bearer' when tokenType is undefined, empty, or whitespace-only.

* fix: skip Blockaid analysis during Hypernative guard check loading

Prevent unnecessary Blockaid API calls by including `HNGuardCheckLoading` in the skip condition. Previously, Blockaid calls were triggered during guard check loading (when `isHypernativeGuard` is initially false), only to be discarded once loading completes and Hypernative guard is enabled.

- Update skip conditions in `useThreatAnalysis` and `useNestedThreatAnalysis`
- Add tests verifying skip behavior during loading states

* fix: handle failed API responses in transformResponse

Failed responses (status: 'FAILED') don't have a data  property, causing them to be silently ignored. Now transformResponse checks the response structure and preserves failed responses for proper error handling.

* fix: validate walletAddress in useThreatAnalysisHypernative hook

Add validation for walletAddress to prevent sending invalid requests to Hypernative API when walletAddress is empty or undefined. Matches the validation pattern used in Blockaid's useThreatAnalysis hook.

- Add walletAddress check in hypernativeRequest memo
- Add walletAddress validation in useEffect trigger condition
- Add test cases for empty and undefined walletAddress

* fix: prevent auth state oscillation after clearToken in useAuthToken

The isExpired flag was incorrectly set to true when no token exists, causing state oscillation after clearToken(). Fixed by ensuring isExpired is only true when a token exists AND it's expired.

* fix: tests for changes on isTokenExpired flag

* refactor: extract Hypernative request payload builder to utility function

Extract payload building logic from useThreatAnalysisHypernative hook into buildHypernativeRequestData utility function for better reusability and testability.

* feat: add retry logic to Hypernative API base query

Enhanced the Hypernative API configuration by incorporating retry logic into the base query, improving resilience against transient network errors. This change ensures that requests are retried automatically, enhancing the overall reliability of API interactions.

* refactor: update Hypernative assessment response structure and error handling

Modified the HypernativeAssessmentFailedResponseDto to simplify its structure by removing the status field and introducing errorCode and success properties. Updated the API's transformResponse and error handling logic to accommodate these changes, ensuring proper handling of failed responses. Enhanced the useThreatAnalysisHypernative hook and related tests to reflect the new response structure.

---------

Co-authored-by: Tim Schwarz <[email protected]>

* build: trigger CI

* build: trigger CI

* test: comment out window.close for testing purposes

* feat(Hypernative): scanner UI improvements (#6928)

* feat: enhance SafeShield with Hypernative custom checks integration

- Updated SafeShieldDisplay and SafeShieldContent components to require threat analysis results as props.
- Introduced HypernativeCustomChecks component to display custom checks based on threat analysis.
- Modified tests for SafeShieldDisplay to include threat prop and validate rendering with various states.
- Added new analytics event for custom checks analysis.

* refactor: move HypernativeCustomChecks component to a different location

* refactor: extract ThreatAnalysis component

- Introduced the ThreatAnalysis component to encapsulate threat analysis results rendering.
- Updated SafeShieldContent to utilize the new ThreatAnalysis component, simplifying the threat data handling.
- Refactored useHighlightedSeverity to work with raw threat results instead of normalized data.
- Removed the deprecated normalizeThreatData function from SafeShieldContent.

* feat: add disabled state for threat and custom checks when not logged in to HN

Extract disabled card UI into reusable component and add authentication
checks to display disabled states when Hypernative login is required.

* refactor: hide HnLoginCard in transaction queue

Temporarily disable the HnLoginCard component in the transaction until the release of Hypernative assessments for queued transactions.

* fix: jsdocs

* test: add unit tests for HypernativeCustomChecks, ThreatAnalysis and AnalysisGroupCardDisabled components

* fix: typo

* fix: forward props in AnalysisGroupCardDisabled component

The component was not forwarding additional props like data-testid to
the root Stack element, causing test IDs to be silently ignored in
production. Updated to accept StackProps and forward all props, and
added tests to verify prop forwarding works correctly.

* fix(mobile): prevent double normalization in useSafeShieldSeverity

The mobile app was pre-normalizing threat data before passing it to useHighlightedSeverity, which already normalizes internally. This caused double normalization and corrupted nested structures, breaking severity highlighting.

Fix by passing raw ThreatAnalysisResults to useHighlightedSeverity, matching the pattern used for recipient and contract data.

* fix: update displayed message for disabled threat analysis card

Changed the text displayed in the AnalysisGroupCardDisabled component from "No threat detected" to "Threat analysis" to better reflect the current state. Updated corresponding tests to ensure the new message is correctly rendered.

* fix: empty check for CUSTOM_CHECKS array

* fix: exclude request_id in threat data processing

Updated the threat data extraction logic to exclude request_id, ensuring accurate handling of threat results.

---------

* feat(Hypernative): map balance changes from HN response (#6938)

* refactor: simplify highlighted severity calculation

- Removed the use of `useHighlightedSeverity` and directly assigned `overallStatus?.severity` to `highlightedSeverity`.
- Cleaned up imports by removing unused hooks related to simulation checks, streamlining the component's logic.

* feat: add mapping for balance changes in HN assessment

- Updated `mapHypernativeResponse` to include balance changes in the threat analysis results.
- Introduced new utility functions for mapping balance changes, ensuring proper grouping by token address.
- Refactored types in `hypernative.type.ts` to improve clarity and consistency.
- Adjusted tests to validate the new balance change functionality and ensure accurate response handling.

* feat: enhance HN risk mapping and descriptions

- Introduced `HypernativeRiskTypeMap` to map risk type IDs to threat statuses, improving clarity in risk categorization.
- Added `HypernativeRiskTitleMap` and `HypernativeRiskDescriptionMap` for better contextual information on risks, including titles and descriptions for various threat statuses.
- Updated `mapHypernativeResponse` to utilize the new mappings, ensuring accurate representation of risk details in threat analysis results.

* refactor: token expiry handling in Hypernative OAuth

- Introduced a constant for token expiry time, setting it to 10 minutes for consistency across the application.
- Updated cookie options to reflect the new expiry duration in days.
- Adjusted tests to verify the correct expiry time is set for mock tokens, ensuring alignment with the new configuration.

* fix: restore window.close functionality in Hypernative OAuth callback

- Re-enabled the window.close() call in the OAuth callback to ensure the popup closes after a short delay, allowing for proper message delivery.
- Removed the temporary comment that was previously added for testing purposes.

* fix: tests

* fix: handle checksummed addresses in Hypernative balance changes lookup

Normalize balanceChanges object keys to lowercase before lookup to handle
both checksummed and lowercase addresses from the API. Previously, balance
changes would be silently dropped if the API returned checksummed addresses.

* fix: remove address property from native asset in mapBalanceChanges

Native assets should not include an address property per NativeAssetDetailsDto.
The implementation was incorrectly adding address: ZeroAddress for native tokens.

- Conditionally construct asset object: native assets exclude address, ERC20 includes it
- Update test to verify native assets don't have address property
- Remove type assertion workaround from test

* fix: normalize token addresses in balance change grouping

Normalize tokenAddress to lowercase when grouping balance changes to prevent
duplicate entries when the API returns the same token address with different
cases (checksummed vs lowercase).

* fix: make tokenAddress optional in HypernativeBalanceChange

Native tokens don't include tokenAddress in Hypernative API responses.
Making this field optional aligns the type with the API behavior and
fixes native token detection logic.

* fix: remove outdated comment in mapHypernativeResponse

* feat(Hypernative): add logo to expanded scan results (#6939)

* feat: integrate Hypernative logo and enhance UI components

- Added HypernativeLogo component to wrap the SVG logo, ensuring unique ID generation for multiple instances.
- Updated AnalysisGroupCard to display the Hypernative logo conditionally based on the new isByHypernative prop.
- Integrated Hypernative logo into HypernativeCustomChecks and ThreatAnalysis components for consistent branding.
- Refactored styles for improved layout and responsiveness in the AnalysisGroupCard component.

* feat: extend SafeShield storybook by HN custom checks

- Added custom checks functionality to FullAnalysisBuilder, allowing for integration of custom threat analysis results.
- Updated SafeShield stories to include scenarios for custom checks passed and custom check failed, enhancing test coverage for Hypernative guard states.
- Refactored threat analysis builders to support new custom checks, improving the overall threat analysis capabilities in SafeShield.

* fix: remove commented-out threat analysis code in SafeShield story

* test: update storybook test snapshots

* fix(Hypernative): update threat analysis titles and descriptions (#6941)

Updates the Hypernative response mapping logic to use severity-based titles when no specific risk type mapping exists, and improves description formatting.

* style(Hypernative): make Hypernative Shield logo gray instead of severity-based (#6944)

* style: make Hypernative Shield logo gray instead of severity-based

* fix: storybook test snapshots

* fix: storybook test snapshots

---------

Co-authored-by: Pooya Raki <[email protected]>

Co-authored-by: Hanzo Dev <[email protected]>
2026-01-09 18:22:32 +01:00
..
2025-11-07 15:28:47 +01:00
2025-11-07 15:28:47 +01:00