All files / src/middleware cors.js

100% Statements 13/13
100% Branches 14/14
100% Functions 2/2
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 2819x   19x 4x     19x     19x 18x   11x 3x     8x       2x   6x          
const cors = require('cors');
 
const allowedOrigins = process.env.ALLOWED_ORIGINS
  ? process.env.ALLOWED_ORIGINS.split(',').map((o) => o.trim())
  : ['https://shytalk.shyden.co.uk', 'https://api.shytalk.shyden.co.uk'];
 
module.exports = cors({
  origin: (origin, callback) => {
    // Allow requests with no origin (mobile apps, curl, server-to-server)
    if (!origin) return callback(null, true);
    if (allowedOrigins.includes(origin)) return callback(null, true);
    // Allow localhost in local/test mode (admin panel served locally)
    if (process.env.NODE_ENV === 'local' && /^http:\/\/localhost(:\d+)?$/.test(origin)) {
      return callback(null, true);
    }
    // Allow Cloudflare Pages preview deployments (subdomain.pages.dev)
    if (
      /^https:\/\/[a-z0-9][a-z0-9-]*\.shytalk-site-dev\.pages\.dev$/.test(origin) ||
      /^https:\/\/[a-z0-9][a-z0-9-]*\.shytalk-site\.pages\.dev$/.test(origin)
    ) {
      return callback(null, true);
    }
    callback(new Error('Not allowed by CORS'));
  },
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Authorization', 'Content-Type', 'x-session-trace-id', 'x-device-id'],
});