Skip to content

πŸ›‘οΈ Sentinel: [HIGH] Fix insecure postMessage target origin and origin verification#18

Open
AGI-Corporation wants to merge 4 commits intomainfrom
sentinel/fix-oauth-postmessage-origin-3844969624917860543
Open

πŸ›‘οΈ Sentinel: [HIGH] Fix insecure postMessage target origin and origin verification#18
AGI-Corporation wants to merge 4 commits intomainfrom
sentinel/fix-oauth-postmessage-origin-3844969624917860543

Conversation

@AGI-Corporation
Copy link
Copy Markdown
Owner

@AGI-Corporation AGI-Corporation commented Mar 16, 2026

🚨 Severity: HIGH
πŸ’‘ Vulnerability:

  1. Insecure postMessage target origin: The /redirect endpoint used a wildcard * as the target origin for postMessage, which could allow malicious sites to intercept OAuth authorization codes.
  2. Improper origin verification: The frontend used startsWith for origin verification, which can be bypassed.

🎯 Impact: An attacker could potentially steal OAuth authorization codes if they can get a reference to the redirect window.

πŸ”§ Fix:

  1. Updated /redirect in packages/server/api/src/app/app.ts to resolve the platform-specific origin using domainHelper and use it as the target origin.
  2. Updated getCode in packages/react-ui/src/lib/oauth2-utils.ts to use strict equality (===) for origin verification.

βœ… Verification:

  1. Verified code changes and imports.
  2. Ran ESLint on modified files to ensure no linting errors.
  3. Fixed typo in redirect message.

PR created automatically by Jules for task 3844969624917860543 started by @AGI-Corporation

Summary by CodeRabbit

  • Bug Fixes

    • Improved OAuth authentication security with stricter origin verification to prevent unauthorized code interception.
    • Fixed typo in OAuth redirect success message.
  • Documentation

    • Added security guidance documenting OAuth origin handling vulnerabilities and remediation recommendations.

… verification

- Restrict postMessage target origin in backend `/redirect` endpoint to the platform's public origin.
- Use strict equality for origin verification in frontend OAuth2 utility.
- Fix typo in redirect message.

Co-authored-by: AGI-Corporation <186229839+AGI-Corporation@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

πŸ‘‹ Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a πŸ‘€ emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 16, 2026

πŸ“ Walkthrough

Walkthrough

This PR addresses OAuth security vulnerabilities by implementing proper origin verification and dynamic target origin resolution in cross-origin postMessage calls, moving away from insecure wildcard targets and inadequate startsWith validation.

Changes

Cohort / File(s) Summary
Documentation & Security Guidelines
.jules/sentinel.md
Added two sentinel entries documenting OAuth origin handling vulnerabilities and their remediation strategies, including platformUtils-based origin derivation and strict equality checks.
Frontend OAuth Validation
packages/react-ui/src/lib/oauth2-utils.ts
Refined cross-origin validation in getCode to derive expected origin from redirectUrl and enforce strict equality (===) instead of startsWith matching for origin verification.
Backend OAuth Redirect Handler
packages/server/api/src/app/app.ts
Integrated platformUtils to determine platformId from request, derive targetOrigin dynamically from platform's public URL, and replace wildcard postMessage target with computed origin. Fixed typo in redirect HTML text.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A hop through origins, securing the way,
No wildcards loose to lead us astray,
With strict equality and platform in hand,
OAuth's now safer, as planned! ✨

πŸš₯ Pre-merge checks | βœ… 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
βœ… Passed checks (2 passed)
Check name Status Explanation
Title check βœ… Passed The title accurately summarizes the main security fix: addressing insecure postMessage target origin and origin verification vulnerabilities in OAuth handling.
Description check βœ… Passed The description is well-structured and covers severity, vulnerabilities, fixes, and verification, but deviates from the template which requires 'What does this PR do?', 'Explain How the Feature Works', and 'Relevant User Scenarios' sections.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • πŸ“ Generate docstrings (stacked PR)
  • πŸ“ Generate docstrings (commit on current branch)
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sentinel/fix-oauth-postmessage-origin-3844969624917860543
πŸ“ Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

πŸ’‘ Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 97e544be16

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with πŸ‘.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +256 to +262
const targetOrigin = new URL(publicUrl).origin
return reply
.type('text/html')
.send(
`<script>if(window.opener){window.opener.postMessage({ 'code': '${encodeURIComponent(
params.code,
)}' },'*')}</script> <html>Redirect succuesfully, this window should close now</html>`,
)}' }, '${targetOrigin}')}</script> <html>Redirect successfully, this window should close now</html>`,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve opener origin when posting OAuth code

The /redirect handler now hard-codes postMessage to the platform public origin, which can differ from the actual opener origin for valid deployments (for example, a platform with a custom domain where users are still on the default cloud host, or any alternate frontend host behind the same backend). In those cases the browser drops the message because targetOrigin does not match window.opener’s real origin, so OAuth popups never resolve and connection/login flows hang.

