2.0.0 • Published 7 years ago

esecurity v2.0.0

Weekly downloads
1
License
MIT
Repository
github
Last release
7 years ago

esecurity NPM version Build status Test coverage License

Security middlewares for express framework (xsrf, xss, clickjacking...).

Installation

  npm install esecurity

Middlewares

CORS

Cross-site HTTP requests are HTTP requests for resources from a domain different of the resource making the request.

    var esecurity = require('esecurity');
    var express = require('express');

    var app = express();

    app.use(esecurity.cors({
        origin: '*',
        credentials: true,
        methods: ['POST'],
        headers: ['X-PINGOTHER'],
        exposeHeaders: ['X-PINGOTHER'],
        maxAge: 60
    }));

    app.use(function(req, res){
        res.end('Hello world.');
    });

    app.listen(9898);

Options

esecurity.cors([options])

NameValueDescription
originStringThis parameter specifies a URI that may access the resource.Default to *.
credentialsBooleanIndicates whether or not the response to the request can be exposed when the credentials flag is true.Default to false.
methodsArraySpecifies the method or methods allowed when accessing the resource.Default to ['GET', 'PUT', 'POST', 'DELETE'].
headersArrayUsed in response to a preflight request to indicate which HTTP headers can be used when making the actual request.Default to ['Origin', 'X-Requested-With', 'Content-Type', 'Accept'].
exposeHeadersStringThis parameter lets a server whitelist headers that browsers are allowed to access.Default to false.
maxAgeNumberSpecify how long the results of a preflight request can be cached.Default to 0.

XSS

Cross-site scripting (XSS) attacks occur when one website, generally malicious, injects (adds) JavaScript code into otherwise legitimate requests to another website.

    var esecurity = require('esecurity');
    var express = require('express');

    var app = express();

    app.use(esecurity.xss());

    app.use(function(req, res){
        res.end('Hello world.');
    });

    app.listen(9898);

Options

esecurity.xss([options])

NameValueDescription
blockModeBooleanSpecify whether or not render only # in IE instead of attempting to sanitize the page to surgically remove the XSS attack.Default to true.

HSTS

HTTP Strict Transport Security (HSTS) is a web security policy mechanism whereby a web server declares that complying user agents (such as a web browser) are to interact with it using only secure HTTPS connections (i.e. HTTP layered over TLS/SSL).

    var esecurity = require('esecurity');
    var express = require('express');

    var app = express();

    app.use(esecurity.hsts({
        maxAge: 60,
        includeSudomains: true
    }));

    app.use(function(req, res){
        res.end('Hello world.');
    });

    app.listen(9898);

Options

esecurity.hsts([options])

NameValueDescription
maxAgeNumberSet the number of seconds, after the reception of the STS header field, during which the UA regards the host (from whom the message was received) as a Known HSTS Host.Default to 365 * 24 * 60 * 60 (one year).
includeSudomainsBooleanOptional directive specifying that this HSTS Policy also applies to any hosts whose domain names are subdomains of the Known HSTS Host's domain name.Default to false.

MimeSniffing

MimeSniffing attempts to determine the content-type for each downloaded resource and therefore can have security issues.

    var esecurity = require('esecurity');
    var express = require('express');

    var app = express();

    app.use(esecurity.mimeSniffing());

    app.use(function(req, res){
        res.end('Hello world.');
    });

    app.listen(9898);

Options

None

XSRF

XSRF is a technique by which an unauthorized site can gain your user's private data.

    var esecurity = require('esecurity');
    var express = require('express');
    var cookieParser = require('cookie-parser');
    var expressSession = require('express-session');
    var bodyParser = require('body-parser');

    var app = express();

    app.use(cookieParser());

    app.use(expressSession({
        resave: false,
        saveUninitialized: false,
        secret: 'esecurity example'
    }));

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    app.use(esecurity.xsrf({
        skip: function (req, res) {
            return /^\/noxsrf/i.test(req.url);
        },
        cookie: {
            path: '/',
            secure: false
        }
    }));

    app.get('/api/xsrf.json', function(req, res, next){
        res.json({ 'xsrf': req.xsrfToken() });
    });

    app.get('/', function(req, res, next){
        res.end('Hello world.');
    });

    app.listen(9898);

Options

esecurity.xsrf([options])

NameValueDescription
skipFunction, BooleanOptional directive skipping angularXsrf module if function return true.Default to function(req, res) {};.
cookieNameStringOptional. Specify the cookie name. If empty, xsrf token will not be passed by cookie.Default to an empty string.
angularBooleanOptional. Shortname for cookiName: 'XSRF-TOKEN' will support Angular xsrf handling.Default to false.
cookieObjectOptional. Specify cookie options used in res.cookie.Default to {}.

Content Security Policy (CSP)

Content Security Policy (CSP) is a computer security concept, to prevent cross-site scripting (XSS) and related attacks.

    var esecurity = require('esecurity');
    var express = require('express');

    var app = express();

    app.use(esecurity.csp({
        scriptSrc: ["self", "www.google-analytics.com"]
    }));

    app.use(function(req, res){
        res.end('Hello world.');
    });

    app.listen(9898);

