Skip to content

Commit

Permalink
Merge pull request #27 from Louis3797/fix/cors
Browse files Browse the repository at this point in the history
Updated cors and helmet config #10
  • Loading branch information
Louis3797 authored Nov 8, 2024
2 parents 0451570 + cd2bccf commit 50ac4b1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
11 changes: 3 additions & 8 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ import config from './config/config';
import authLimiter from './middleware/authLimiter';
import { xssMiddleware } from './middleware/xssMiddleware';
import path from 'path';
import corsConfig from './config/cors';

const app: Express = express();

// Helmet is used to secure this app by configuring the http-header
app.use(helmet());
app.use(helmet.frameguard({ action: 'deny' }));

// parse json request body
app.use(express.json());
Expand All @@ -30,13 +31,7 @@ app.use(cookieParser());
// Compression is used to reduce the size of the response body
app.use(compression({ filter: compressFilter }));

app.use(
cors({
// origin is given a array if we want to have multiple origins later
origin: String(config.cors.cors_origin).split('|'),
credentials: true
})
);
app.use(cors(corsConfig));

if (config.node_env === 'production') {
app.use('/api/v1/auth', authLimiter);
Expand Down
33 changes: 33 additions & 0 deletions src/config/cors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { type CorsOptions } from 'cors';
import config from './config';

const whitelist = String(config.cors.cors_origin).split('|') ?? [];

const corsConfig: Readonly<CorsOptions> = {
origin (
origin: string | undefined,
callback: (
err: Error | null,
origin?: boolean | string | RegExp | Array<boolean | string | RegExp>
) => void
) {
if (!origin || whitelist.some((val) => origin.match(val))) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
maxAge: 86400,
headers: [
'Accept',
'Authorization',
'Content-Type',
'If-None-Match',
'BX-User-Token',
'Trace-Id'
],
exposedHeaders: ['WWW-Authenticate', 'Server-Authorization'],
credentials: true
} as CorsOptions;

export default corsConfig;

0 comments on commit 50ac4b1

Please sign in to comment.