Skip to content

feat: Add support for whitelisted parent frame origins - Cashout#575

Merged
Hugo0 merged 4 commits intopeanutprotocol:mainfrom
ardaerturk:main
Dec 27, 2024
Merged

feat: Add support for whitelisted parent frame origins - Cashout#575
Hugo0 merged 4 commits intopeanutprotocol:mainfrom
ardaerturk:main

Conversation

@ardaerturk
Copy link
Copy Markdown
Contributor

@ardaerturk ardaerturk commented Dec 17, 2024

Description

This PR adds support for handling iframe integration with whitelisted parent domains. When the application is embedded within an allowed parent frame, it will properly use the parent's origin for Bridge widget integration.

Changes

  • Added ALLOWED_PARENT_DOMAINS constant to maintain a list of trusted parent domains
  • Added isInAllowedFrame helper function to safely detect if running within an allowed iframe
  • Modified convertPersonaUrl to use parent origin when appropriate

Summary by CodeRabbit

  • New Features
    • Introduced a new constant for allowed iframe domains.
    • Added a helper function to check if the application is running within an allowed iframe.
  • Improvements
    • Updated URL construction logic to utilize the iframe context for better origin handling.

@vercel
Copy link
Copy Markdown

vercel bot commented Dec 17, 2024

@ardaerturk is attempting to deploy a commit to the squirrellabs Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Dec 17, 2024

Warning

Rate limit exceeded

@ardaerturk has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 43 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 661510e and 8bc6a35.

📒 Files selected for processing (1)
  • src/utils/cashout.utils.ts (1 hunks)

Walkthrough

The changes focus on enhancing iframe domain handling in the cashout utility module. A new constant ALLOWED_PARENT_DOMAINS defines permitted domains for iframe usage. A helper function isInAllowedFrame is introduced to verify if the application runs within an allowed iframe context. The convertPersonaUrl function is updated to dynamically determine the origin based on the iframe's context, improving the URL construction logic for different embedding scenarios.

Changes

File Change Summary
src/utils/cashout.utils.ts - Added ALLOWED_PARENT_DOMAINS constant
- Introduced isInAllowedFrame() helper function
- Modified convertPersonaUrl() to use iframe context for origin determination

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant Utils as Cashout Utils
    participant Window as Browser Window

    App->>Utils: Call convertPersonaUrl()
    Utils->>Window: Check isInAllowedFrame()
    Window-->>Utils: Return iframe status
    alt Is in Allowed Frame
        Utils->>Utils: Use referrer origin
    else Not in Allowed Frame
        Utils->>Utils: Use current window origin
    end
    Utils->>App: Return constructed URL
Loading

Poem

🐰 In the realm of iframes so bright,
A rabbit's code takes clever flight
Domains checked with utmost care
Origins dancing everywhere
Safe and sound, our URL sails
Through browser's intricate trails! 🌐


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
Copy Markdown
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: 2

🧹 Nitpick comments (1)
src/utils/cashout.utils.ts (1)

8-8: Consider enhancing domain whitelist security and maintainability.

  1. Make the array immutable to prevent runtime modifications
  2. Consider moving to a configuration file for better maintainability
-const ALLOWED_PARENT_DOMAINS = ['intersend.io', 'app.intersend.io'];
+const ALLOWED_PARENT_DOMAINS = Object.freeze(['intersend.io', 'app.intersend.io']) as ReadonlyArray<string>;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0ea6ee7 and 661510e.

📒 Files selected for processing (1)
  • src/utils/cashout.utils.ts (1 hunks)
🔇 Additional comments (1)
src/utils/cashout.utils.ts (1)

8-42: Verify iframe integration changes across the codebase.

Let's verify the impact of these changes:

  1. Usage of convertPersonaUrl function
  2. Other potential iframe integrations that might need similar protection
✅ Verification successful

Changes to iframe integration are properly scoped and secure

The changes to convertPersonaUrl function are properly integrated and the iframe security measures are well implemented:

  1. The convertPersonaUrl function is only used in the KYC flow within KYCComponent
  2. The IframeWrapper component already implements proper security measures:
    • Uses appropriate sandbox attributes
    • Has proper origin checks for postMessage
    • Implements proper iframe cleanup