Options

esecurity.csp([options])

NameValueDescription
headersArraySpecify which headers name to add Content-Security-Policy (standard) and/or X-Content-Security-Policy, X-Webkit-CSP (experimental). Possible values are "standard", "experimental".Default to standard.
rules_secureBooleanSpecify whether or not use predefined secure directive rules.Default to true.
defaultSrcStringRefer to default-src directive.
scriptSrcStringRefer to script-src directive.
objectSrcStringRefer to object-src directive.
styleSrcStringRefer to style-src directive.
imgSrcStringRefer to img-src directive.
mediaSrcStringRefer to media-src directive.
frameSrcStringRefer to frame-src directive.
fontSrcStringRefer to font-src directive.
connectSrcStringRefer to connect-src directive.
sandboxStringRefer to sandbox directive.
reportUriStringRefer to report-uri directive.
reportOnlyBooleanindicating whether or not use Content-Security-Policy-Report-Only header field. The Content-Security-Policy-Report-Only header field lets servers experiment with policies by monitoring (rather than enforcing) a policy.Default to false.
reportFilenameStringFilename where to write report data.Default to /tmp/esecurity_cspreport.
onReportFunction (msg)Use to write report data.Default to function (data) {...}.

ClickJacking

Clickjacking (User Interface redress attack, UI redress attack, UI redressing) is a malicious technique of tricking a Web user into clicking on something different from what the user perceives they are clicking on, thus potentially revealing confidential information or taking control of their computer while clicking on seemingly innocuous web pages.

    var esecurity = require('esecurity');
    var express = require('express');

    var app = express();

    app.use(esecurity.clickJacking({
        sameOrigin: true
    }));

    app.use(function(req, res){
        if (!/\.js$/i.test(req.url)) 
            res.sendfile(__dirname + '/test.html');
    });

    app.listen(9898);

With test.html file:

    <!DOCTYPE html>
    <html>
        <head>
            <script src="clickjacking_protection.js"/>
        </head>
        <body>
            <pre>Hello world.</pre>
        </body>
    </html>

Options

esecurity.clickJacking([options])

NameValueDescription
denyBooleanSpecify whether or not use DENY x-frame-option.Default to true.
sameOriginBooleanSpecify whether or not use SAMEORIGIN x-frame-option.Default to false.
allowFromStringSpecify origin to use in ALLOW-FROM x-frame-option.Default is empty.
jsUrlStringSpecify URI to load javascript file containing clickjacking protection.Default to clickjacking_protection.js.

ZoneLimit

This module helps you to limit requests according ip, cookie or anything else.

    var esecurity = require('esecurity');
    var express = require('express');

    var app = express();

    app.use(esecurity.zoneLimit({
        keyZone: function(req) {
            return req.ip;
        }
    }));

    app.use(function(req, res){
        res.end('Hello world.');
    });

    app.listen(9898);

Options

esecurity.zoneLimit([options])

NameValueDescription
rateNumberSpecify the rate limit ceiling.Default to 100.
windowNumberSpecify the time window in seconds.Default to 5.
delayGcNumberSpecify the delay in seconds before garbage collector is launched.Default to 20.
keyZoneFunction (req)Returns name of the zone to catch.Default to function(req) { return req.ip; };.
logFunction (msg)Log denied requests.Default is to not log.

Rate

This module helps you to limit requests by session and by route. X-Rate-Limit headers can be sent to client.

    var esecurity = require('esecurity');
    var express = require('express');

    var app = express();

    app.use(express.cookieParser());
    app.use(express.session({ secret: 'SECRET_KEY' }));

    app.get('/', esecurity.rate({ rate: 2, window: 5, enableHeaders: true }), function(req, res, next) {
        res.end('Hello world.');
    });

    app.listen(9898);

Options

esecurity.rate([options])

NameValueDescription
rateNumberSpecify the rate limit ceiling.Default to 100.
windowNumberSpecify the time window in minutes.Default to 15.
enableHeadersBooleanEnable response headers (X-Rate-Limit-Limit, X-Rate-Limit-Remaining, X-Rate-Limit-Reset).Default to false.With: - X-Rate-Limit-Limit: the rate limit ceiling for that given request - X-Rate-Limit-Remaining: the number of requests left for the N minute window - X-Rate-Limit-Reset: the remaining window before the rate limit resets in UTC epoch seconds

Run Tests

Tests are given complete coverage of all features.

  $ npm test

Examples

To run examples, clone the Esecurity repo and install the example/test suite dependencies:

$ git clone git://github.com/math-nao/esecurity.git --depth 1
$ cd esecurity
$ npm install

then run any example:

$ node examples/cors

License

MIT

2.0.0

7 years ago

1.0.1

10 years ago

0.1.2

10 years ago

0.1.1

10 years ago

0.1.0

10 years ago

1.0.0

10 years ago