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

feat: added iframe detection and auto resolving for exit action #2867

Merged
merged 3 commits into from
Nov 28, 2024

Conversation

chesterkmr
Copy link
Collaborator

@chesterkmr chesterkmr commented Nov 27, 2024

image
image

Summary by CodeRabbit

  • New Features

    • Introduced a utility function to detect if the application is running in an iframe.
    • Enhanced exit handling logic to track exit events based on iframe detection.
  • Bug Fixes

    • Updated conditions for tracking exit actions, ensuring they are triggered appropriately when in an iframe.
  • Chores

    • Updated subproject reference to the latest commit.

@chesterkmr chesterkmr requested a review from alonp99 November 27, 2024 11:16
Copy link

changeset-bot bot commented Nov 27, 2024

⚠️ No Changeset found

Latest commit: 18a217e

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

Walkthrough

A new utility function isIframe has been added to determine if the current window is within an iframe. This function checks the relationship between window.self and window.top, and includes error handling for cross-origin access. Additionally, the useAppExit hook has been modified to incorporate this iframe detection, affecting how exit actions are triggered based on the presence of an iframe or specific exit actions. A commit hash for a subproject has also been updated without any functional changes.

Changes

File Path Change Summary
apps/kyb-app/src/common/utils/is-iframe.ts Added utility function isIframe to check if the window is in an iframe with cross-origin handling.
apps/kyb-app/src/hooks/useAppExit/useAppExit.ts Modified useAppExit to include isIframe, altering exit event tracking conditions and updating dependencies.
services/workflows-service/prisma/data-migrations Updated subproject commit hash from a0c3055b4df212f7d4cf13a200593fe4de2ae909 to fd8fd971694ef091eba2b3ca586441c98b7e13e7.

Possibly related PRs

Suggested reviewers

  • Omri-Levy

Poem

🐇 In a world of frames, both near and far,
I check the skies, where the iframe are.
With a hop and a skip, I track the exit's flight,
Ensuring all bunnies are safe and bright!
So if you're in a frame, do not despair,
Just call on me, I’ll always be there! 🌟

Warning

Rate limit exceeded

@chesterkmr has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 34 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between bd9516f and 18a217e.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bd9516f and 18a217e.

