1import type { IncomingMessage, ServerResponse } from 'http';
2
3// Like securityHeadersMiddleware but further allow cross-origin requests
4// from https://chrome-devtools-frontend.appspot.com/
5export function remoteDevtoolsSecurityHeadersMiddleware(
6  req: IncomingMessage,
7  res: ServerResponse,
8  next: (err?: Error) => void
9) {
10  // Block any cross origin request.
11  if (
12    typeof req.headers.origin === 'string' &&
13    !req.headers.origin.match(/^https?:\/\/localhost:/) &&
14    !req.headers.origin.match(/^https:\/\/chrome-devtools-frontend\.appspot\.com/)
15  ) {
16    next(
17      new Error(
18        `Unauthorized request from ${req.headers.origin}. ` +
19          'This may happen because of a conflicting browser extension to intercept HTTP requests. ' +
20          'Please try again without browser extensions or using incognito mode.'
21      )
22    );
23    return;
24  }
25
26  // Block MIME-type sniffing.
27  res.setHeader('X-Content-Type-Options', 'nosniff');
28
29  next();
30}
31