npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

esecurity

v2.0.0

Published

Add security layers to express.

Downloads

4

Readme

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])

Name | Value | Description ------ | ----- | ----------- origin | String | This parameter specifies a URI that may access the resource.Default to *. credentials | Boolean | Indicates whether or not the response to the request can be exposed when the credentials flag is true.Default to false. methods | Array | Specifies the method or methods allowed when accessing the resource.Default to ['GET', 'PUT', 'POST', 'DELETE']. headers | Array | Used 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']. exposeHeaders | String | This parameter lets a server whitelist headers that browsers are allowed to access.Default to false. maxAge | Number | Specify 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])

Name | Value | Description ------ | ----- | ----------- blockMode | Boolean | Specify 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])

Name | Value | Description ------ | ----- | ----------- maxAge | Number | Set 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). includeSudomains | Boolean | Optional 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])

Name | Value | Description ------ | ----- | ----------- skip | Function, Boolean | Optional directive skipping angularXsrf module if function return true.Default to function(req, res) {};. cookieName | String | Optional. Specify the cookie name. If empty, xsrf token will not be passed by cookie.Default to an empty string. angular | Boolean | Optional. Shortname for cookiName: 'XSRF-TOKEN' will support Angular xsrf handling.Default to false. cookie | Object | Optional. 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])

Name | Value | Description ------ | ----- | ----------- headers | Array | Specify 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_secure | Boolean | Specify whether or not use predefined secure directive rules.Default to true. defaultSrc | String | Refer to default-src directive. scriptSrc | String | Refer to script-src directive. objectSrc | String | Refer to object-src directive. styleSrc | String | Refer to style-src directive. imgSrc | String | Refer to img-src directive. mediaSrc | String | Refer to media-src directive. frameSrc | String | Refer to frame-src directive. fontSrc | String | Refer to font-src directive. connectSrc | String | Refer to connect-src directive. sandbox | String | Refer to sandbox directive. reportUri | String | Refer to report-uri directive. reportOnly | Boolean | indicating 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. reportFilename | String | Filename where to write report data.Default to /tmp/esecurity_cspreport. onReport | Function (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])

Name | Value | Description ------ | ----- | ----------- deny | Boolean | Specify whether or not use DENY x-frame-option.Default to true. sameOrigin | Boolean | Specify whether or not use SAMEORIGIN x-frame-option.Default to false. allowFrom | String | Specify origin to use in ALLOW-FROM x-frame-option.Default is empty. jsUrl | String | Specify 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])

Name | Value | Description ------ | ----- | ----------- rate | Number | Specify the rate limit ceiling.Default to 100. window | Number | Specify the time window in seconds.Default to 5. delayGc | Number | Specify the delay in seconds before garbage collector is launched.Default to 20. keyZone | Function (req) | Returns name of the zone to catch.Default to function(req) { return req.ip; };. log | Function (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])

Name | Value | Description ------ | ----- | ----------- rate | Number | Specify the rate limit ceiling.Default to 100. window | Number | Specify the time window in minutes.Default to 15. enableHeaders | Boolean | Enable 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