freeCodeCamp/api/src/plugins/security.ts
Oliver Eyton-Williams 5e17868c74
fix(api): allow fastify to set content-type dynamically (#50248)
fix: allow fastify to set content-type dynamically

We can set content-type: application/json for specific routes, but
doing so ends up with confusing, over-engineered code.

Instead we should take care when auditing the endpoints.
2023-05-02 10:15:31 -07:00

29 lines
851 B
TypeScript

import { FastifyPluginCallback } from 'fastify';
import fp from 'fastify-plugin';
import { FREECODECAMP_NODE_ENV } from '../utils/env';
const securityHeaders: FastifyPluginCallback = (fastify, _options, done) => {
// OWASP recommended headers
fastify.addHook('onRequest', async (_request, reply) => {
void reply
.header('Cache-Control', 'no-store')
.header('Content-Security-Policy', "frame-ancestors 'none'")
.header('X-Content-Type-Options', 'nosniff')
.header('X-Frame-Options', 'DENY');
// TODO: Increase this gradually to 2 years. Include preload once it is
// at least 1 year.
if (FREECODECAMP_NODE_ENV === 'production') {
void reply.header(
'Strict-Transport-Security',
'max-age=300; includeSubDomains'
);
}
});
done();
};
export default fp(securityHeaders);