GithubHelp home page GithubHelp logo

venables / koa-helmet Goto Github PK

View Code? Open in Web Editor NEW
639.0 8.0 38.0 886 KB

Important security headers for koa

License: MIT License

JavaScript 100.00%
helmet secure secure-by-default koa koa2 middleware koa-helmet headers

koa-helmet's Introduction

koa-helmet

Version Dependency Status js-semistandard-style Downloads

koa-helmet is a wrapper for helmet to work with koa. It provides important security headers to make your app more secure by default.

Installation

npm i koa-helmet

# or:

yarn add koa-helmet

Usage

Usage is the same as helmet

Helmet offers 11 security middleware functions:

// This...
app.use(helmet());

// ...is equivalent to this:
app.use(helmet.contentSecurityPolicy());
app.use(helmet.dnsPrefetchControl());
app.use(helmet.expectCt());
app.use(helmet.frameguard());
app.use(helmet.hidePoweredBy());
app.use(helmet.hsts());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.permittedCrossDomainPolicies());
app.use(helmet.referrerPolicy());
app.use(helmet.xssFilter());

You can see more in the documentation.

Example

import Koa from 'koa';
import helmet from 'koa-helmet';

const app = new Koa();

app.use(helmet());

app.use((ctx) => {
  ctx.body = "Hello World"
});

app.listen(4000);

Testing

To run the tests, simply run

npm test

Versioning

  • koa-helmet >=2.x (master branch) supports koa 2.x
  • koa-helmet 1.x (koa-1 branch) supports koa 0.x and koa 1.x

koa-helmet's People

Contributors

a-s-o avatar anthonylau avatar davdiv avatar dependabot[bot] avatar dola avatar evanhahn avatar hatchan avatar heunghingwan avatar hickford avatar jbuck avatar jeffharrell avatar johnnyreilly avatar kevinmartin avatar mahovich avatar mareksuscak avatar mattjay avatar natevw avatar nfantone avatar omgimalexis avatar panva avatar philtrep avatar pkuczynski avatar ratson avatar renehamburger avatar sp3nx0r avatar venables avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

koa-helmet's Issues

Unknown directive ‘script-src-attr’

After upgrading to 6.0.0 I started to get the following error: Content Security Policy: Couldn’t process unknown directive ‘script-src-attr’. I reverted back to 5.2.0 and the error message is gone. Here's the other packages in use:

