diff --git a/cli/defaults/siteConfig.json b/cli/defaults/siteConfig.json index 7b23113e..e6366a3d 100644 --- a/cli/defaults/siteConfig.json +++ b/cli/defaults/siteConfig.json @@ -18,7 +18,8 @@ "host": "https://www.example.com", "description": "A decentralized hosting platform built on LBRY", "twitter": false, - "blockListEndpoint": "https://api.lbry.com/file/list_blocked" + "blockListEndpoint": "https://api.lbry.com/file/list_blocked", + "corsWhitelist": [] }, "publishing": { "primaryClaimAddress": null, diff --git a/server/index.js b/server/index.js index 64225f47..d96ba252 100644 --- a/server/index.js +++ b/server/index.js @@ -24,7 +24,7 @@ const processTrending = require('./utils/processTrending'); const { setRouteDataInContextMiddleware } = require('./middleware/httpContextMiddleware'); const { - details: { port: PORT, blockListEndpoint }, + details: { port: PORT, blockListEndpoint, corsWhitelist, host }, startup: { performChecks, performUpdates }, } = require('@config/siteConfig'); @@ -83,23 +83,36 @@ function Server() { // set HTTP headers to protect against well-known web vulnerabilties app.use(helmet()); - // open cors for lbry.tv lbry.tech localhost lbry.com - var whitelist = [ - 'https://lbry.com', - 'https://lbry.tech', - 'https://lbry.tv', - 'http://localhost', - 'http://localhost:1337', + // open cors for site/config:host (current instance) + var originWhitelist = [ + host ]; - var corsOptions = { + // whitelist is found in site/config:details: + // enter corsWhitelist: ["*"] to allow all + // enter your domains otherwise:["https://example.com", ...] + if ( corsWhitelist && corsWhitelist.length ) { + originWhitelist = originWhitelist.concat(corsWhitelist); + } + + var corsOptions = originWhitelist && originWhitelist.includes('*') + ? { + "origin": "*", + "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", + "preflightContinue": false, + "optionsSuccessStatus": 204 + } + : { origin: function(origin, callback) { - if (whitelist.indexOf(origin) !== -1) { + if ((origin === undefined) || originWhitelist.indexOf(origin) !== -1) { callback(null, true); } else { - callback(new Error('Not allowed by CORS')); + let error = new Error(`CORS has blocked this website from access. Contact an administrator from ${host} if you feel this is in error.`); + error.code = "ECORS" + callback(error); } }, }; + app.use(cors(corsOptions)); // Support per-request http-context app.use(httpContext.middleware); @@ -166,6 +179,16 @@ function Server() { ); }); + app.use( (error, req, res, next) => { + if (error.code === 'ECORS'){ + res.status(403); + res.send({message: error}) + } else { + res.status(520); + res.send({ message: error }); + } + }) + this.app = app; }; this.createServer = () => {