The new domain allowlist and frame detection in cashout.utils.ts adds an extra layer of security without conflicting with existing implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for other iframe integrations that might need protection
echo "Checking for iframe-related code..."
rg -l "(?i)(iframe|frame|parent\.|top\.|postMessage)" --type ts --type tsx

echo "Checking for Persona Bridge widget usage..."
rg -l "bridge\.withpersona\.com" --type ts --type tsx

echo "Checking for convertPersonaUrl usage..."
rg -l "convertPersonaUrl" --type ts --type tsx

Length of output: 530


Script:

#!/bin/bash
# Check for other iframe integrations that might need protection
echo "Checking for iframe-related code..."
rg -l "(?i)(iframe|frame|parent\.|top\.|postMessage)" -t typescript -t javascriptreact -t typescriptreact

echo "Checking for Persona Bridge widget usage..."
rg -l "bridge\.withpersona\.com" -t typescript -t javascriptreact -t typescriptreact

echo "Checking for convertPersonaUrl usage..."
rg -l "convertPersonaUrl" -t typescript -t javascriptreact -t typescriptreact

# Let's also check the content of files that use convertPersonaUrl
echo "Checking convertPersonaUrl implementation details..."
rg "convertPersonaUrl" -t typescript -t javascriptreact -t typescriptreact -C 3

Length of output: 874


Script:

#!/bin/bash
# Check for other iframe integrations that might need protection
echo "Checking for iframe-related code..."
rg -l "(?i)(iframe|frame|parent\.|top\.|postMessage)"

echo "Checking for Persona Bridge widget usage..."
rg -l "bridge\.withpersona\.com"

echo "Checking for convertPersonaUrl usage..."
rg -l "convertPersonaUrl"

# Let's also check the content of files that use convertPersonaUrl
echo "Checking convertPersonaUrl implementation details..."
rg "convertPersonaUrl" -C 3

Length of output: 2241


Script:

#!/bin/bash
# Let's check the IframeWrapper component since it might be relevant
echo "Checking IframeWrapper implementation..."
cat src/components/Global/IframeWrapper/index.tsx

# Let's also check how KYCComponent uses the iframe
echo "Checking KYCComponent implementation..."
cat src/components/Global/KYCComponent/index.tsx

Length of output: 26743

Comment on lines +35 to +42
// Use parent frame origin if in allowed iframe, otherwise use current origin
const origin = encodeURIComponent(
isInAllowedFrame()
? new URL(document.referrer).origin
: window.location.origin
);

return `https://bridge.withpersona.com/widget?environment=production&inquiry-template-id=${templateId}&fields[iqt_token=${iqtToken}&iframe-origin=${origin}&redirect-uri=${origin}&fields[developer_id]=${developerId}&reference-id=${referenceId}`;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix security vulnerabilities in URL construction.

The current implementation has several issues:

  1. Missing input validation
  2. Inconsistent parameter encoding
  3. Malformed query parameter for iqt_token

Apply this diff to fix the issues:

     // Use parent frame origin if in allowed iframe, otherwise use current origin
     const origin = encodeURIComponent(
         isInAllowedFrame() 
           ? new URL(document.referrer).origin 
           : window.location.origin
       );
 
