How to use the helmet.contentSecurityPolicy function in helmet

To help you get started, we’ve selected a few helmet examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github partio-scout / reki / src / server / server.js View on Github external
done(null, models.User.toClientFormat(user, sessionType));
    } catch (e) {
      done(e);
    }
  });

  app.use(helmet());
  app.use(helmet.noCache()); // noCache disabled by default

  if (appConfig.standalone) {
    app.use(morgan('dev'));
  }

  const validConnectSrc = appConfig.isDev ? ['*'] : ["'self'"];

  app.use(helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'"],
      connectSrc: validConnectSrc,
      styleSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'"],
    },
  }));

  app.use((err, req, res, next) => {
    console.error(err);
    res.status(500).send('Internal server error');
  });

  await updateDatabase(app);
  errorHandling(app);
github magda-io / magda / magda-gateway / src / buildApp.ts View on Github external
}
    );
    installStatusRouter(app, { probes });

    // Redirect http url to https
    app.set("trust proxy", true);
    app.use(createHttpsRedirectionMiddleware(config.enableHttpsRedirection));

    // GZIP responses where appropriate
    app.use(compression());

    // Set sensible secure headers
    app.disable("x-powered-by");
    app.use(helmet(_.merge({}, defaultConfig.helmet, config.helmetJson as {})));
    app.use(
        helmet.contentSecurityPolicy(
            _.merge({}, defaultConfig.csp, config.cspJson)
        )
    );

    // Set up CORS headers for all requests
    const configuredCors = cors(
        _.merge({}, defaultConfig.cors, config.corsJson as {})
    );
    app.options("*", configuredCors);
    app.use(configuredCors);

    // Configure view engine to render EJS templates.
    app.set("views", path.join(__dirname, "..", "views"));
    app.set("view engine", "ejs");
    app.engine(".ejs", ejs.__express); // This stops express trying to do its own require of 'ejs'
github adeperio / base / src / server / server.js View on Github external
server.set('view engine', 'jade');

//Setup location to static assets
server.use(express.static(path.join(__dirname)));

// ======== *** SECURITY MIDDLEWARE ***

//setup helmet js
server.use(helmet());

//setting CSP
var scriptSources = ["'self'", "'unsafe-inline'", "'unsafe-eval'", "ajax.googleapis.com", "www.google-analytics.com"];
var styleSources = ["'self'", "'unsafe-inline'", "ajax.googleapis.com"];
var connectSources = ["'self'"];

server.use(helmet.contentSecurityPolicy({
    defaultSrc: ["'self'"],
    scriptSrc: scriptSources,
    styleSrc: styleSources,
    connectSrc: connectSources,
    reportOnly: false,
    setAllHeaders: false,
    safari5: false
}));

server.use(methodOverride());
server.use(bodyParser());