├── @koa/[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

Helmet expects an Express request object but koa-helmet passes it a Node request

This is specifically a problem when Helmet is looking for fields on the request that a Node request doesn't have, like request.secure.

You can see this with the hsts() middleware which doesn't send the Strict-Transport-Security header since ctx.req.secure is always undefined. Passing in ctx.request fixes this specific issue, but there might not be a robust solution at hand since Koa request objects aren't guaranteed to be the same as Express request objects.

For the hsts() middleware, an easy workaround is to configure the middleware with { force: ctx.request.secure } but it's a little fragile that Helmet's logic for whether to send the HSTS response header needs to be replicated.

ctx.state is undefined

Hello, I've originally encountered a problem with JQuery and koa-helmet's CSP, but found a solution by generating nonce for JQuery. Now my problem is by following the helmet documentation on how to generate nonces, I can't seem to replicate it in KOA2, my app is throwing an error saying ctx.state is undefined.

How to use CSP with koa-helmet?

With how middleware works in koa, i've found this to be surprisingly difficult. It was pretty easy to do in express, via locals, but I can't quite get it to work in koa. Am I missing something obvious here?

app.use(async (ctx, next) => {
    console.log('ctx.state => ', ctx.state); // { nonce: validNonceHere }
    return koaHelmet.contentSecurityPolicy({
      directives: {
        defaultSrc: ["'self'"],
        frameAncestors: ["'none'"],
        objectSrc: ["'none'"],
        reportUri: '/report-violation',
        scriptSrc: [
          "'self'",
          ' ajax.googleapis.com',
          `'nonce-${ctx.state.nonce}'`,
        ],
        upgradeInsecureRequests: true,
      },
      reportOnly: IS_DEV,
    });
  });

When I pass in helmet or a helmet function directly, it works fine. When I pass in an async middleware function, in order to access my nonce in state, nothing happens (or it 404s).

I know this isn't a bug or an 'issue', but maybe some clarity in the docs around this could help?

Thanks

Support for crossOrigin* headers

The type definition does not include the crossOriginEmbedderPolicy, crossOriginOpenerPolicy, nor the crossOriginOpenerPolicy listed in the API documentation for helmetjs (https://helmetjs.github.io/). Are they going to be added to the type definition and supported?

Consider making koa-helmet a wrapper instead of a fork

@venables We are discussing Koa support for Helmet in helmetjs/helmet#100
Please join the conversation and outline your vision for this project.

As a lesser important item, I would also like to know if you would be open to moving this project to the helmetjs Github orginization to make it more "official". Discussions with @EvanHahn about this would be needed. I'll open a new issue about this as well if EvanHahn thinks it is a good idea in helmetjs/helmet#100.

New TS types fail to import koa

Thanks for merging types directly into the lib.

My dependency bot is trying to pull this update, but my tsc builds with yarn 2.4.1 (with pnp) fail on it for some reason.

> tsc -b tsconfig.build.json

.yarn/cache/koa-helmet-npm-6.1.0-5168096bc9-63a0ab6ded.zip/node_modules/koa-helmet/koa-helmet.d.ts:9:37 - error TS2307: Cannot find module 'koa' or its corresponding type declarations.

To be honest, I'm kinda stumped, the source looks just fine.

Node 14.16.0 x64 on windows 10

tsconfig,json (definitely irrelevant stuff omitted)

{
    "compilerOptions": {
        "composite": true,
        "esModuleInterop": true,
        "importHelpers": true,
        "module": "commonjs",
        "noUncheckedIndexedAccess": true,
        "strict": true,
        "target": "es2020"
    }
}

package.json (also trimmed down)

    "dependencies": {
        "koa": "2.13.1",
        "koa-compose": "4.1.0",
        "koa-compress": "5.0.1",
        "koa-helmet": "6.1.0",
        "koa-router": "10.0.0",
    },
    "devDependencies": {
        "@types/koa": "2.13.1",
        "@types/koa-compose": "3.2.5",
        "@types/koa-compress": "4.0.1",
        "@types/koa-router": "7.4.1",
        "tslib": "2.1.0",
        "typescript": "4.2.3"
    }

I can send you a copy of my whole (tiny) project if you can't troubleshoot it with this.

hidePoweredBy doesn't work

For anyone using this library, hidePoweredBy doesn't work.

Workaround:

var koa = require('koa');
var app = koa();

app.poweredBy = false;

TypeError when setting secure property

I am working on a project that uses firebase. I opted to use TypeScript in this project for my cloud functions. I am using the nodejs 12 runtime.

Here is the error I am getting:
> TypeError: Cannot set property secure of #<IncomingMessage> which has only a getter

The issue seems to be occurring when the secure property is being assigned in the node request object ctx.req.

I am using koa-helmet in my standard non-typescript JS projects without any problems.

I am able to fix the issue when i comment out 'use strict' in lib/koa-helmet.js, but I'm not sure if this is the best solution.

CSP types need to be more flexible

Helmet allows the CSP directives object to contain arbitrary key-value pairs. The current typings for koa-helmet don't reflect this, so trying to do the following results in a type error:

app.use(helmet.contentSecurityPolicy({
  directives: {
    manifestSrc: ["'self'"]
  }
}));

There are several other missing directives, so it might make the most sense to just make this type definition more flexible instead of trying to maintain the list of possible options (that's what the underlying helmet library did helmetjs/helmet#328).

useDefaults not present in type declarations

I'm trying to use the useDefaults option, but Typescript doesn't like it:

app.use(helmet({
  contentSecurityPolicy: {
    // @ts-ignore
    useDefaults: true,
    directives: {
      'connect-src': 'https://*.sentry.io'
    }
  }
}))

also the helmet.contentSecurityPolicy.getDefaultDirectives() is not declared in the types.

BTW, using // @ts-ignore both work, so it's only a typing issue

helmet.defaults()

The koa-helmet 0.1.0 readme suggested using app.use(helmet.defaults());, but this now breaks.

What should the replacement be?

Error:

  TypeError: helmet.defaults is not a function
      at Object.<anonymous> (/[...]/apps/www/app-www.js:98:16)
      at Module._compile (module.js:430:26)
      at Object.Module._extensions..js (module.js:448:10)
      at Module.load (module.js:355:32)
      at Function.Module._load (module.js:310:12)
      at Module.require (module.js:365:17)
      at require (module.js:384:17)
      at Object.subApp (/[...]/app.js:84:37)
      at GeneratorFunctionPrototype.next (native)
      at onFulfilled (/[...]/node_modules/co/index.js:65:19)

res.setHeader is not a function

Hi,

const Koa = require('koa')
const helmet = require('helmet')
const app = new Koa()

app.use(helmet())

app.use((ctx) => {
  ctx.body = "Hello World"
});

app.listen(3000, () => {
  console.log('server up and running')
})

Generates "TypeError: res.setHeader is not a function"

If I comment out "app.use(helmet())" everything works normally.

Thanks

HSTS Not Set

I have the following Koa Helmet setup in my app and I'm not receiving the HSTS header as I would expect.

HTTP Response

HTTP/1.1 200 OK
Content-Security-Policy-Report-Only: default-src 'none'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self'; sandbox allow-forms allow-scripts; object-src; connect-src 'self'; report-uri https://domain.com
Content-Type: application/json; charset=utf-8
Date: Mon, 17 Oct 2016 01:38:18 GMT
X-Content-Type-Options: nosniff
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Content-Length: 729
Connection: Close

Code

var helmet = require('koa-helmet')
...
// use default helmet settings
app.use(helmet())

app.use(helmet.contentSecurityPolicy({
  // Specify directives as normal.
  directives: {
    defaultSrc: ["'none'"],
    scriptSrc: ["'self' 'unsafe-eval'"],
    styleSrc: ["'self' 'unsafe-inline'"],
    imgSrc: ["'self'"],
    sandbox: ['allow-forms', 'allow-scripts'],
    objectSrc: [], // An empty array allows nothing through
    'connect-src': ["'self'"],
    reportUri: 'https://<domain>.com'
  },

  // Set to true if you only want browsers to report errors, not block them
  reportOnly: true,

  // Set to true if you want to blindly set all headers: Content-Security-Policy,
  // X-WebKit-CSP, and X-Content-Security-Policy.
  setAllHeaders: false,

  // Set to true if you want to disable CSP on Android where it can be buggy.
  disableAndroid: false,

  // Set to false if you want to completely disable any user-agent sniffing.
  // This may make the headers less compatible but it will be much faster.
  // This defaults to `true`.
  browserSniff: true
}))

Upgrade helmet version to add support for `Feature-Policy`

The Feature-Policy header is currently not supported in helmet version 3.12.0 as used by this library.
See:
https://helmetjs.github.io/docs/feature-policy/

This first became available in [email protected] as discussed in this issue

I am aware that the way the dependency is specified, it theoretically allows for automatic update without a change to the package.json file of this library. We can however improve the situation for developers that heavily rely on package-lock.json files that potentially fix the dependency on a lower version.

Publish v1.1.0 to npm

The latest version for koa-v1 isn't published to npm. The last version for koa-v1 on npm is 1.0.0, which uses helmet 1.0 rather than helmet 3.0. As a result, I can't specify a configuration, because helmet 1.0 doesn't take configurations. 😭 koa-helmet v1.1.0 is big improvement. Please publish it to npm. Kthxbai

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.