@@ -104,7 +104,7 @@ export class HttpServer {
104104 socket . destroy ( ) ;
105105 return ;
106106 }
107- if ( ! isAllowedHost ( request , this . _allowedHosts ) ) {
107+ if ( ! isAllowedHost ( request , this . _allowedHosts ) || ! isSameOriginUpgrade ( request ) ) {
108108 socket . write ( `HTTP/${ request . httpVersion } 403 Forbidden\r\n\r\n` ) ;
109109 socket . destroy ( ) ;
110110 return ;
@@ -355,6 +355,29 @@ export function isAllowedHost(request: http.IncomingMessage, allowedHosts: Set<s
355355 return ! ! hostname && allowedHosts . has ( hostname ) ;
356356}
357357
358+ // Browsers always send Origin with a WebSocket handshake, and a page cannot change it or add headers.
359+ // Accept only pages of this server. This also rejects sandboxed pages, which have the "null" origin.
360+ // Clients that are not browsers send no Origin. A proxy can pass the public host in X-Forwarded-Host.
361+ function isSameOriginUpgrade ( request : http . IncomingMessage ) : boolean {
362+ const origin = request . headers . origin ;
363+ if ( origin === undefined )
364+ return true ;
365+ let originHost : string ;
366+ try {
367+ originHost = new URL ( origin ) . host . toLowerCase ( ) ;
368+ } catch {
369+ return false ;
370+ }
371+ const forwardedHost = request . headers [ 'x-forwarded-host' ] ;
372+ const hosts = [ request . headers . host , ...( Array . isArray ( forwardedHost ) ? forwardedHost : ( forwardedHost ?? '' ) . split ( ',' ) ) ] ;
373+ return ! ! originHost && hosts . some ( host => host ?. trim ( ) . toLowerCase ( ) === originHost ) ;
374+ }
375+
376+ // A page must never show a file with content from the pages under test inside a frame.
377+ export function isFrameNavigation ( request : http . IncomingMessage ) : boolean {
378+ return [ 'iframe' , 'frame' , 'embed' , 'object' ] . includes ( String ( request . headers [ 'sec-fetch-dest' ] ) ) ;
379+ }
380+
358381// Bracket IPv6 literals so they can be used as the host part of a URL.
359382export function urlHostFromAddress ( address : { address : string , family : string } ) : string {
360383 return address . family === 'IPv6' ? `[${ address . address } ]` : address . address ;
@@ -378,9 +401,15 @@ export function serveFolder(folder: string): HttpServer {
378401 const requested = url . searchParams . get ( 'path' ) ;
379402 if ( ! requested )
380403 return false ;
404+ if ( isFrameNavigation ( request ) ) {
405+ response . statusCode = 403 ;
406+ response . end ( ) ;
407+ return true ;
408+ }
381409 const resolved = path . resolve ( requested ) ;
382410 try {
383- return server . serveFile ( request , response , resolved ) ;
411+ // These files can have content from the pages under test. Do not run them as pages in the trace viewer origin.
412+ return server . serveFile ( request , response , resolved , { 'Content-Security-Policy' : 'sandbox' , 'X-Content-Type-Options' : 'nosniff' } ) ;
384413 } catch ( e ) {
385414 return false ;
386415 }
0 commit comments