//setup express sessions
server.use(cookieParser());
server.use(session({
  store: new pgSession({
github mozilla / learning.mozilla.org / app.js View on Github external
serverBundle = requireUncached('./build/server.library');
    router = React.createElement(Router, {routes: serverBundle.routes});
  });
}


var app = express();

/**
 * Several app security settings
 */
app.disable('x-powered-by');

var securityHeaders = require('./server/security-headers');

app.use(helmet.contentSecurityPolicy(securityHeaders));

app.use(helmet.xssFilter({
  setOnOldIE: true
}));


// maxAge for HSTS header must be at least 18 weeks (see https://hstspreload.org/)
app.use(helmet.hsts({
  maxAge: 60 * 60 * 24 * 7 * 18 // 18 weeks in seconds
}));

app.use(helmet.ieNoOpen());

app.use(helmet.noSniff());

/**
github mcibique / express-security / server / middlewares / security.js View on Github external
includeSubdomains: true,
    preload: true
  }));
  // X-Powered-By: http://expressjs.com/en/4x/api.html#app.settings.table
  app.disable('x-powered-by');
  // X-Download-Options: https://github.com/helmetjs/ienoopen
  app.use(helmet.ieNoOpen());
  // X-Content-Type-Options: https://github.com/helmetjs/dont-sniff-mimetype
  app.use(helmet.noSniff());
  // Content-Security-Policy: https://github.com/helmetjs/csp
  app.use(function nonceGenerator(req, res, next) {
    res.locals.nonce = uuid.v4();
    next();
  });
  /* eslint-disable quotes */
  app.use(helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: [ "'self'", (req, res) => `'nonce-${res.locals.nonce}'` ],
      styleSrc: [ "'self'", (req, res) => `'nonce-${res.locals.nonce}'` ],
      baseUri: ["'self'"],
      connectSrc: [ "'self'", 'wss:' ],
      frameAncestors: ["'none'"],
      reportUri: config.csp.reportUri
    },
    setAllHeaders: false,
    reportOnly: false,
    browserSniff: false
  })); /* eslint-enable */
  // Public-Key-Pins: https://github.com/helmetjs/hpkp
  app.use(helmet.hpkp({
    maxAge: ms(config.hpkp.maxAge) / 1000,
github strues / boldr / packages / server / src / middleware / initSecurity.js View on Github external
// Note: Setting this to stricter than * breaks the service worker. :(
          // I can't figure out how to get around this, so if you know of a safer
          // implementation that is kinder to service workers please let me know.
          // ["'self'", 'ws:'],
          connectSrc: ['*'],

          // objectSrc: [ "'none'" ],
          // mediaSrc: [ "'none'" ],

          childSrc: ["'self'"],
        },
      }
    : null;

  if (enableCSP) {
    app.use(helmet.contentSecurityPolicy(cspConfig));
  }

  // The xssFilter middleware sets the X-XSS-Protection header to prevent
  // reflected XSS attacks.
  // @see https://helmetjs.github.io/docs/xss-filter/
  app.use(helmet.xssFilter());

  // Frameguard mitigates clickjacking attacks by setting the X-Frame-Options header.
  // We disable this for embedding
  // @see https://helmetjs.github.io/docs/frameguard/
  app.use(helmet.frameguard('false'));

  // Sets the X-Download-Options to prevent Internet Explorer from executing
  // downloads in your site’s context.
  // @see https://helmetjs.github.io/docs/ienoopen/
  app.use(helmet.ieNoOpen());
github edwardwohaijun / draw / app.js View on Github external
let express = require('express');
let http = require('http');
let path = require('path');
let logger = require('morgan');
let bodyParser = require('body-parser');
let sysConfig = require('./config/systemConfig')();

let app = express();
app.disable('x-powered-by');

// if you don't know what helmet and contentSecurity is, comment out the following block, or take some time learning
let helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
  browserSniff: false,
  setAllHeaders: false,
  directives:{
    defaultSrc: ["'self'"],
    childSrc: ["'none'"],
    objectSrc: ["'none'"],
    scriptSrc: ["'self'"],
    styleSrc: ["'self'", "'unsafe-inline'"],
    imgSrc: ["'self'", 'data:', 'blob:', "https://cdn.jsdelivr.net",  "http://cdn.jsdelivr.net"],
    fontSrc: ["'self'"],
    connectSrc: ["'self'", `wss://${sysConfig.hostname}:${sysConfig.port}`, `ws://${sysConfig.hostname}:${sysConfig.port}`,
      `wss://127.0.0.1:${sysConfig.port}`, `ws://127.0.0.1:${sysConfig.port}`],
  }
}));
app.use(helmet.xssFilter());
github jverhoelen / node-express-typescript-boilerplate / service / server / ExpressServer.ts View on Github external
private setupSecurityMiddlewares(server: Express) {
        server.use(hpp())
        server.use(helmet())
        server.use(helmet.referrerPolicy({ policy: 'same-origin' }))
        server.use(helmet.noCache())
        server.use(
            helmet.contentSecurityPolicy({
                directives: {
                    defaultSrc: ["'self'"],
                    styleSrc: ["'unsafe-inline'"],
                    scriptSrc: ["'unsafe-inline'", "'self'"]
                }
            })
        )
    }
github gardener / dashboard / backend / lib / app.js View on Github external
app.set('io', api.io)
app.set('trust proxy', 1)
app.set('etag', false)
app.set('x-powered-by', false)

app.use(helmet.dnsPrefetchControl())
app.use(helmet.permittedCrossDomainPolicies())
app.use(helmet.noSniff())
app.use(helmet.hsts())
app.use('/auth', auth.router)
app.use('/api', api.router)
app.use('/webhook', githubWebhook.router)
app.get('/config.json', api.frontendConfig)

app.use(helmet.xssFilter())
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ['\'self\''],
    connectSrc,
    styleSrc: ['\'self\'', '\'unsafe-inline\'', 'https://fonts.googleapis.com', 'https://cdn.materialdesignicons.com'],
    fontSrc: ['\'self\'', 'https://fonts.gstatic.com', 'https://cdn.materialdesignicons.com'],
    imgSrc,
    scriptSrc: ['\'self\'', '\'unsafe-eval\''],
    frameAncestors: ['\'none\'']
  }
}))
app.use(helmet.referrerPolicy({
  policy: 'same-origin'
}))

app.use(express.static(PUBLIC_DIRNAME))
github alphagov / paas-admin / src / components / app / app.ts View on Github external
app.use(cookieSession({
    name: 'pazmin-session',
    keys: [config.sessionSecret],
    secure: !config.allowInsecureSession,
    httpOnly: true,
  }));

  app.use('/assets', staticGzip('dist/assets', {immutable: true}));
  app.use('/assets', staticGzip('node_modules/govuk-frontend/govuk', {immutable: true}));
  app.use('/assets', staticGzip('node_modules/govuk-frontend/govuk/assets', {immutable: true}));
  app.use('/assets', staticGzip('node_modules/d3/dist', {immutable: true}));
  app.use('/assets', staticGzip('node_modules/d3-sankey/dist', {immutable: true}));
  app.use(compression());

  app.use(helmet());
  app.use(helmet.contentSecurityPolicy(csp));

  app.use(express.urlencoded({extended: true}));
  app.use(csrf());

  app.get('/healthcheck', (_req: express.Request, res: express.Response) => res.send({message: 'OK'}));

  app.get('/forbidden', () => {
    throw new NotAuthorisedError('Forbidden');
  });

  app.get('/calculator', (req: express.Request, res: express.Response, next: express.NextFunction) => {
    const route = router.findByName('admin.home');
    const ctx = initContext(req, router, route, config);

    getCalculator(ctx, {...req.query, ...req.params, ...route.parser.match(req.path)})
      .then((response: IResponse) => {