From 8424cda3bbbb8c8f7f8afa872be5ae39f59b77c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ferit=20Yi=C4=9Fit=20BALABAN?= Date: Tue, 19 Mar 2024 01:17:24 +0300 Subject: [PATCH] Refactor email access and origin validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Ferit Yiğit BALABAN --- index.js | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/index.js b/index.js index 899211b..380f4d9 100644 --- a/index.js +++ b/index.js @@ -12,17 +12,20 @@ const SENDER_PASS = process.env.EMAIL_PASSWORD; const SERV_HOST = process.env.EMAIL_HOST; const SERV_PORT = process.env.EMAIL_PORT; +const recipients = process.env.ACCESS_KEYS.split(',').map((whole) => { + return { + key: whole.split(':')[0], + recipient: whole.split(':')[1], + }; +}); + const allowedOrigins = process.env.ALLOWED_ORIGINS.split(','); app.enable('trust proxy'); app.disable('x-powered-by'); app.use(express.json()); app.use(helmet()); -app.use( - morgan( - '[ :method :url ] ~:status | :date[web] | :total-time[digits] ms | IP :remote-addr | :user-agent' - ) - ) +app.use(morgan('[ :method :url ] ~:status | :date[web] | :total-time[digits] ms | IP :remote-addr | :user-agent')); // 10 requests per minute const rootLimiter = rateLimit({ @@ -46,11 +49,11 @@ app.use( ); app.use((req, res, next) => { - const origin = req.headers.origin; - if (origin && allowedOrigins.includes(origin)) { - next(); - } else { - res.status(403).json({ success: false, message: `Origin ${origin} is not allowed` }); + const origin = req.headers.origin; + if (origin && allowedOrigins.includes(origin)) { + next(); + } else { + res.status(403).json({ success: false, message: `Origin ${origin} is not allowed` }); console.warn(`Connection refused: origin ${origin} is not allowed`); } }); @@ -72,12 +75,14 @@ const mailRouteLimiter = rateLimit({ }); app.post('/api/mail', mailRouteLimiter, (req, res) => { - const { to, subject, text, access } = req.body; + const { subject, text, access } = req.body; + let to; - if (!process.env.ACCESS_KEYS.split(',').includes(access)) { - return res.status(403).json({ success: false, message: 'Access denied!' }); + if (!recipients.some((recipient) => recipient.key === access)) { console.log('Access denied!'); - } + return res.status(403).json({ success: false, message: 'Access denied!' }); + } else + to = recipients.find((recipient) => recipient.key === access).recipient; const mail = { from: `"Arbeit Mail Hizmeti" <${SENDER_EMAIL}>`, @@ -94,7 +99,7 @@ app.post('/api/mail', mailRouteLimiter, (req, res) => { } else { console.error('Failed to send:', mail); res.status(500).json({ success: false, message: 'Mail could not be sent!' }); - }; + } } else res.status(200).json(mail); });