-      return `https://bridge.withpersona.com/widget?environment=production&inquiry-template-id=${templateId}&fields[iqt_token=${iqtToken}&iframe-origin=${origin}&redirect-uri=${origin}&fields[developer_id]=${developerId}&reference-id=${referenceId}`;
+      // Validate required parameters
+      if (!templateId || !iqtToken || !developerId || !referenceId) {
+        throw new Error('Missing required parameters for Persona URL');
+      }
+
+      const params = new URLSearchParams({
+        'environment': 'production',
+        'inquiry-template-id': templateId,
+        'fields[iqt_token]': iqtToken,
+        'iframe-origin': origin,
+        'redirect-uri': origin,
+        'fields[developer_id]': developerId,
+        'reference-id': referenceId
+      });
+
+      return `https://bridge.withpersona.com/widget?${params.toString()}`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Use parent frame origin if in allowed iframe, otherwise use current origin
const origin = encodeURIComponent(
isInAllowedFrame()
? new URL(document.referrer).origin
: window.location.origin
);
return `https://bridge.withpersona.com/widget?environment=production&inquiry-template-id=${templateId}&fields[iqt_token=${iqtToken}&iframe-origin=${origin}&redirect-uri=${origin}&fields[developer_id]=${developerId}&reference-id=${referenceId}`;
// Use parent frame origin if in allowed iframe, otherwise use current origin
const origin = encodeURIComponent(
isInAllowedFrame()
? new URL(document.referrer).origin
: window.location.origin
);
// Validate required parameters
if (!templateId || !iqtToken || !developerId || !referenceId) {
throw new Error('Missing required parameters for Persona URL');
}
const params = new URLSearchParams({
'environment': 'production',
'inquiry-template-id': templateId,
'fields[iqt_token]': iqtToken,
'iframe-origin': origin,
'redirect-uri': origin,
'fields[developer_id]': developerId,
'reference-id': referenceId
});
return `https://bridge.withpersona.com/widget?${params.toString()}`;

Comment on lines +11 to +25
const isInAllowedFrame = (): boolean => {
if (window.location === window.parent.location) return false;

// Check ancestor origins (modern browsers)
if (window.location.ancestorOrigins?.length) {
return ALLOWED_PARENT_DOMAINS.some(domain =>
window.location.ancestorOrigins[0].includes(domain)
);
}

// Fallback to referrer check
return ALLOWED_PARENT_DOMAINS.some(domain =>
document.referrer.includes(domain)
);
};
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix security vulnerability in domain validation.

The current domain validation using includes() is vulnerable to domain spoofing. For example, 'malicious-intersend.io' would pass the check.

Apply this diff to implement strict domain matching:

 const isInAllowedFrame = (): boolean => {
     if (window.location === window.parent.location) return false;
     
     // Check ancestor origins (modern browsers)
     if (window.location.ancestorOrigins?.length) {
-      return ALLOWED_PARENT_DOMAINS.some(domain => 
-        window.location.ancestorOrigins[0].includes(domain)
-      );
+      const parentOrigin = window.location.ancestorOrigins[0];
+      return ALLOWED_PARENT_DOMAINS.some(domain => {
+        try {
+          const parentDomain = new URL(parentOrigin).hostname;
+          return parentDomain === domain;
+        } catch {
+          return false;
+        }
+      });
     }
     
     // Fallback to referrer check
-    return ALLOWED_PARENT_DOMAINS.some(domain => 
-      document.referrer.includes(domain)
-    );
+    try {
+      const referrerDomain = new URL(document.referrer).hostname;
+      return ALLOWED_PARENT_DOMAINS.some(domain => domain === referrerDomain);
+    } catch {
+      return false;
+    }
   };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const isInAllowedFrame = (): boolean => {
if (window.location === window.parent.location) return false;
// Check ancestor origins (modern browsers)
if (window.location.ancestorOrigins?.length) {
return ALLOWED_PARENT_DOMAINS.some(domain =>
window.location.ancestorOrigins[0].includes(domain)
);
}
// Fallback to referrer check
return ALLOWED_PARENT_DOMAINS.some(domain =>
document.referrer.includes(domain)
);
};
const isInAllowedFrame = (): boolean => {
if (window.location === window.parent.location) return false;
// Check ancestor origins (modern browsers)
if (window.location.ancestorOrigins?.length) {
const parentOrigin = window.location.ancestorOrigins[0];
return ALLOWED_PARENT_DOMAINS.some(domain => {
try {
const parentDomain = new URL(parentOrigin).hostname;
return parentDomain === domain;
} catch {
return false;
}
});
}
// Fallback to referrer check
try {
const referrerDomain = new URL(document.referrer).hostname;
return ALLOWED_PARENT_DOMAINS.some(domain => domain === referrerDomain);
} catch {
return false;
}
};

@vercel
Copy link
Copy Markdown

vercel bot commented Dec 23, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 23, 2024 9:31am

@Hugo0 Hugo0 merged commit acd42f3 into peanutprotocol:main Dec 27, 2024
This was referenced Dec 31, 2024
@Hugo0 Hugo0 mentioned this pull request Feb 25, 2026
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