@@ -16,6 +16,12 @@ if (!document.referrer.match(ALLOWED_REFERRER_PATTERN)) {
1616 ) ;
1717}
1818
19+ // Extract the expected host origin from the referrer for origin validation.
20+ // This is the origin we expect all parent messages to come from.
21+ const EXPECTED_HOST_ORIGIN = new URL ( document . referrer ) . origin ;
22+
23+ const OWN_ORIGIN = new URL ( window . location . href ) . origin ;
24+
1925// Security self-test: verify iframe isolation is working correctly.
2026// This MUST throw a SecurityError -- if `window.top` is accessible, the sandbox
2127// configuration is dangerously broken and untrusted content could escape.
@@ -79,8 +85,18 @@ function buildCspMetaTag(csp?: { connectDomains?: string[]; resourceDomains?: st
7985
8086window . addEventListener ( "message" , async ( event ) => {
8187 if ( event . source === window . parent ) {
82- // NOTE: In production you'll also want to validate `event.origin` against
83- // your Host domain.
88+ // Validate that messages from parent come from the expected host origin.
89+ // This prevents malicious pages from sending messages to this sandbox.
90+ if ( event . origin !== EXPECTED_HOST_ORIGIN ) {
91+ console . error (
92+ "[Sandbox] Rejecting message from unexpected origin:" ,
93+ event . origin ,
94+ "expected:" ,
95+ EXPECTED_HOST_ORIGIN
96+ ) ;
97+ return ;
98+ }
99+
84100 if ( event . data && event . data . method === RESOURCE_READY_NOTIFICATION ) {
85101 const { html, sandbox, csp } = event . data . params ;
86102 if ( typeof sandbox === "string" ) {
@@ -112,14 +128,25 @@ window.addEventListener("message", async (event) => {
112128 }
113129 }
114130 } else if ( event . source === inner . contentWindow ) {
131+ if ( event . origin !== OWN_ORIGIN ) {
132+ console . error (
133+ "[Sandbox] Rejecting message from inner iframe with unexpected origin:" ,
134+ event . origin ,
135+ "expected:" ,
136+ OWN_ORIGIN
137+ ) ;
138+ return ;
139+ }
115140 // Relay messages from inner frame to parent window.
116- window . parent . postMessage ( event . data , "*" ) ;
141+ // Use specific origin instead of "*" to prevent message interception.
142+ window . parent . postMessage ( event . data , EXPECTED_HOST_ORIGIN ) ;
117143 }
118144} ) ;
119145
120146// Notify the Host that the Sandbox is ready to receive Guest UI HTML.
147+ // Use specific origin instead of "*" to ensure only the expected host receives this.
121148window . parent . postMessage ( {
122149 jsonrpc : "2.0" ,
123150 method : PROXY_READY_NOTIFICATION ,
124151 params : { } ,
125- } , "*" ) ;
152+ } , EXPECTED_HOST_ORIGIN ) ;
0 commit comments