An open API service indexing awesome lists of open source software.

https://github.com/reallyreally/reallysecure

ExpressJS Security Middleware
https://github.com/reallyreally/reallysecure

Last synced: about 1 year ago
JSON representation

ExpressJS Security Middleware

Awesome Lists containing this project

README

          

[![Known Vulnerabilities](https://snyk.io/test/github/reallyreally/reallySecure:package.json/badge.svg?targetFile=package.json)](https://snyk.io/test/github/reallyreally/reallySecure:package.json?targetFile=package.json)

# ExpressJS Security Layer

Introduces comprehensive security for your ExpressJS based application.

## Is this for you?

This package has been built for our specific needs. Your mileage may vary. Be very cautious enabling HSTS - do not turn it on unless you understand the implications for your domain and subdomains.

### Prerequisites

This package is called while instantiating your ExpressJS based application. It is not a stand-alone package.

### Glitch

You can check this out on [Glitch](https://glitch.com/edit/#!/really-secure) - see working code examples, and test it yourself without any effort!

### Installing

Assuming you are starting an ExpressJS project from scratch.
Create your ExpressJS project.

```
express --view=hbs --css=less --git my-secure-project
```

Then install ExpressJS

```
cd my-secure-project && npm install
```

Then install this package

```
npm install --save @really/really-secure
```

Now you should be able to add it to your application layer

## Using with ExpressJS

In your app.js require the package

```
var securityLayer = require('@really/really-secure');
```

Prepare your configuration

```
var reallySecureConfig = {
"csp": {
"fontSrc": ["'self'", "use.typekit.net"],
"imgSrc": ["'self'", "data:"],
"defaultSrc": ["'self'"],
"reportUri": "/cspreport",
"upgradeInsecureRequests": true
},
"poweredBy": "A Secure Engine"
}
```

Now add it to the application flow

```
// Secure site
app.use(securityLayer(reallySecureConfig));
```

**Using A Load Balancer? (Like Google App Engine)**

You will need to trust the proxy or you will end up with SSL issues.

```
// Trust App Engine proxy
app.enable('trust proxy')
```

**A Node about NODE_ENV**

Many of the security requirements that force or require SSL (like HSTS) are ignored unless you are `NODE_ENV=production`
This is a conscious choice to enable local development (without SSL) but retain security when deployed with little to no interaction.

### Example app.js

Your app.js may end up looking like this

```
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var securityLayer = require('@really/really-secure');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

var reallySecureConfig = {
"csp": {
"fontSrc": ["'self'", "use.typekit.net"],
"imgSrc": ["'self'", "data:"],
"defaultSrc": ["'self'"],
"reportUri": "/cspreport",
"upgradeInsecureRequests": true
},
"poweredBy": "A Secure Engine"
}

// Secure site
app.use(securityLayer(reallySecureConfig));

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;

```

## Using a nonce

For your security pleasure - we generate a nonce for each request. Where your site has inline script or other elements, and those elements are inserted intentionally - you can use the nonce to validate the insertion.

The nonce is automatically added to all the CSP types, so no extra work is required here. The nonce value is available in `res.locals` - as `res.locals.nonce`.

If you are using handlebars - you might end up with something like this `layout.hbs` example. (Note the ``)

```
<!doctype html>
<html class="no-js" lang="en-US">
<head>
<!-- Google Tag Manager -->
<script nonce="{{ nonce }}">(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-A0A0000');



Example Layout








{{{body}}}