user742030
user742030

Reputation:

How to Implement Helmet Into a Node Server? [w/o Express]

I am experimenting with npm modules for the first time and I am trying to implement helmet into a server module to set security headers. I know that helmet is meant for Express but I am not using Express.

Can I still use `helmet' in the following server module? If so, How do I go about it (code examples would be appreciated)? If not, what can I use that will "plug-in" into the module below or should I attack this differently?

Thx for your help/input.

'use strict';

var helmet  = require('helmet')
  , web     = require('node-static')
  , chalk   = require('chalk');

var server;

module.exports = plugin;

function plugin(options) {
  var defaults = {
      cache: 0
    , port: 8080
    , host: "localhost"
    , verbose: false
  };

  var opts = options || {};

  setDefaults(opts, defaults);

  return function(files, staticsmith, done) {
    if (server) {
      done();
      return;
    }

    var docRoot = staticsmith.destination()
      , fileServer = new web.Server(docRoot, { cache: opts.cache});

    server = require('http').createServer(function (request, response) {

      request.addListener('end', function () {

        fileServer.serve(request, response, function(err, res) {

          if (err) {
            log(chalk.red("[" + err.status + "] " + request.url), true);

            response.writeHead(err.status, err.headers);
            response.end("Not found");

          } else if (opts.verbose) {
            log("[" + response.statusCode + "] " + request.url, true);
          }
        });

      }).resume();

    }).listen(opts.port, opts.host);

    server.on('error', function (err) {
      if (err.code == 'EADDRINUSE') {
        log(chalk.red("Address " + opts.host + ":" + opts.port + " already in use"));
        throw err;
      }
    });

    log(chalk.green("serving " + docRoot + " at http://" + opts.host + ":" + opts.port));
    done();
  };

  function setDefaults(opts, defaults) {
    Object.keys(defaults).forEach(function(key) {
      if (!opts[key]) {
        opts[key] = defaults[key];
      }
    });
  }

  function formatNumber(num) {
    return num < 10 ? "0" + num : num;
  }

  function log(message, timestamp) {
    var tag    = chalk.blue("[staticsmith-serve]");
    var date   = new Date();
    var tstamp = formatNumber(date.getHours()) + ":" + formatNumber(date.getMinutes()) + ":" + formatNumber(date.getSeconds());
    console.log(tag + (timestamp ? " " + tstamp : "") + " " + message);
  }
}

Upvotes: 3

Views: 2792

Answers (1)

user742030
user742030

Reputation:

The best solution was to implement a Security Headers policy by not using any-kind of "middleware". This keeps things simpler, cleaner and more secure on the server by not relying on another developers module.

To do so, I created a security-config.json5 file that holds the settings making it easy to maintain and update:

module.exports = {
  security: [
    { name:  'Cache-Control',
      value: 'public, max-age=30672000'
    },
    { name:   'server',
      value:  'mySpecial-Server'
    },
    { name:   'Strict-Transport-Security',
      value:  'max-age=86400'
    },
    { name:   'X-Content-Type-Options',
      value:  'nosniff'
    },
    { name:   'X-Frame-Options',
      value:  'DENY'
    },
    { name:   'X-Powered-By',
      value:  'Awesomeness'
    },
    { name:   'X-XSS-Protection',
      value:  '1; mode=block'
    },
    { name:   'Content-Security-Policy',
      value:  "default-src 'none'; script-src 'self' https://cdnjs.cloudflare.com connect-src 'self'; img-src 'self' data:; style-src 'self' https://cdnjs.cloudflare.com; font-src 'self' https://cdnjs.cloudflare.com; manifest-src 'self'"
    }
  ]
};

The above settings are a good starting point, taking special note to the quotes for the Content-Security-Policy key/value, but you may want to do some tweaks for your site. I also show how to implement a CDN here.

Now in your createServer() function, you can loop thru the key:value pairs and add them to your headers using setHeader():

var security_default = require('./security-config.json5');

for(let i = 0; i < security_default.security.length; i++) {
  res.setHeader(
    security_default.security[i].name,
    security_default.security[i].value
  );
}

The Helmet Node module on npm is great but it's bloated (requires 3MB of disc-space) and requires regular updating while this method is light (<850bytes), plugable and maintainable for those who wish not to use middleware.

Upvotes: 8

Related Questions