From 780fa84e669f13c99788e5ccebcd7b671ef7ef8c Mon Sep 17 00:00:00 2001 From: RCCodeBase Date: Thu, 1 Aug 2024 22:47:11 +0530 Subject: [PATCH] fix: cors policy updated --- package.json | 2 ++ src/index.ts | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 4ab7727..5eb62d6 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "@cord.network/sdk": "0.9.3-1rc14", "@cord.network/vc-export": "0.9.3-1rc14", "body-parser": "^1.20.2", + "cors": "^2.8.5", "dotenv": "^16.0.3", "express": "^4.18.2", "moment": "^2.30.1", @@ -28,6 +29,7 @@ "yamljs": "^0.3.0" }, "devDependencies": { + "@types/cors": "^2.8.14", "@types/express": "^4.17.17", "@types/node": "^20.11.0", "@types/swagger-ui-express": "^4.1.3", diff --git a/src/index.ts b/src/index.ts index 91b4c86..1b1bc87 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,13 +15,75 @@ import { revokeCred, updateCred, } from './controller/credential_controller'; - +import cors from 'cors'; const app = express(); export const { PORT } = process.env; app.use(bodyParser.json({ limit: '5mb' })); app.use(express.json()); + +const allowedOrigins = [ + 'http://localhost:3000', + 'http://localhost:5001', + 'http://localhost:5108', + 'https://studio.dhiway.com', + 'https://markdemo.dhiway.com', + 'https://studiodemo.dhiway.com', +]; + + +const allowedDomains = [ + 'localhost', + 'dhiway.com', + 'dway.io', + 'cord.network', + 'amplifyapp.com' /* For supporting quick hosting of UI */, +]; + +app.use( + cors({ + origin: function (origin, callback) { + if (!origin) return callback(null, true); + let tmpOrigin = origin; + + if (origin.slice(-1) === '/') { + tmpOrigin = origin.substring(0, origin.length - 1); + } + if (allowedOrigins.indexOf(tmpOrigin) === -1) { + /* Check if we should allow star/asteric */ + const b = tmpOrigin.split('/')[2].split('.'); + const domain = `${b[b.length - 2]}.${b[b.length - 1]}`; + if (allowedDomains.indexOf(domain) === -1) { + console.log(tmpOrigin, domain); + const msg = `The CORS policy for this site (${origin}) does not allow access from the specified Origin.`; + return callback(new Error(msg), false); + } + } + return callback(null, true); + }, + optionsSuccessStatus: 200, // For legacy browser support + credentials: true, + preflightContinue: true, + methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'HEAD', 'PATCH'], + allowedHeaders: [ + 'Content-Type', + 'X-UserId', + 'Accept', + 'Authorization', + 'user-agent', + 'Host', + 'X-Forwarded-For', + 'Upgrade', + 'Connection', + 'X-Content-Type-Options', + 'Content-Security-Policy', + 'X-Frame-Options', + 'Strict-Transport-Security', + ], + }) +); + const credentialRouter = express.Router({ mergeParams: true }); const schemaRouter = express.Router({ mergeParams: true });