From 8a21abcd6b7a5cd7649ca0e12d46b98e7da1b550 Mon Sep 17 00:00:00 2001 From: Rafael Oleza Date: Wed, 22 Aug 2018 09:52:05 -0700 Subject: [PATCH] Prevent cross origin requests to development server Summary: This diff adds a middleware to the RN development server to prevent processing requests coming from a third-party website. The way we choose to do it is to block any request that has an origin header and it's different than localhost. This will still allow simulators to work properly while blocking potential external websites to do malign CORS requests. This is just a first quick measure to block a potential attack vector while we implement full authentication in the RN development server Reviewed By: mjesun Differential Revision: D9238674 fbshipit-source-id: b7bdc40dabc2f4d92f5ac84515f93b89efa4e833 --- .../server/middleware/MiddlewareManager.js | 2 ++ .../getSecurityHeadersMiddleware.js | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 local-cli/server/middleware/getSecurityHeadersMiddleware.js diff --git a/local-cli/server/middleware/MiddlewareManager.js b/local-cli/server/middleware/MiddlewareManager.js index 8692abdcc..c565f6810 100644 --- a/local-cli/server/middleware/MiddlewareManager.js +++ b/local-cli/server/middleware/MiddlewareManager.js @@ -17,6 +17,7 @@ const WebSocketServer = require('ws').Server; const indexPageMiddleware = require('./indexPage'); const copyToClipBoardMiddleware = require('./copyToClipBoardMiddleware'); +const getSecurityHeadersMiddleware = require('./getSecurityHeadersMiddleware'); const loadRawBodyMiddleware = require('./loadRawBodyMiddleware'); const openStackFrameInEditorMiddleware = require('./openStackFrameInEditorMiddleware'); const statusPageMiddleware = require('./statusPageMiddleware'); @@ -44,6 +45,7 @@ module.exports = class MiddlewareManager { this.options = options; this.app = connect() + .use(getSecurityHeadersMiddleware) .use(loadRawBodyMiddleware) .use(compression()) .use('/debugger-ui', serveStatic(debuggerUIFolder)) diff --git a/local-cli/server/middleware/getSecurityHeadersMiddleware.js b/local-cli/server/middleware/getSecurityHeadersMiddleware.js new file mode 100644 index 000000000..ab14cd18b --- /dev/null +++ b/local-cli/server/middleware/getSecurityHeadersMiddleware.js @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @strict + * @format + */ + +module.exports = function(req, res, next) { + const address = req.client.server.address(); + + // Block any cross origin request. + if ( + req.headers.origin && + req.headers.origin !== `http://localhost:${address.port}` + ) { + next(new Error('Unauthorized')); + return; + } + + // Block MIME-type sniffing. + res.setHeader('X-Content-Type-Options', 'nosniff'); + + next(); +};