📒 Files selected for processing (2)
  • apps/kyb-app/src/common/utils/is-iframe.ts (1 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/kyb-app/src/common/utils/is-iframe.ts
  • services/workflows-service/prisma/data-migrations

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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 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
Contributor

@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: 3

🧹 Outside diff range and nitpick comments (4)
apps/kyb-app/src/common/utils/is-iframe.ts (1)

1-17: Consider caching the result for better performance.

Since the iframe status won't change during runtime, consider memoizing the result to avoid redundant checks.

+let isIframeCache: boolean | null = null;
+
 export const isIframe = (): boolean => {
+  if (isIframeCache !== null) {
+    return isIframeCache;
+  }
+
   try {
     // Check if window.self and window.top are the same reference
     const isFramed = window.self !== window.top;

     // Additional security check - try to access parent
     // This will throw an error if cross-origin
     if (isFramed) {
       window.parent.location.origin;
     }

-    return isFramed;
+    isIframeCache = isFramed;
+    return isIframeCache;
   } catch (e: unknown) {
     // If we get a security error, we're definitely in a cross-origin iframe
-    return true;
+    isIframeCache = true;
+    return isIframeCache;
   }
 };
apps/kyb-app/src/hooks/useAppExit/useAppExit.ts (3)

Line range hint 18-29: Add error handling for trackEvent call

While the logic for handling iframe and exit actions is correct, consider adding error handling for the tracking event to ensure robustness.

   if (kybOnExitAction === 'send-event' || isIframe()) {
-    trackEvent(CollectionFlowEvents.USER_EXITED);
+    try {
+      trackEvent(CollectionFlowEvents.USER_EXITED);
+    } catch (error) {
+      console.error('Failed to track exit event:', error);
+    }
     return;
   }

33-33: Improve readability of isExitAvailable logic

The current ternary expression could be made more readable by splitting it into separate conditions.

-    isExitAvailable: kybOnExitAction === 'send-event' || isIframe() ? true : !!customer?.websiteUrl,
+    isExitAvailable: (() => {
+      if (kybOnExitAction === 'send-event' || isIframe()) {
+        return true;
+      }
+      return !!customer?.websiteUrl;
+    })(),

Line range hint 9-36: Consider splitting the hook for better separation of concerns

The useAppExit hook currently handles multiple responsibilities: iframe detection, exit action handling, and customer portal redirection. Consider splitting this into smaller, more focused hooks:

  • useIframeDetection
  • useExitAction
  • useCustomerRedirect

This would improve maintainability and make the code more testable.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c83a724 and bd9516f.

📒 Files selected for processing (3)
  • apps/kyb-app/src/common/utils/is-iframe.ts (1 hunks)
  • apps/kyb-app/src/hooks/useAppExit/useAppExit.ts (3 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • services/workflows-service/prisma/data-migrations
🔇 Additional comments (3)
apps/kyb-app/src/common/utils/is-iframe.ts (2)

1-17: LGTM! The implementation correctly handles iframe detection and cross-origin security.

The function properly checks for iframes using window references and includes appropriate error handling for cross-origin scenarios.


1-17: Verify browser compatibility of the window APIs.

The implementation uses standard window APIs. Let's verify their browser support to ensure compatibility across different browsers and versions.

✅ Verification successful

Browser compatibility is verified and supported

The implementation uses well-supported window APIs (window.self, window.top, window.parent) that are compatible with modern browsers. This is confirmed by:

  • The project's browserslist configuration which targets modern browsers (>0.2%, not dead, not IE 11)
  • The consistent usage of these APIs across the codebase without any special polyfills or fallbacks
  • The implementation follows standard cross-origin security patterns with proper error handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for any browser compatibility issues or workarounds in the codebase
# Look for similar window.self, window.top, and window.parent usage patterns

# Search for similar iframe detection patterns
rg -A 2 "window\.(self|top|parent)" --type ts --type js

# Search for any browser compatibility comments or issues
rg -i "browser.*(compatibility|support).*iframe" --type ts --type js

Length of output: 2092


Script:

#!/bin/bash
# Let's check for any polyfills, fallbacks, or browser-specific code related to window APIs
rg -i "(polyfill|fallback|browser|compatibility).*(window|iframe)" --type ts --type js

# Check package.json for any browser compatibility configurations or polyfills
fd "package.json" --exec cat {} \; | jq -r '.browserslist, .targets, .engines'

# Look for any browser-specific tests or test cases
rg -i "test.*(window|iframe)" --type ts --type js

Length of output: 798

apps/kyb-app/src/hooks/useAppExit/useAppExit.ts (1)

1-1: Verify the implementation of the imported iframe detection utility

Let's ensure the imported isIframe utility is implemented correctly and handles edge cases.

✅ Verification successful

Implementation of isIframe utility is robust and secure

The isIframe utility is well-implemented with proper security considerations:

  • Correctly checks window references (window.self !== window.top)
  • Handles cross-origin scenarios with try-catch block
  • Includes additional security verification by attempting to access parent origin
  • Returns appropriate boolean values for both same-origin and cross-origin cases
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of isIframe utility
# Expected: The utility should handle cross-origin access and various window contexts

# Search for the implementation
ast-grep --pattern 'export const isIframe = $_' 

Length of output: 17370

apps/kyb-app/src/common/utils/is-iframe.ts Outdated Show resolved Hide resolved
apps/kyb-app/src/common/utils/is-iframe.ts Show resolved Hide resolved
@chesterkmr chesterkmr force-pushed the illiar/feat/kyb-iframe-detection branch from 7553719 to c7368b0 Compare November 28, 2024 11:27
@chesterkmr chesterkmr merged commit 7fbcebc into dev Nov 28, 2024
10 checks passed
@chesterkmr chesterkmr deleted the illiar/feat/kyb-iframe-detection branch November 28, 2024 11:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants