Skip to content
XSS Write-up Intermediate

Cross-Origin postMessage DOM XSS: From a Missing Origin Check to Authenticated Account Compromise

A postMessage listener accepted redirect messages from any origin without checking the sender, and the attacker-supplied destination was passed through an HTML sanitiser before being assigned to a navigation sink. Because HTML sanitisation does not restrict URL schemes, a dangerous scheme could survive and run script in the trusted origin, giving access to same-origin authenticated APIs.

redhunter01 Follow

Published on medium.com

Cybersecurity

redhunter01, on medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 12 min read.

Context

During reconnaissance of a large consumer web application, the researcher found a window.postMessage handler belonging to a third-party voting integration. The feature is a voting modal: a route resembling /voting/:activityId renders a component that embeds a third-party iframe, and the message listener is registered when that integration loads.

The handler looked like this:

JavaScript
window.addEventListener("message", function (event) {    if (        event.data &&        event.data.action === "redirect" &&        event.data.options &&        event.data.options.link    ) {        window.location.href = sanitize(event.data.options.link);    }});

The application trusted messages from every origin. The check that should have been there was absent:

JavaScript
if (event.origin !== TRUSTED_ORIGIN) return;

A missing origin check is not automatically XSS, but it gives an attacker-controlled source. The real question is where that value goes, and here it reached window.location.href. Following the application architecture further, the issue escalated from JavaScript execution to authenticated account actions.

Setup

The report does not describe the target by name, the programme, the accounts used or any tool versions. What it does describe is the testing approach: reading minified JavaScript bundles, identifying dependencies from strings inside them, reproducing library behaviour locally with the exact installed version, and validating browser behaviour across engines. For cross-browser work the researcher names Playwright entry points:

JavaScript
chromium.launch()firefox.launch()webkit.launch()

One precondition shaped the whole exercise: the vulnerable code existed permanently, but the trigger depended on an active campaign. The listener was only registered when the third-party voting integration loaded, so reachability had to be established separately from code existence.

Finding it

The starting point was a search of JavaScript bundles for cross-window communication patterns:

Text
addEventListener("message"

and:

Text
window.onmessage

These patterns appear in OAuth integrations, payment widgets, surveys, voting systems, embedded forms, customer-support widgets, advertising, authentication flows and third-party SDKs. The security boundary matters because postMessage lets documents from different origins talk to each other, so a safe handler verifies the sender, for example:

JavaScript
window.addEventListener("message", event => {    if (event.origin !== "https://trusted.example") {        return;
JavaScript
    // process message});

The handler found here performed multiple actions based entirely on event.data. Conceptually, event.data.action === "redirect" caused location.href = event.data.options.link, with no validation of event.origin. That produced an immediate hypothesis: any website may be able to instruct the victim application to navigate somewhere. The next task was to find out whether that navigation could become JavaScript execution.

Exploitation

Step 1: trace source, transformation and sink

The data flow was mapped in three parts.

Source:

Text
event.data.options.link

An external page could potentially control this through postMessage.

Transformation: the value passed through a function that appeared to sanitise it, conceptually sanitizeHtml(value).

Sink:

Text
window.location.href

So the flow became:

Text
Cross-origin postMessage        ↓event.data.options.link        ↓HTML sanitizer        ↓window.location.href

At this point one detail mattered enormously: what exactly did the sanitizer protect against?

Step 2: identify the sanitizer library

The bundle contained minified module references, so the next task was to identify which library implemented the sanitizer. Useful clues were strings relating to:

Text
allowedSchemesnaughtyHrefsanitize-html

This identified the dependency as an HTML sanitisation library. Rather than assuming its behaviour, the researcher reproduced it locally:

JavaScript
const sanitizeHtml = require("sanitize-html");
JavaScript
console.log(    sanitizeHtml("SOME_TEST_VALUE"));

Testing the exact installed version is better still. The questions this answers are whether it normalises whitespace, lowercases schemes, removes URLs, behaves differently on raw strings, and whether configuration changes the output. The same method applies to DOMPurify, sanitize-html, validator.js, lodash, marked, axios, React Router and Next.js helpers: do not rely solely on documentation, test the exact behaviour.

Step 3: classify the sink

For window.location.href = attackerControlledValue, possible values include:

Text
https://example.com/about/profilemailto:[redacted]:...data:...

The browser interprets the scheme, so the security question is not whether the value is valid HTML but which URL schemes are allowed. The application used an HTML sanitizer before assigning the value to a URL navigation sink. An HTML sanitizer is designed for input resembling:

HTML
<b>Hello</b><script>alert(1)</script>

It may remove unsafe HTML elements, but a plain URL-like string may contain no HTML at all. A dangerous URI scheme can therefore survive because there is nothing for the HTML parser to sanitise. The bug was not that the sanitizer was broken; the bug was that the wrong type of sanitizer was used for the sink.

Step 4: understand the browser primitive

A missing postMessage origin validation bug usually looks like this on the sender side:

JavaScript
victimWindow.postMessage(    {        action: "redirect",        options: {            link: attackerControlledValue        }    },    "*");

The browser delivers a MessageEvent carrying event.data, event.origin and event.source. If the application only checks event.data and ignores event.origin, it has lost one of the browser's primary trust boundaries:

Text
Attacker origin      |      | postMessage()      vVictim origin      |      | missing origin verification      vTrusted application logic

Step 5: check that the vulnerable route actually loads

Finding vulnerable code in a bundle does not guarantee users can reach it. The vulnerable handler belonged to a voting modal, and a route resembling /voting/:activityId rendered the relevant component, which then created the third-party iframe. The listener was registered when that integration loaded. The three states are distinct:

Text
Code exists     ↓Feature reachable     ↓Exploit trigger active

Modern SPAs frequently return the application shell for arbitrary routes. For example:

Text
/voting/123/voting/456/voting/test

may all return:

HTML
<div id="root"></div><script src="/static/main.js"></script>

and React Router decides what component to render. During testing, verify:

HTTP
GET /interesting/route

and inspect whether the response includes the main SPA bundle. Also inspect router definitions, searching for:

Text
path:createBrowserRouter<RouteuseParams/voting/

Step 6: analyse the authentication context

JavaScript execution becomes significantly more serious inside an authenticated origin. The application exposed same-origin APIs for profile validation, wallet and point balances, rewards, challenges, polls and surveys. Because injected JavaScript executes as the application origin, browser requests inherit the victim's authenticated session:

JavaScript
fetch("/api/profile", {    credentials: "include"});

The browser automatically supplies eligible session cookies. HttpOnly cookies do not prevent XSS from using the victim's session: HttpOnly protects against document.cookie, but attacker-controlled script can still call:

JavaScript
fetch("/api/account")fetch("/api/rewards")fetch("/api/profile")

because the browser sends cookies automatically. The impact chain is therefore XSS, then authenticated API access, then PII exposure, then account actions, then account compromise, rather than alert(1).

Step 7: map the authenticated API surface

Once XSS is confirmed, the researcher built an impact map instead of jumping to destructive testing, reviewing network requests, JavaScript bundles, API clients, route definitions, GraphQL operations, Redux actions and service modules, and classifying endpoints:

Category Example
Identity profile / account details
Financial-like value points / credits / rewards
State changes challenge participation
User content votes / surveys
Account security email / password / MFA
Privileged actions administration

For this case the interesting classes were profile information, loyalty identifiers, points balance, reward redemption, challenge actions and voting actions. That changed the report from "DOM XSS exists" into "attacker-controlled JavaScript executes inside an authenticated loyalty application and can interact with privileged same-origin APIs".

Step 8: check browser differences

An exploit primitive that works in Chromium may behave differently in Firefox or Safari, so cross-browser validation is part of serious client-side testing. Useful environments listed were Chrome, Chromium, Edge, Firefox and Safari / WebKit. For this class of navigation behaviour, Chromium-family browsers allowed the relevant programmatic navigation while Firefox imposed stricter user-activation requirements. The correct claim is therefore that the demonstrated exploit chain affects Chromium-family browsers under the tested conditions, not that all users are vulnerable.

Step 9: check security headers

Whenever a client-side injection issue is found, inspect the response headers: Content-Security-Policy, X-Frame-Options, Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy and Referrer-Policy. For XSS specifically, CSP can provide additional defence. A strong policy might contain:

Text
script-src 'self' 'nonce-...'object-src 'none'base-uri 'none'frame-ancestors 'none'

CSP is defence in depth; the primary bug still needs fixing. For postMessage that means validating the sender, and for URL navigation it means validating the destination.

Step 10: consider popup versus iframe authentication

Modern cookies may use SameSite=Lax, SameSite=Strict or SameSite=None, and whether cookies are sent can depend on browsing context. An embedded third-party iframe may not receive the same cookies as a top-level navigation. When assessing a cross-origin attack, consider iframe, popup, top-level navigation, same-site navigation and cross-site subresource request, and ask under which browser context the authenticated session actually accompanies the request. Do not assume that a cookie existing means every context gets it.

Step 11: build a local replica

When production testing is limited, a minimal replica of the vulnerable behaviour is valuable. This applies when bot protection blocks automation, login requires unavailable credentials, destructive actions must be avoided, the feature is temporarily inactive, or reproducing against production would affect users. A good replica contains an attacker origin, a victim origin, the message listener, the same sanitizer version, the same sink, a mock authenticated endpoint and browser automation. The goal is not to invent behaviour but to reproduce the verified production data flow:

Text
attacker.test      |      | cross-origin postMessage      vvictim.test      |      | vulnerable listener      vnavigation sink      |      vscript execution      |      vmock authenticated API

This proves mechanically that input reaches the sink, executes, and produces an authenticated request, without abusing a production account.

Step 12: keep production and replica evidence separate

The report suggests separating production evidence, such as the handler existing or origin validation missing, from replica evidence. Verified in a controlled replica were: the browser executes the navigation, script executes in the victim origin, the authenticated API response can be accessed, and data can leave the origin. The report should never claim full account takeover reproduced in production if only the complete chain was reproduced locally; it should explain exactly which links were verified where.

Root cause

The architectural mistake was an HTML sanitizer feeding a URL sink:

Text
HTML sanitizer        ↓URL sink

Sanitisation is context-specific. Different sinks require different validation:

Text
HTML context        → HTML sanitizationHTML attribute      → attribute encodingJavaScript context  → JS escapingSQL query           → parameterizationURL destination     → URL scheme validation

The handler accepted messages from any origin, and the only transformation applied was one designed for HTML. A URL-like string with a dangerous scheme contains no HTML for the sanitizer to act on, so it survived and was assigned to window.location.href. The correct model would have been:

Text
Untrusted URL        ↓URL parser        ↓scheme allowlist        ↓hostname allowlist        ↓navigation

A safer pattern would be:

JavaScript
const url = new URL(value, window.location.origin);
JavaScript
if (url.protocol !== "https:") {    return;}window.location.href = url.href;

potentially with hostname restrictions:

JavaScript
const allowedHosts = new Set([    "trusted.example.com"]);
JavaScript
if (!allowedHosts.has(url.hostname)) {    return;}

The recurring pattern is a correct-looking sanitizer combined with the wrong security context.

Impact

The full chain was:

Text
[1] Cross-origin communication        ↓[2] Missing event.origin validation        ↓[3] Attacker controls redirect destination        ↓[4] HTML sanitizer used instead of URL validator        ↓[5] Dangerous navigation scheme survives        ↓[6] JavaScript executes in trusted origin        ↓[7] Victim session is available        ↓[8] Same-origin authenticated APIs become accessible        ↓[9] PII and loyalty actions exposed

The chain, if completed, would let an attacker page send a crafted message that leads to script execution in the application origin. In an authenticated session the script could reach same-origin APIs covering profile information, loyalty identifiers, point balances, reward redemption, challenge and voting actions. The demonstrated chain affects Chromium-family browsers under the tested conditions; Firefox imposed stricter user-activation requirements for the relevant navigation behaviour. The trigger also depended on an active campaign, since the listener was registered only when the third-party voting integration loaded.

Fix

There are multiple layers to fix.

Validate the message origin:

JavaScript
const TRUSTED_ORIGINS = new Set([    "https://trusted-widget.example"]);
JavaScript
window.addEventListener("message", event => {    if (!TRUSTED_ORIGINS.has(event.origin)) {        return;    }    // handle message});

For stronger validation, also verify event.source when the expected window reference is known.

Validate URLs as URLs rather than using an HTML sanitizer for navigation security:

JavaScript
function safeRedirect(value) {    const url = new URL(value, window.location.origin);
JavaScript
    if (url.protocol !== "https:") {        throw new Error("Unsupported protocol");    }    return url.href;}

Restrict hostnames if external navigation is unnecessary. Even better, prefer semantic actions over arbitrary URLs: instead of accepting

JavaScript
{    action: "redirect",    link: "https://..."}

accept

JavaScript
{    action: "openRewards"}

and map the action internally:

JavaScript
const destinations = {    openRewards: "/rewards",    openProfile: "/profile"};

so the external sender never supplies the destination at all. Finally, add a strong Content Security Policy as an additional boundary; it should not replace the application-level fix but can significantly reduce the impact of future injection bugs.

Variants to test

  1. Search bundles for addEventListener("message", onmessage and postMessage(. A positive result is a handler that reads event.data without a nearby event.origin, e.origin, allowedOrigins or trustedOrigins check.
  2. Identify which message fields are controllable: event.data.url, event.data.redirect, event.data.link, event.data.html, event.data.command, event.data.action. A positive result is any field that changes application behaviour.
  3. Trace those fields to high-value sinks: location.href, location.assign, location.replace, innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, Function, script.src, iframe.src, form.action. A positive result is attacker-controlled data reaching one of them.
  4. Identify every transformation (sanitize(), escape(), encode(), validate(), normalize()) and the actual library behind it. A positive result is a transformation whose purpose does not match the sink, such as HTML sanitisation before a URL sink.
  5. Reproduce the library locally with the exact package version, testing normal input, mixed case, whitespace, encoded characters, scheme variations, relative URLs and absolute URLs. A positive result is a dangerous scheme surviving the transformation.
  6. Determine reachability: route, feature flag, campaign ID, iframe condition, component lifecycle and authentication requirement. A positive result is a route that returns the SPA bundle and mounts the vulnerable component.
  7. Determine execution context: iframe, popup, top-level page or sandboxed frame. A positive result is execution in the trusted application origin rather than an isolated one.
  8. Map authenticated capabilities once execution is established, prioritising profile, account, billing, wallet, rewards, email, security settings and administrative functions. A positive result is a same-origin API returning victim data to the injected script.
  9. Validate across Chromium, Firefox and WebKit. A positive result is a documented difference in behaviour, so the report states exactly which browsers are affected.
  10. Document conditions such as requiring login, requiring one click, Chromium only, feature active only during campaigns, or a specific account state. Stating constraints makes the report more credible, not weaker.

Useful ripgrep searches for this workflow:

Bash
rg 'addEventListener\(["\'\'']message' .
Bash
rg 'postMessage\(' .
Bash
rg 'location\.(href|assign|replace)' .
Bash
rg 'event\.origin|e\.origin' .

The pattern worth manual review is a message handler with no origin validation nearby and a security-sensitive sink. Not every missing origin check is exploitable: a handler that only calls console.log(e.data), or one that checks e.data === "resize" before resizing a widget, generally has little security impact. Severity rises when attacker-controlled messages influence navigation, HTML, authentication, account state, sensitive APIs, payments, tokens or privileged actions. Always follow the data.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 32 min read.

What happened, in plain words

A security researcher was looking around a large consumer website, the kind of site where people log in, collect points and take part in campaigns. While reading the site's JavaScript (the code that runs inside your browser and makes the page interactive), the researcher found a small piece of code that listens for messages sent from other web pages. That code belonged to a voting feature that embeds a widget made by another company.

The problem was that this code accepted messages from absolutely any website, without checking who sent them. Worse, it took a link from the message and told the browser to go to that link. If an attacker could send a specially crafted link, the browser might run attacker code inside the trusted site while the victim was logged in. From there, the attacker's code could potentially reach same-origin APIs for profile data, points balances and reward actions, because the browser attaches the victim's cookies automatically.

This article walks through the whole story step by step, explaining every technical idea from scratch. You only need to know how to use a browser and a computer to follow it.

1. Start with message handlers

What is postMessage?

Web pages are not allowed to freely read each other's content. That rule is called the same-origin policy, and it is one of the main safety walls of the web. An origin is the combination of protocol (http or https), hostname (like example.com) and port. Two pages with the same origin can talk freely; pages with different origins are kept apart.

Sometimes pages from different origins genuinely need to talk, for example a payment widget embedded in a shop. Browsers provide a controlled way to do this: window.postMessage. One page calls postMessage on another window and hands it a message. The receiving page gets an event, and that event carries three useful pieces of information:

  • event.data: the actual content of the message.
  • event.origin: which origin sent it.
  • event.source: a reference to the window that sent it.

Think of it like a building with a mail slot. Anyone on the street can drop a letter through the slot. The safe thing for the person inside is to check the return address before acting on the letter. If they act on every letter without looking at who sent it, a stranger can give them instructions.

Why the researcher searched for these handlers

Cross-window communication appears everywhere on modern sites: login integrations (OAuth), payment widgets, surveys, voting systems, embedded forms, customer-support chat widgets, advertising, authentication flows and third-party software kits (SDKs). Because so many features rely on it, searching for it is a productive way to start an audit.

The researcher searched the site's JavaScript files for two patterns:

Text
addEventListener("message"

This is the standard way to say "run this function whenever a message arrives". The text addEventListener("message" is the literal code that registers a listener for message events.

Text
window.onmessage

This is an older, alternative way to do the same thing: assign a function to window.onmessage and it will be called for every incoming message.

What a safe handler looks like

A safe handler checks the sender before doing anything. The report shows this example:

JavaScript
window.addEventListener("message", event => {    if (event.origin !== "https://trusted.example") {        return;
JavaScript
    // process message});

Line by line:

  • window.addEventListener("message", event => { registers a function that runs every time a message arrives. The function receives an event object.
  • if (event.origin !== "https://trusted.example") { compares the sender's origin with the one trusted origin. If they differ, the condition is true.
  • return; stops the function immediately, so nothing else happens for untrusted senders.
  • // process message is a comment marking where the real work would happen, only for trusted senders.
  • }); closes the function and the registration.

The key idea: the check happens first, before any action.

What the researcher actually found

The handler on this site did several things based entirely on event.data, with no check of event.origin. In plain terms, if the message said action was redirect and included a link, the code set location.href to that link. location.href is the browser's address bar: assigning to it makes the browser navigate to a new address.

That gave the researcher an immediate hypothesis: any website might be able to tell the victim's browser to go somewhere. The next question was whether that navigation could be turned into running attacker code.

2. Trace source, transformation and sink

Security researchers use three words to describe how untrusted data moves through a program:

  • Source: where attacker-controlled data enters.
  • Transformation: anything the program does to the data in between.
  • Sink: the dangerous operation where the data finally lands.

If you can draw a line from a source you control to a sink that matters, you have a vulnerability. This way of thinking is called data flow analysis.

For this bug the three parts were:

Source:

Text
event.data.options.link

This means: inside the message content (event.data), look at the options object, and inside it the link field. An external page could potentially put anything it liked in that field through postMessage.

Transformation: the value passed through a function that appeared to sanitise it, conceptually sanitizeHtml(value). Sanitising means cleaning input so it is safe. The name suggested HTML cleaning.

Sink:

Text
window.location.href

This is the browser navigation sink. Assigning a value here tells the browser to go to that address.

So the flow became:

Text
Cross-origin postMessage        ↓event.data.options.link        ↓HTML sanitizer        ↓window.location.href

Read this diagram top to bottom: a message arrives from another origin, the link field is extracted, it passes through an HTML sanitizer, and the result is assigned to the address bar. At this point one detail mattered enormously: what exactly did the sanitizer protect against?

3. Never trust a function because it is called "sanitise"

This was the most important lesson from the finding.

Developers often assume that calling sanitize(userInput) means the value is now safe everywhere. That is incorrect. Sanitisation is context-specific: the right cleaning depends on where the value will be used.

Different sinks require different validation:

Text
HTML context        → HTML sanitizationHTML attribute      → attribute encodingJavaScript context  → JS escapingSQL query           → parameterizationURL destination     → URL scheme validation

Line by line:

  • HTML context → HTML sanitization: if the value will be placed between HTML tags, you clean it by removing dangerous HTML.
  • HTML attribute → attribute encoding: if the value goes inside an HTML attribute, you encode characters so it cannot break out of the attribute.
  • JavaScript context → JS escaping: if the value goes into JavaScript code, you escape it so it cannot become code.
  • SQL query → parameterization: if the value goes into a database query, you use parameters so it cannot change the query's meaning.
  • URL destination → URL scheme validation: if the value becomes a link the browser will follow, you must check which kind of link it is.

Think of it like cleaning a kitchen. You would not use the same cleaner for a wooden table and for drinking water. The cleaner might be excellent for one job and dangerous for the other. A sanitizer is the same: excellent for one context, useless for another.

The application used an HTML sanitizer before assigning the value to a URL navigation sink. Those are different security contexts.

An HTML sanitizer is designed for input resembling:

HTML
<b>Hello</b><script>alert(1)</script>

Line by line:

  • <b>Hello</b> is bold text. Harmless.
  • <script>alert(1)</script> is a script tag. If a page inserted this into its HTML, the browser would run the JavaScript inside it, here showing a popup with 1. An HTML sanitizer would typically remove the script tag.

But a plain URL-like string may contain no HTML at all. Therefore a dangerous URI scheme can survive because there is nothing for the HTML parser to sanitise. The bug was not that the sanitizer was broken. The real bug was that the wrong type of sanitizer was used for the sink.

4. Classify the sink correctly

Consider:

Text
window.location.href = attackerControlledValue

Possible values include:

Text
https://example.com/about/profilemailto:[redacted]:...data:...

Line by line:

  • https://example.com/about/profile is a normal web address. The browser loads that page.
  • mailto:[redacted] tells the browser to open an email program addressed to that person.
  • javascript:... tells the browser to run the JavaScript that follows as if it were part of the page. This is the dangerous one.
  • data:... embeds content directly in the address, which can also be abused.

The part before the colon is called the scheme. The browser interprets the scheme to decide what to do. Therefore the security question is not "is this valid HTML?" but "which URL schemes are allowed?".

A safer pattern would be:

JavaScript
const url = new URL(value, window.location.origin);
JavaScript
if (url.protocol !== "https:") {    return;}window.location.href = url.href;

Line by line:

  • const url = new URL(value, window.location.origin); parses the value as a URL using the browser's built-in URL parser. The second argument is a base address used for relative links.
  • if (url.protocol !== "https:") { checks whether the scheme is exactly https:. If not, the condition is true.
  • return; stops, so anything other than https is refused.
  • window.location.href = url.href; navigates only to the parsed, checked address.

Potentially with hostname restrictions as well:

JavaScript
const allowedHosts = new Set([    "trusted.example.com"]);
JavaScript
if (!allowedHosts.has(url.hostname)) {    return;}

Line by line:

  • const allowedHosts = new Set([ starts a set, a collection of allowed values.
  • "trusted.example.com" is the only hostname allowed.
  • ]); closes the set.
  • if (!allowedHosts.has(url.hostname)) { checks whether the parsed URL's hostname is not in the set. The ! means "not".
  • return; stops if the hostname is not allowed.
  • } closes the check.

This is a recurring bug bounty pattern:

Text
correct-looking sanitizer+wrong security context=vulnerability

A sanitizer that looks correct, applied in the wrong context, produces a vulnerability.

5. Verify the library instead of guessing

Another important methodology lesson is verifying dependency behaviour. A dependency is a piece of code written by someone else that the site includes, like a library. The bundle contained minified module references, which makes reading hard. So the next task was identifying which library implemented the sanitizer.

Useful clues were strings relating to:

Text
allowedSchemesnaughtyHrefsanitize-html

Line by line:

  • allowedSchemes is a setting name about which URL schemes are permitted.
  • naughtyHref is an internal name suggesting a check on links.
  • sanitize-html is the name of a well-known HTML sanitisation library.

These strings identified the dependency as an HTML sanitisation library. Rather than assuming its behaviour, the researcher reproduced it locally:

JavaScript
const sanitizeHtml = require("sanitize-html");

Line by line:

  • const sanitizeHtml = declares a constant named sanitizeHtml.
  • require("sanitize-html") loads the library in Node.js, a JavaScript runtime for running code outside the browser.
  • ; ends the statement.
JavaScript
console.log(    sanitizeHtml("SOME_TEST_VALUE"));

Line by line:

  • console.log( prints whatever follows to the terminal.
  • sanitizeHtml("SOME_TEST_VALUE") runs the library on a test string.
  • ); closes the call.

Testing the exact installed version is even better. This answers questions such as:

  • Does it normalise whitespace?
  • Does it lowercase schemes?
  • Does it remove URLs?
  • Does it behave differently on raw strings?
  • Does configuration change the output?

This methodology is reusable across nearly every bug bounty target. When a bundle uses DOMPurify, sanitize-html, validator.js, lodash, marked, axios, React Router or Next.js helpers, do not rely solely on documentation. Test the exact behaviour.

6. Understand the browser primitive

A missing postMessage origin validation bug usually looks like this on the sender side:

JavaScript
victimWindow.postMessage(    {        action: "redirect",        options: {            link: attackerControlledValue        }    },    "*");

Line by line:

  • victimWindow.postMessage( sends a message to another window, here called victimWindow.
  • { starts the message object.
  • action: "redirect", says the action is a redirect.
  • options: { starts a nested object of options.
  • link: attackerControlledValue puts the attacker's chosen link in the message.
  • } closes the options object.
  • }, closes the message object.
  • "*" is the target origin. A star means "deliver to any origin", which is the loose setting.
  • ); closes the call.

The browser delivers a MessageEvent, an event object carrying event.data, event.origin and event.source. If the application only checks event.data and ignores event.origin, it has lost one of the browser's primary trust boundaries:

Text
Attacker origin      |      | postMessage()      vVictim origin      |      | missing origin verification      vTrusted application logic

Read this top to bottom: the attacker's origin sends a message, it crosses into the victim's origin, the missing check lets it through, and it reaches trusted application logic. A trust boundary is any line where data passes from a less trusted place to a more trusted one. Removing the check removes the boundary.

7. Do not stop at "postMessage bug"

A common bug bounty mistake would be stopping here and reporting "missing origin validation in postMessage handler". That might receive a low severity rating. Instead ask: what security-sensitive operation does the message control?

Possible sinks include:

Text
location.hreflocation.assign()location.replace()innerHTMLouterHTMLinsertAdjacentHTML()eval()Function()document.write()script.srciframe.srcform.action

Line by line:

  • location.href navigates the page.
  • location.assign() and location.replace() also navigate, with slightly different history behaviour.
  • innerHTML, outerHTML and insertAdjacentHTML() insert HTML into the page, which can run scripts.
  • eval() and Function() turn strings into running code.
  • document.write() writes content into the page.
  • script.src and iframe.src load external code or pages.
  • form.action decides where a form submits.

Also search for application-specific actions such as logout(), redeemReward(), changeEmail(), linkAccount(), purchase() and updateProfile(). The vulnerability's real severity depends on the sink.

In this case the chain became:

Text
Untrusted cross-origin message        ↓Missing origin validation        ↓Attacker-controlled navigation        ↓Dangerous URL interpretation        ↓JavaScript execution

That is fundamentally different from a harmless cross-origin message bug.

8. Check whether the vulnerable route actually loads

Finding vulnerable code in a JavaScript bundle does not guarantee that users can reach it. The next question should always be: what conditions cause this component to mount?

A component is a self-contained piece of a web interface, like a voting popup. Mounting means the component is created and shown on the page.

The vulnerable handler belonged to a voting modal. A modal is a popup window over the page. A route resembling /voting/:activityId rendered the relevant component. A route is a URL pattern the site uses to decide what to show; :activityId is a placeholder for a value. The component then created a third-party iframe. An iframe is a web page embedded inside another web page. The message listener was registered when that integration loaded.

This introduced an important condition: the vulnerable code existed permanently, but the trigger depended on an active campaign. There are three different states:

Text
Code exists     ↓Feature reachable     ↓Exploit trigger active

Read this top to bottom: the code is present in the files, the feature can be opened by users, and the trigger actually fires. Do not treat them as identical.

9. Test deep-link routing

Modern SPAs (single-page applications) are sites where the browser loads one page and JavaScript swaps the content as you navigate. They frequently return the application shell for arbitrary routes. For example:

Text
/voting/123/voting/456/voting/test

may all return:

HTML
<div id="root"></div><script src="/static/main.js"></script>

Line by line:

  • <div id="root"></div> is an empty container where the app will draw itself.
  • <script src="/static/main.js"></script> loads the main JavaScript file that builds the page.

and React Router decides what component to render. React Router is a library that maps URLs to components inside an SPA.

This matters because attackers may be able to directly open the vulnerable application state. During testing, verify:

HTTP
GET /interesting/route

Line by line:

  • GET is the HTTP method for requesting a page.
  • /interesting/route is the path being requested.

and inspect whether the response includes the main SPA bundle. A bundle is the packaged JavaScript file the site ships. Also inspect router definitions. Useful searches include:

Text
path:createBrowserRouter<RouteuseParams/voting/

Line by line:

  • path: is a route definition keyword.
  • createBrowserRouter is a React Router function that sets up routing.
  • <Route is the component that declares a route.
  • useParams is a React Router hook that reads URL placeholders.
  • /voting/ is the path fragment of interest.

Understanding routes often turns theoretically vulnerable code into a reproducible attack surface.

10. Analyse authentication context

JavaScript execution becomes significantly more serious when it occurs inside an authenticated origin. Authenticated means the user is logged in. The next question was: what authenticated APIs become accessible once script executes in this origin?

An API (application programming interface) is a set of URLs a website's own code calls to get or change data, usually returning JSON. The application exposed same-origin APIs for things such as profile validation, wallet and point balances, rewards, challenges, polls and surveys.

Because injected JavaScript executes as the application origin, browser requests inherit the victim's authenticated session:

JavaScript
fetch("/api/profile", {    credentials: "include"});

Line by line:

  • fetch("/api/profile", { sends an HTTP request to the relative path /api/profile.
  • credentials: "include" tells the browser to attach cookies even for cross-origin requests.
  • }); closes the call.

The browser automatically supplies eligible session cookies. A cookie is a small piece of data the browser stores for a site and sends back with requests; a session cookie identifies a logged-in user. HttpOnly is a cookie flag that hides the cookie from JavaScript via document.cookie.

HttpOnly cookies do not prevent XSS from using the victim's session. XSS (cross-site scripting) means attacker-controlled JavaScript running inside a trusted site. HttpOnly protects against document.cookie, but attacker-controlled script can still call:

JavaScript
fetch("/api/account")fetch("/api/rewards")fetch("/api/profile")

Line by line:

  • fetch("/api/account") requests the account endpoint.
  • fetch("/api/rewards") requests the rewards endpoint.
  • fetch("/api/profile") requests the profile endpoint.

because the browser sends cookies automatically. Therefore the real impact may be:

Text
XSS ↓authenticated API access ↓PII exposure ↓account actions ↓account compromise

rather than simply alert(1). PII means personally identifiable information, data that identifies a person.

11. Map the application's authenticated API surface

Once XSS is confirmed, do not immediately jump to destructive testing. Instead create an impact map. Look through network requests, JavaScript bundles, API clients, route definitions, GraphQL operations, Redux actions and service modules. GraphQL is a query language for APIs. Redux is a state-management library. Classify endpoints:

Category Example
Identity profile / account details
Financial-like value points / credits / rewards
State changes challenge participation
User content votes / surveys
Account security email / password / MFA
Privileged actions administration

Line by line:

  • Identity covers who the user is.
  • Financial-like value covers points and rewards that have real worth.
  • State changes cover actions that alter the account.
  • User content covers things the user created.
  • Account security covers login and protection settings. MFA means multi-factor authentication.
  • Privileged actions cover administration.

This gives you a structured picture of what XSS means inside that origin. For this case, the interesting classes were profile information, loyalty identifiers, points balance, reward redemption, challenge actions and voting actions. That changed the report from "DOM XSS exists" into "attacker-controlled JavaScript executes inside an authenticated loyalty application and can interact with privileged same-origin APIs." DOM XSS means XSS caused by client-side JavaScript manipulating the page (the DOM, the document object model) rather than by the server.

12. Check browser differences

Browser behaviour matters. An exploit primitive that works in Chromium may behave differently in Firefox or Safari. Therefore cross-browser validation should be part of serious client-side testing. Useful environments:

Text
ChromeChromiumEdgeFirefoxSafari / WebKit

Line by line:

  • Chrome is Google's browser.
  • Chromium is the open-source browser Chrome is built on.
  • Edge is Microsoft's browser.
  • Firefox is Mozilla's browser.
  • Safari / WebKit is Apple's browser and its engine.

With Playwright:

JavaScript
chromium.launch()firefox.launch()webkit.launch()

Line by line:

  • chromium.launch() starts a Chromium browser under automation.
  • firefox.launch() starts Firefox.
  • webkit.launch() starts WebKit.

Playwright is a tool for controlling browsers with code. For this particular class of navigation behaviour, Chromium-family browsers allowed the relevant programmatic navigation behaviour while Firefox imposed stricter user-activation requirements. User activation means the browser requires a real click or key press before allowing certain actions.

That means the correct report should not say "All users are vulnerable." It should say something closer to "The demonstrated exploit chain affects Chromium-family browsers under the tested conditions." Honest limitations improve a report. They do not weaken it. They make the report more credible.

13. Check security headers

Whenever you find a client-side injection issue, inspect the response headers. Headers are extra pieces of information the server sends with a response. Important headers include:

Text
Content-Security-PolicyX-Frame-OptionsCross-Origin-Opener-PolicyCross-Origin-Resource-PolicyReferrer-Policy

Line by line:

  • Content-Security-Policy (CSP) restricts what scripts and resources a page may load.
  • X-Frame-Options controls whether the page may be embedded in an iframe.
  • Cross-Origin-Opener-Policy isolates the page from windows it opens.
  • Cross-Origin-Resource-Policy controls who may load the resource.
  • Referrer-Policy controls how much address information is shared when navigating.

For XSS specifically, CSP can provide additional defence. A strong policy might contain:

Text
script-src 'self' 'nonce-...'object-src 'none'base-uri 'none'frame-ancestors 'none'

Line by line:

  • script-src 'self' 'nonce-...' allows scripts only from the same site or with a matching one-time nonce.
  • object-src 'none' blocks plugin content.
  • base-uri 'none' blocks changing the base address.
  • frame-ancestors 'none' blocks embedding the page in a frame.

But remember: CSP is defence in depth. Defence in depth means several layers of protection, so one failure does not mean total failure. The primary bug still needs to be fixed. For postMessage, that means validating the sender. For URL navigation, that means validating the destination.

14. Understand popup versus iframe authentication

Another useful lesson came from authentication behaviour. Modern cookies may use:

Text
SameSite=LaxSameSite=StrictSameSite=None

Line by line:

  • SameSite=Lax sends the cookie on top-level navigations to the site but not on most cross-site requests.
  • SameSite=Strict sends the cookie only for same-site requests.
  • SameSite=None sends the cookie on cross-site requests too, but requires the Secure flag.

Whether cookies are sent can depend on browsing context. An embedded third-party iframe may not receive the same cookies that a top-level browser navigation receives. So when assessing a cross-origin attack, consider:

Text
iframepopuptop-level navigationsame-site navigationcross-site subresource request

Line by line:

  • iframe is an embedded page.
  • popup is a new window opened by script.
  • top-level navigation is the main address bar changing.
  • same-site navigation stays within the same site.
  • cross-site subresource request loads a resource from another site.

The relevant question is: under what browser context does the authenticated session actually accompany the request? Do not simply assume that a cookie existing means every context gets it. Modern browser cookie rules make that incorrect.

15. Build a local replica when production testing is limited

One of the most useful bug bounty techniques is building a minimal replica of the vulnerable behaviour. This becomes particularly valuable when:

  • bot protection blocks automation,
  • login requires unavailable credentials,
  • destructive actions must be avoided,
  • the feature is temporarily inactive,
  • reproducing against production would affect users.

A good replica can contain:

Text
attacker originvictim originmessage listenersame sanitizer versionsame sinkmock authenticated endpointbrowser automation

Line by line:

  • attacker origin is a test site you control.
  • victim origin is a test site imitating the target.
  • message listener is the vulnerable handler copied over.
  • same sanitizer version is the exact library version.
  • same sink is the same navigation operation.
  • mock authenticated endpoint is a fake API that returns test data.
  • browser automation is Playwright or similar.

The goal is not to invent behaviour. It is to reproduce the verified production data flow:

Text
attacker.test      |      | cross-origin postMessage      vvictim.test      |      | vulnerable listener      vnavigation sink      |      | vscript execution      |      | vmock authenticated API

Read this top to bottom: the attacker site sends a message, the victim site's listener accepts it, the navigation sink fires, script executes, and the fake API is called. This allows the researcher to mechanically prove input, sink, execution and authenticated request without abusing a production account. That is significantly more convincing than a theoretical explanation.

16. Keep production evidence and replica evidence separate

This is critical. A strong report should clearly distinguish:

Verified directly in production:

Text
message handler existsorigin validation missingspecific sanitizer library presentdangerous sink presentSPA route reachablesecurity headers absentauthenticated API endpoints present

Line by line:

  • message handler exists: the listener is in the live code.
  • origin validation missing: there is no sender check.
  • specific sanitizer library present: the named library is in the bundle.
  • dangerous sink present: the navigation operation is there.
  • SPA route reachable: the URL loads the app.
  • security headers absent: the protective headers are not set.
  • authenticated API endpoints present: the APIs exist.

Verified in a controlled replica:

Text
browser executes the navigationscript executes in victim originauthenticated API response can be accesseddata can leave the origin

Line by line:

  • browser executes the navigation: the redirect happens.
  • script executes in victim origin: code runs as the site.
  • authenticated API response can be accessed: the fake API returns data.
  • data can leave the origin: the data can be sent out.

Never write "Full account takeover reproduced in production" if you only reproduced the complete chain locally. Instead explain exactly which links in the chain were verified where. Triagers appreciate this. A triager is the person who first reviews a bug report.

17. Think in exploit chains

The best vulnerability research often comes from chaining individually modest observations. This case can be represented as:

Text
[1] Cross-origin communication        ↓[2] Missing event.origin validation        ↓[3] Attacker controls redirect destination        ↓[4] HTML sanitizer used instead of URL validator        ↓[5] Dangerous navigation scheme survives        ↓[6] JavaScript executes in trusted origin        ↓[7] Victim session is available        ↓[8] Same-origin authenticated APIs become accessible        ↓[9] PII and loyalty actions exposed

Line by line:

  • [1] pages from different origins can talk.
  • [2] the receiver does not check who sent the message.
  • [3] the attacker chooses the link.
  • [4] the wrong cleaner is used.
  • [5] a dangerous scheme gets through.
  • [6] code runs as the trusted site.
  • [7] the victim's login is present.
  • [8] the site's own APIs can be called.
  • [9] personal data and loyalty actions are exposed.

If you stop at step two, you have a low-level bug. If you follow the chain to step nine, you understand the security impact. That mindset is one of the biggest differences between ordinary scanning and high-quality bug bounty research.

18. A reusable postMessage hunting methodology

When auditing JavaScript bundles, use the following workflow.

Step 1: find message handlers

Search:

Text
addEventListener("message"onmessagepostMessage(

Line by line:

  • addEventListener("message" registers a listener.
  • onmessage is the older assignment style.
  • postMessage( is the sending side.

Step 2: look for origin validation

Search nearby code for:

Text
event.origine.originallowedOriginstrustedOrigins

Line by line:

  • event.origin is the sender's origin.
  • e.origin is the same, with a shorter variable name.
  • allowedOrigins and trustedOrigins are common names for allowlists.

If none exists, investigate further.

Step 3: identify controllable fields

Examples:

Text
event.data.urlevent.data.redirectevent.data.linkevent.data.htmlevent.data.commandevent.data.action

Line by line:

  • event.data.url, event.data.redirect, event.data.link are address fields.
  • event.data.html is markup.
  • event.data.command and event.data.action are instructions.

Ask: which part of the message controls application behaviour?

Step 4: trace those fields to sinks

High-value sinks include:

Text
location.hreflocation.assignlocation.replaceinnerHTMLouterHTMLinsertAdjacentHTMLdocument.writeevalFunctionscript.srciframe.srcform.action

Line by line:

  • location.href, location.assign, location.replace navigate.
  • innerHTML, outerHTML, insertAdjacentHTML, document.write insert HTML.
  • eval, Function run code.
  • script.src, iframe.src, form.action load or submit elsewhere.

Step 5: understand every transformation

If data goes through:

Text
sanitize()escape()encode()validate()normalize()

Line by line:

  • sanitize() cleans.
  • escape() neutralises special characters.
  • encode() converts characters to a safe representation.
  • validate() checks against rules.
  • normalize() standardises the form.

identify the actual library and behaviour. Never assume safety from the function name.

Step 6: reproduce library behaviour locally

Use the exact package version where possible. Test:

Text
normal inputmixed casewhitespaceencoded charactersscheme variationsrelative URLsabsolute URLs

Line by line:

  • normal input is the ordinary case.
  • mixed case tests upper and lower letters.
  • whitespace tests spaces and tabs.
  • encoded characters tests percent-encoded forms.
  • scheme variations tests different URL schemes.
  • relative URLs and absolute URLs test both link styles.

The goal is understanding the parser.

Step 7: determine reachability

Find:

Text
routefeature flagcampaign IDiframe conditioncomponent lifecycleauthentication requirement

Line by line:

  • route is the URL path.
  • feature flag is a switch that turns a feature on or off.
  • campaign ID identifies a marketing campaign.
  • iframe condition is when the embedded page loads.
  • component lifecycle is when the component is created and destroyed.
  • authentication requirement is whether login is needed.

A vulnerable function that never executes has different risk from one reachable by every visitor.

Step 8: determine execution context

Ask:

Text
Does it execute in an iframe?A popup?The top-level page?A sandboxed frame?

Line by line:

  • iframe is an embedded page.
  • popup is a new window.
  • top-level page is the main tab.
  • sandboxed frame is an iframe with restricted permissions.

Security behaviour changes significantly depending on context.

Step 9: map authenticated capabilities

Once execution is established, inspect same-origin APIs. Prioritise:

Text
profileaccountbillingwalletrewardsemailsecurity settingsadministrative functions

Line by line:

  • profile, account are identity data.
  • billing, wallet, rewards are value.
  • email, security settings are account security.
  • administrative functions are privileged actions.

Do not perform destructive actions unless explicitly permitted.

Step 10: validate multiple browsers

Do not assume browser behaviour is universal. Test Chromium, Firefox and WebKit where relevant.

Step 11: document conditions

Examples:

Text
requires loginrequires one clickChromium onlyfeature only active during campaignsspecific account state required

Line by line:

  • requires login means the victim must be signed in.
  • requires one click means user activation is needed.
  • Chromium only means other browsers are unaffected.
  • feature only active during campaigns means timing matters.
  • specific account state required means the account must be in a certain condition.

Good researchers communicate constraints instead of hiding them.

19. Interesting search patterns

During JavaScript bundle auditing, searches like these can uncover similar issues:

Text
addEventListener("message"event.originpostMessage(location.hreflocation.assignlocation.replacesanitizeredirectoptions.linkevent.data

Line by line:

  • addEventListener("message" finds listeners.
  • event.origin finds origin checks.
  • postMessage( finds senders.
  • location.href, location.assign, location.replace find navigation sinks.
  • sanitize finds cleaning functions.
  • redirect, options.link, event.data find message fields.

Using ripgrep:

Bash
rg 'addEventListener\(["\'\'']message' .

Line by line:

  • rg is ripgrep, a fast text search tool.
  • 'addEventListener\(["\'\'']message' is the pattern, matching the listener registration with different quote styles.
  • . means search the current directory.
Bash
rg 'postMessage\(' .

Line by line:

  • rg runs ripgrep.
  • 'postMessage\(' matches the sending call.
  • . searches the current directory.
Bash
rg 'location\.(href|assign|replace)' .

Line by line:

  • rg runs ripgrep.
  • 'location\.(href|assign|replace)' matches any of the three navigation forms.
  • . searches the current directory.
Bash
rg 'event\.origin|e\.origin' .

Line by line:

  • rg runs ripgrep.
  • 'event\.origin|e\.origin' matches either origin check form.
  • . searches the current directory.

The interesting pattern is often:

Text
message handler found+no origin validation nearby+security-sensitive sink

That combination deserves manual review.

20. Common false positives

Not every missing origin check is exploitable. A false positive is a finding that looks like a bug but is not. For example:

JavaScript
window.addEventListener("message", e => {    console.log(e.data);});

Line by line:

  • window.addEventListener("message", e => { registers a listener.
  • console.log(e.data); prints the message to the developer console.
  • }); closes it.

is generally not a security vulnerability. Likewise:

JavaScript
window.addEventListener("message", e => {    if (e.data === "resize") resizeWidget();});

Line by line:

  • if (e.data === "resize") resizeWidget(); only resizes a widget when the message is exactly resize.
  • }); closes it.

may have little security impact. Severity increases when attacker-controlled messages influence navigation, HTML, authentication, account state, sensitive APIs, payments, tokens or privileged actions. Always follow the data.

21. Reporting strategy

A strong title should describe the full chain. For example:

Cross-Origin postMessage DOM XSS via Missing Origin Validation Leading to Authenticated Account Actions

The summary should answer four things immediately:

Text
What can the attacker control?Where does it go?Why does the existing protection fail?What can the attacker accomplish?

Line by line:

  • What can the attacker control? is the source.
  • Where does it go? is the sink.
  • Why does the existing protection fail? is the broken transformation.
  • What can the attacker accomplish? is the impact.

For example:

A cross-origin postMessage listener accepts redirect messages without validating the sender. The attacker-controlled destination is passed through an HTML sanitizer and assigned to a browser navigation sink. Because HTML sanitisation does not enforce safe URL schemes, an unsafe navigation value can survive and execute within the trusted application origin. In authenticated sessions, this gives attacker-controlled JavaScript access to same-origin profile and loyalty functionality.

That communicates the entire vulnerability without requiring a triager to reverse-engineer the report.

22. Remediation

Remediation means the fix. There are multiple layers to fix.

Validate the message origin

JavaScript
const TRUSTED_ORIGINS = new Set([    "https://trusted-widget.example"]);

Line by line:

  • const TRUSTED_ORIGINS = new Set([ starts a set of allowed origins.
  • "https://trusted-widget.example" is the only trusted origin.
  • ]); closes the set.
JavaScript
window.addEventListener("message", event => {    if (!TRUSTED_ORIGINS.has(event.origin)) {        return;    }    // handle message});

Line by line:

  • window.addEventListener("message", event => { registers the listener.
  • if (!TRUSTED_ORIGINS.has(event.origin)) { checks whether the sender is not in the set.
  • return; stops for untrusted senders.
  • // handle message marks the trusted work.
  • }); closes it.

For stronger validation, also verify event.source when the expected window reference is known.

Validate URLs as URLs

Do not use an HTML sanitizer for navigation security. Instead:

JavaScript
function safeRedirect(value) {    const url = new URL(value, window.location.origin);
JavaScript
    if (url.protocol !== "https:") {        throw new Error("Unsupported protocol");    }    return url.href;}

Line by line:

  • function safeRedirect(value) { defines a function taking a value.
  • const url = new URL(value, window.location.origin); parses it as a URL.
  • if (url.protocol !== "https:") { checks the scheme.
  • throw new Error("Unsupported protocol"); refuses anything else.
  • return url.href; returns the safe address.
  • } closes the function.

Restrict hostnames if external navigation is unnecessary.

Prefer semantic actions over arbitrary URLs

Even better than accepting:

JavaScript
{    action: "redirect",    link: "https://..."}

Line by line:

  • { starts an object.
  • action: "redirect", says what to do.
  • link: "https://..." supplies an arbitrary address.
  • } closes it.

is accepting:

JavaScript
{    action: "openRewards"}

Line by line:

  • { starts an object.
  • action: "openRewards" names a fixed action.
  • } closes it.

and mapping the action internally:

JavaScript
const destinations = {    openRewards: "/rewards",    openProfile: "/profile"};

Line by line:

  • const destinations = { starts a lookup table.
  • openRewards: "/rewards", maps the action to a fixed path.
  • openProfile: "/profile" maps another action.
  • }; closes it.

The external sender never supplies the destination at all.

Add CSP

A strong Content Security Policy provides another security boundary. CSP should not replace the application-level fix, but it can significantly reduce the impact of future injection bugs.

23. The bigger lesson: context matters more than sanitisation

The most important technical lesson from this finding is simple:

Text
Sanitized ≠ safe.

A value can be safe for HTML while dangerous as a URL, JavaScript, CSS, SQL, a shell command or an HTTP header. Security controls must match the parser that ultimately consumes the value. A parser is the piece of software that reads and interprets a value. In this case:

Text
HTML sanitizer        ↓URL sink

was the architectural mistake. The correct model should have been:

Text
Untrusted URL        ↓URL parser        ↓scheme allowlist        ↓hostname allowlist        ↓navigation

Read this top to bottom: parse the URL, check the scheme against an allowlist, check the hostname against an allowlist, then navigate.

24. The research mindset

There are several broader lessons bug bounty hunters can take from this case. Do not stop when you find suspicious code. Ask:

Text
Can I control it?Where does it flow?What parser handles it?Can I reach the component?What browser context executes it?What privileges does that origin have?What happens when the victim is authenticated?

Line by line:

  • Can I control it? asks about the source.
  • Where does it flow? asks about the path.
  • What parser handles it? asks about the transformation.
  • Can I reach the component? asks about reachability.
  • What browser context executes it? asks about the environment.
  • What privileges does that origin have? asks about the origin's power.
  • What happens when the victim is authenticated? asks about impact.

Do not stop at missing origin check. Trace the message. Do not stop at XSS. Map the authenticated APIs. Do not stop at there is a sanitizer. Determine whether it matches the sink. Do not stop at works in my browser. Test browser differences. And when production conditions prevent a safe full-chain test, reproduce the verified behaviour in a controlled environment and clearly separate production evidence from controlled exploit-chain evidence. That combination of technical depth and disciplined validation is what turns an interesting JavaScript bug into a strong vulnerability report.

Final attack-chain mental model

Whenever you encounter cross-window communication, mentally run this checklist:

Text
Who can send the message?        ↓Is event.origin validated?        ↓Which message properties are attacker controlled?        ↓Where do those values flow?        ↓What sink consumes them?        ↓Is sanitization appropriate for that sink?        ↓Can the vulnerable feature actually be reached?        ↓What origin will attacker-controlled code execute under?        ↓What authentication context exists?        ↓Which sensitive APIs become reachable?

Line by line:

  • Who can send the message? identifies the sender.
  • Is event.origin validated? checks the trust boundary.
  • Which message properties are attacker controlled? finds the source fields.
  • Where do those values flow? traces the path.
  • What sink consumes them? finds the dangerous operation.
  • Is sanitization appropriate for that sink? checks the transformation.
  • Can the vulnerable feature actually be reached? checks reachability.
  • What origin will attacker-controlled code execute under? checks the execution context.
  • What authentication context exists? checks the session.
  • Which sensitive APIs become reachable? checks the impact.

That methodology applies far beyond this particular case. It can uncover vulnerabilities in OAuth implementations, payment widgets, embedded checkout flows, SSO integrations, marketing widgets, support systems, survey platforms, authentication popups, loyalty applications and third-party SDK integrations. OAuth is a login delegation standard. SSO means single sign-on. The important part is not memorising one payload. A payload is the crafted input that triggers a bug. It is learning to identify a broken trust boundary and following attacker-controlled data all the way to its security impact.

Glossary

  • API: a set of URLs a website's own code calls to get or change data.
  • Authenticated: logged in.
  • Bundle: the packaged JavaScript file a site ships.
  • Component: a self-contained piece of a web interface.
  • Cookie: a small piece of data the browser stores for a site and sends back with requests.
  • CSP (Content Security Policy): a response header that restricts what scripts and resources a page may load.
  • Data flow analysis: tracing where untrusted data enters, how it changes, and where it ends up.
  • Defence in depth: several layers of protection so one failure does not mean total failure.
  • Dependency: code written by someone else that a site includes.
  • DOM: the document object model, the browser's in-memory tree of the page.
  • DOM XSS: XSS caused by client-side JavaScript manipulating the page rather than by the server.
  • False positive: a finding that looks like a bug but is not.
  • GraphQL: a query language for APIs.
  • Header: extra information the server sends with a response.
  • HttpOnly: a cookie flag that hides the cookie from JavaScript via document.cookie.
  • Iframe: a web page embedded inside another web page.
  • MessageEvent: the event object delivered when a postMessage message arrives.
  • MFA: multi-factor authentication.
  • Minified: code with whitespace and names squeezed to make files smaller.
  • Modal: a popup window over the page.
  • Mounting: creating and showing a component on the page.
  • OAuth: a login delegation standard.
  • Origin: protocol plus hostname plus port.
  • Parser: the piece of software that reads and interprets a value.
  • Payload: the crafted input that triggers a bug.
  • PII: personally identifiable information.
  • Playwright: a tool for controlling browsers with code.
  • postMessage: the browser API that lets pages from different origins send messages.
  • React Router: a library that maps URLs to components inside an SPA.
  • Redux: a state-management library.
  • Remediation: the fix.
  • Ripgrep: a fast text search tool.
  • Route: a URL pattern a site uses to decide what to show.
  • Same-origin policy: the browser rule that keeps pages from different origins apart.
  • Sanitising: cleaning input so it is safe for a particular context.
  • Scheme: the part of a URL before the colon, like https or javascript.
  • SDK: a software development kit, a bundle of code for a specific service.
  • Session cookie: a cookie that identifies a logged-in user.
  • Sink: the dangerous operation where untrusted data finally lands.
  • SPA: single-page application, a site where JavaScript swaps content as you navigate.
  • SSO: single sign-on.
  • Transformation: anything a program does to data between source and sink.
  • Triager: the person who first reviews a bug report.
  • Trust boundary: any line where data passes from a less trusted place to a more trusted one.
  • User activation: the browser requiring a real click or key press before allowing certain actions.
  • XSS: cross-site scripting, attacker-controlled JavaScript running inside a trusted site.

More by redhunter01

View all

24 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site scripting (XSS)

The lesson behind this report.

Script an attacker supplies runs in another user's browser, on the target's origin, with that user's session.