Useful? React with πŸ‘Β / πŸ‘Ž.

… verification

- Restrict postMessage target origin in backend `/redirect` endpoint to the platform's public origin.
- Use strict equality for origin verification in frontend OAuth2 utility.
- Fix typo in redirect message.
- Ensure correct import order for linting.

Co-authored-by: AGI-Corporation <186229839+AGI-Corporation@users.noreply.github.com>
Copy link
Copy Markdown

@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

πŸ€– Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/react-ui/src/lib/oauth2-utils.ts`:
- Around line 77-82: The message handler currently only checks origin and
redirectUrl which is vulnerable to same-origin forged posts; update the handler
in oauth2-utils.ts to also verify event.source matches the popup window
reference you opened (e.g. the auth popup variable used when launching OAuth)
before accepting event.data['code'], and ensure you remove the listener after
success; reference the existing handler function, event, expectedOrigin, and
redirectUrl when implementing the event.source === popupWindowRef check.

ℹ️ Review info
βš™οΈ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e6884ca8-125d-4b10-afcd-ec5383512c3f

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between f61e720 and 97e544b.

πŸ“’ Files selected for processing (3)
  • .jules/sentinel.md
  • packages/react-ui/src/lib/oauth2-utils.ts
  • packages/server/api/src/app/app.ts

Comment on lines 77 to 82
window.addEventListener('message', function handler(event) {
if (
redirectUrl &&
redirectUrl.startsWith(event.origin) &&
event.origin === expectedOrigin &&
event.data['code']
) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n --type=ts -C3 "addEventListener\\('message'" packages/react-ui/src/lib/oauth2-utils.ts
rg -n --type=ts -C3 "event\\.source\\s*===\\s*currentPopup|currentPopup\\s*===\\s*event\\.source" packages/react-ui/src/lib/oauth2-utils.ts

Repository: AGI-Corporation/Route.X

Length of output: 384


🏁 Script executed:

#!/bin/bash
# Read the full context around the handler
sed -n '70,95p' packages/react-ui/src/lib/oauth2-utils.ts

# Search for currentPopup declaration and usage in the file
rg -n "currentPopup" packages/react-ui/src/lib/oauth2-utils.ts

Repository: AGI-Corporation/Route.X

Length of output: 889


🏁 Script executed:

#!/bin/bash
# Check if there are other message listeners in the file
rg -n "addEventListener.*message" packages/react-ui/src/lib/oauth2-utils.ts

# Look at the openWindow function to understand the popup context
rg -n -B2 -A8 "function openWindow" packages/react-ui/src/lib/oauth2-utils.ts

# Check the full file to see the complete flow
wc -l packages/react-ui/src/lib/oauth2-utils.ts

Repository: AGI-Corporation/Route.X

Length of output: 415


Bind OAuth message acceptance to the popup window (event.source) as well as origin.

event.origin === expectedOrigin is necessary, but not sufficient for popup integrity. A different same-origin window can still post a forged { code } message and satisfy this check.

πŸ” Proposed hardening
 function getCode(redirectUrl: string): Promise<string> {
   const expectedOrigin = new URL(redirectUrl).origin;
   return new Promise<string>((resolve) => {
     window.addEventListener('message', function handler(event) {
       if (
-        redirectUrl &&
+        event.source === currentPopup &&
         event.origin === expectedOrigin &&
-        event.data['code']
+        typeof event.data === 'object' &&
+        event.data !== null &&
+        'code' in event.data &&
+        typeof (event.data as { code?: unknown }).code === 'string'
       ) {
-        resolve(decodeURIComponent(event.data.code));
+        resolve(decodeURIComponent((event.data as { code: string }).code));
         currentPopup?.close();
         window.removeEventListener('message', handler);
       }
     });
   });
 }
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/react-ui/src/lib/oauth2-utils.ts` around lines 77 - 82, The message
handler currently only checks origin and redirectUrl which is vulnerable to
same-origin forged posts; update the handler in oauth2-utils.ts to also verify
event.source matches the popup window reference you opened (e.g. the auth popup
variable used when launching OAuth) before accepting event.data['code'], and
ensure you remove the listener after success; reference the existing handler
function, event, expectedOrigin, and redirectUrl when implementing the
event.source === popupWindowRef check.

google-labs-jules bot and others added 2 commits March 16, 2026 08:03
- Restrict postMessage target origin in backend `/redirect` endpoint to the platform's public origin.
- Use strict equality for origin verification in frontend OAuth2 utility.
- Fix typo in redirect message.
- Correct import order in `app.ts`.

Co-authored-by: AGI-Corporation <186229839+AGI-Corporation@users.noreply.github.com>
- Restrict postMessage target origin in backend `/redirect` endpoint.
- Use strict equality for origin verification in frontend OAuth utility.
- Fix typo in redirect message and correct import order.

Co-authored-by: AGI-Corporation <186229839+AGI-Corporation@users.noreply.github.com>
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.

1 participant