GithubHelp home page GithubHelp logo

jagaapple / next-secure-headers Goto Github PK

View Code? Open in Web Editor NEW
306.0 6.0 13.0 605 KB

Sets secure response headers for Next.js.

License: MIT License

JavaScript 8.06% TypeScript 91.94%
nextjs headers security csp

next-secure-headers's People

Contributors

jagaapple avatar mattdell avatar naotone avatar samantha-wong 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

next-secure-headers's Issues

ESLint - no extraneous dependencies

๐Ÿ’ฉ Bug Report

A summary of the bug

ESLint is throwing an error on:

const { createSecureHeaders } = require('next-secure-headers');

'next-secure-headers' should be listed in the project's dependencies, not devDependencies.eslintimport/no-extraneous-dependencies

I was in fact wondering why should this be a development dependency given that the directives should, of course, be included in production.

Current behavior

This is next.config.js

   const { createSecureHeaders } = require('next-secure-headers');

 module.exports = {
     async headers() {
        return [{ source: '/(.*)', headers: createSecureHeaders() }];
    },
 };

To Reproduce

Install using $ npm install -D next-secure-headers

Per your documentation, it should be installed with the -D option, unless :

โ—๏ธ For withSecureHeaders . If you want to use withSecureHeaders , you have to install without -D option (i.e., installing as dependencies not devDependencies )

.

Expected behavior

No warnings from ESLint

Environment

  • This project version(s): v2.0.0
  • Nextjs version: 9.5.3
  • Nodejs version: v12.16.0
  • OS: macOS 10.15.6

Additional context

Add any other context about the problem here, or a screenshot if applicable.


  • I've tried to find similar issues
  • I would like to work on a fix ๐Ÿ’ช๐Ÿป

Google Analytics & Adsense errors

๐Ÿ’ฉ Bug Report

A summary of the bug

I set up next.config.js as below aiming at allowing the regular scripts from Analytics and Adsense but getting a number of errors.

I tried adding some of the origins to the config, but how can one be sure to have included all origins that Google may include.

Current behavior

With the following code at `next.config.js:

   async headers() {
    return [
        {
            source: '/(.*)',
            headers: createSecureHeaders({
                contentSecurityPolicy: {
                    directives: {
                        scriptSrc: [
                            "'self'",
                            'https://www.googletagmanager.com',
                            'https://pagead2.googlesyndication.com',
                            'https://partner.googleadservices.com',
                        ],
                    },
                },
            }),
        },
    ];
},

Getting these errors:
Screenshot 2021-06-20 at 12 34 17

To Reproduce

Code above

Expected behavior

Load scripts while keeping secure headers.

Environment

  • This project version(s): v2.1.0
  • Nodejs version: v14.15.3
  • OS: macOS 11.4

Additional context

Add any other context about the problem here, or a screenshot if applicable.


  • I've tried to find similar issues
  • I would like to work on a fix ๐Ÿ’ช๐Ÿป

Content-Security-Policy reportURI cannot be relative

๐Ÿ’ฉ Bug Report

A summary of the bug

next-secure-headers crashes if you try to use a relative URL in reportURI.

Here you can see what next-secure-headers is using URL for that directive:
https://github.com/jagaapple/next-secure-headers/blob/master/src/rules/content-security-policy.ts#L197
https://github.com/jagaapple/next-secure-headers/blob/master/src/rules/shared/uri-encoder.ts
And it is a bad idea.

Current behavior

Currently it crashes the server on its start:

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
TypeError [ERR_INVALID_URL]: Invalid URL
    at new NodeError (node:internal/errors:363:5)
    at onParseError (node:internal/url:536:9)
    at new URL (node:internal/url:612:5)
    at encodeStrictURI (/home/my/ui-auth/node_modules/next-secure-headers/lib/rules/shared/uri-encoder.js:4:34)
    at Array.map (<anonymous>)
    at convertReportingDirectiveToString (/home/my/***/node_modules/next-secure-headers/lib/rules/content-security-policy.js:109:62)
    at createContentSecurityPolicyOptionHeaderValue (/home/my/***/node_modules/next-secure-headers/lib/rules/content-security-policy.js:127:9)
    at Object.createContentSecurityPolicyHeader (/home/my/***/node_modules/next-secure-headers/lib/rules/content-security-policy.js:139:19)
    at Object.createHeadersObject (/home/my/***/node_modules/next-secure-headers/lib/index.js:18:23)
    at createSecureHeaders (/home/my/***/node_modules/next-secure-headers/lib/index.js:37:35) {
  input: '/api/csp_violation',
  code: 'ERR_INVALID_URL'
}

To Reproduce

Create following next.config.mjs

import { createSecureHeaders, } from 'next-secure-headers';

let cspDirectives = {
    defaultSrc: "'self'",
    styleSrc: ["'self'", "https://stackpath.bootstrapcdn.com"],
}; // any directives
cspDirectives.reportURI = '/api/csp_violation';

export default {
    async headers() {
        return [
            {
                source: '/(.*)',
                headers: createSecureHeaders({
                    contentSecurityPolicy: {
                        directives: cspDirectives,
                    },
                    referrerPolicy: 'no-referrer',
                }),
            },
        ];
    },
}

And run yarn run dev.

Expected behavior

No crash.

Helmet allows relative report-uri in CSP (e.g /api/csp_violation).

Also, specification allows such URIs:
https://w3c.github.io/webappsec-csp/#directive-report-uri
https://datatracker.ietf.org/doc/html/rfc3986#section-4.1

Environment

  • This project version(s): v2.2.0
  • Nodejs version: v16.3.0
  • OS: Ubuntu 16.04

  • I've tried to find similar issues
  • I would like to work on a fix ๐Ÿ’ช๐Ÿป

Nonce & Hash support for CSP Level 2

๐ŸŒฑ Feature Request

Is your feature request related to a problem? Please describe.

I am attempting to implement a CSP into my app and not use unsafe-inline.

The way I understand CSP is that for every HTTP request I need to generate a base64 nonce / hash which gets put on the script tag and in the CSP header prefixed with nonce-.

Describe the solution you'd like

I am not entirely sure on the solution I need here.
In my opinion it would be nice to have a solution which allows me to access a generated base64 string and pass it into both the headers and the script tags

Describe alternatives you've considered

I haven't considered any way of approaching this yet but I'll continue to try.


  • I've tried to find similar issues and pull requests
  • I would like to work on this feature ๐Ÿ’ช๐Ÿป

Modify `source` value in sample codes

๐Ÿ’ฉ Bug Report

A summary of the bug

Currently the readme is written source: "/(.*)" , but it does not working in some cases -- for example, an application uses Next.js built-in I18n routings.

Current behavior

Configured headers is not applied in some cases.

Expected behavior

It should be applied even if an application uses Next.js built-in I18n routings.

Additional context

Use "/:path*" instead.


  • I've tried to find similar issues
  • I would like to work on a fix ๐Ÿ’ช๐Ÿป

Support spec names of CSP directives

๐ŸŒฑ Feature Request

Is your feature request related to a problem? Please describe.

The spec defines directives in kebab-case, e.g. script-src, these are currently not picked up, but appear as undefined.

Describe the solution you'd like

Since the camel-cased directives are sensible as well, supporting both would be nice.

Add how to set unsupported headers to readme

๐ŸŒฑ Feature Request

Is your feature request related to a problem? Please describe.

Next.js supports to set any headers, but some developers don't know about it.

Describe the solution you'd like

Readme should be written how to set unsupported headers in next-secure-headers using the standard way in Next.js.

Describe alternatives you've considered

None.

Documentation, Adoption, Migration Strategy

None.

Additional context

This will be released in 2.3.0.


  • I've tried to find similar issues and pull requests
  • I would like to work on this feature ๐Ÿ’ช๐Ÿป

Support for setting dynamic frameAncestors URLs

Hi,

I need to set frameAncestors to different URLs depending on the current URL.
I have not been able to do that with next.config.js or withSecureHeaders, although I might be missing something?

Thanks,
-Louise

Add support for Next.js 9.5 and static pages

Vercel has introduced Next.js v9.5, and it supports to configure custom response headers in Next.js ( next.config.js ) for servers and static pages. I think next-secure-headers can supports static pages without getInitialProps and getServerSideProps , also it is possible to enable Automatic Static Optimization (#11).

https://nextjs.org/blog/next-9-5

These changes require breaking changes, so that I'll release them as v2, and it is not backward-compatible with v1.x.

Typo in README file, `soruce` instead of `source`

๐Ÿ’ฉ Bug Report

A summary of the bug

Hello,
There is a typo in README file in property name. It says soruce, but it should be source instead.
There are 4 places in a file with this typo, to be precise.

Environment

  • This project version(s): v2.0.0

  • I've tried to find similar issues
  • I would like to work on a fix ๐Ÿ’ช๐Ÿป

Support for Content-Security-Policy: upgrade-insecure-requests;

๐ŸŒฑ Feature Request

Is your feature request related to a problem? Please describe.

A clear and concise description of what you want and what your use case is.

Hi,
There is a way to set the upgrade-insecure-requests in the CSP headers?

Describe the solution you'd like

A clear and concise description of what you want to happen.

A new parameter like "upgradeInsecureRequest" of type bool (default false)

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.

Documentation, Adoption, Migration Strategy

If you can, explain how users will be able to use this and how it might be documented. Maybe a mock-up?

Additional context

Add any other context or screenshots about the feature request here.


  • I've tried to find similar issues and pull requests
  • I would like to work on this feature ๐Ÿ’ช๐Ÿป

Feature/Permission policy

๐ŸŒฑ Feature Request

Is your feature request related to a problem? Please describe.

Currently the package doesn't support the Feature-Policy header, nor the Permission-Policy header.
Although the headers are still in draft stage, most browsers are already accepting them.
Moreover, sending those response headers is already a recommended best practice amongst IT corporations, and is included as part of pen testing reports.

Describe the solution you'd like

Implementing the support for those headers.

Documentation, Adoption, Migration Strategy

Same way as other headers in the package.

  • [ x ] I've tried to find similar issues and pull requests
  • [ x ] I would like to work on this feature ๐Ÿ’ช๐Ÿป

Using i18n in next.config.js will cause secure headers to disappear

๐Ÿ’ฉ Bug Report

A summary of the bug

Using i18n internationalization will cause secure headers to disappear

Current behavior

If you have this in your next.config.js:

i18n: {
  defaultLocale: "de",
  locales: ["de"]
},

Your headers will not be used.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository.

  1. add this to your next.config.js alongside your headers configuration
    i18n: { defaultLocale: "de", locales: ["de"] },
  2. npm run build & npm run start
  3. Check network tab, the CSP header wont be displayed
  4. Remove i18n, recompile & restart, CSP Headers are back there

Expected behavior

CSP Headers to work when i18n locales are set.

Environment

  • This project version(s): v2.2.0
  • Nodejs version: v14.15.4
  • OS: Windows 10

Additional context

The headers config i used:

  async headers() {
    return [{
      source: "/(.*)",
      headers: createSecureHeaders({
        contentSecurityPolicy: {
          directives: {
            defaultSrc: "'self'",
            imgSrc: ["https://*", "'self'", "data:"],
            styleSrc: ["'self'", "https://use.typekit.net/", "'unsafe-inline'"],
            fontSrc: "https://use.typekit.net/",
            scriptSrc: ["'self'", process.env.NODE_ENV === "development" ? "'unsafe-eval'" : ""],
            scriptSrcElem: "'self'"
          }
        }
      })
    }]
  }

  • I've tried to find similar issues
  • I would like to work on a fix ๐Ÿ’ช๐Ÿป

Export types for contentSecurityPolicy and directives

๐ŸŒฑ Feature Request

Is your feature request related to a problem? Please describe.

A clear and concise description of what you want and what your use case is.

Hello, I have been working on my own interpretation of this package to handle specific headers for my company and I would like to import the types for directives in contentSecurityPolicy so that I'm able to extend the interface.

Describe the solution you'd like

A clear and concise description of what you want to happen.

Adding the types to the export would be the ideal way forward. Being able to export the types means that we can extend it to make certain keys and values strict to a specific value or to only accept string[]

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.

Currently, I have been trying to access the types through this method.

import { createSecureHeaders } from 'next-secure-headers';

type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;

type SecureHeadersArguments = ArgumentTypes<typeof createSecureHeaders>[0];

export type Directives = SecureHeadersArguments['contentSecurityPolicy'];

But I'm getting a type error on the last line:

Property 'contentSecurityPolicy' does not exist on type 'Partial<{ contentSecurityPolicy: ContentSecurityPolicyOption; expectCT: ExpectCTOption; forceHTTPSRedirect: ForceHTTPSRedirectOption; ... 4 more ...; xssProtection: XSSProtectionOption; }> | undefined'.ts(2339)

Documentation, Adoption, Migration Strategy

If you can, explain how users will be able to use this and how it might be documented. Maybe a mock-up?

import { ContentSecurityPolicyOption } from "next-secure-headers";

type Directives = ContentSecurityPolicyOption['directives']
  • I've tried to find similar issues and pull requests
  • I would like to work on this feature ๐Ÿ’ช๐Ÿป

Add Content-Security-Policy Default directives as found in Helmet

๐ŸŒฑ Feature Request

Is your feature request related to a problem? Please describe.

As a solution similar to helmet, it would be beneficial for consumers to have similar defaults, so as to align with other packages features. This would provide consumers with a simple interface to match other packages leveraging helmet defaults. Otherwise, consumers need to specify these in their repositories.

You can find the defaults in helmet here

Describe the solution you'd like

Somewhere in the CSP rule, you could allow users to specify they want a set of default directives here: https://github.com/jagaapple/next-secure-headers/blob/master/src/rules/content-security-policy.ts#L226-L238

The behavior of the helmet repository is that if you tell it to include CSP without specifying any directives, it will default to the set defined in the module here

next-secure-headers can implement something similar by here:
https://github.com/jagaapple/next-secure-headers/blob/master/src/rules/content-security-policy.ts#L213-L223

When no directives are passed through, it can default to the same set of directives.

Describe alternatives you've considered

Consumers need to maintain a basic set of default directives for helmet independently when this should rest with the package.

Documentation, Adoption, Migration Strategy

If you can, explain how users will be able to use this and how it might be documented. Maybe a mock-up?

Additional context

Add any other context or screenshots about the feature request here.


  • I've tried to find similar issues and pull requests
  • I would like to work on this feature ๐Ÿ’ช๐Ÿป

Support for frame-ancestors

๐ŸŒฑ Feature Request

Is your feature request related to a problem? Please describe.

A clear and concise description of what you want and what your use case is.

I'm looking to set the CSP frame-ancestors header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors

as such:

Content-Security-Policy: frame-ancestors 'self' https://www.example.org;

Describe the solution you'd like

A clear and concise description of what you want to happen.

I would like to be able to set in the configuration a key value such as...

frameAncestors: "'self' https://www.example.org"

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.
I'm currently doing this...

    headers: async () => [
      {
        source: '/(.*)',
        headers: [
          ...createSecureHeaders(),
          {
            key: 'Content-Security-Policy',
            value: "frame-ancestors 'self' *.example.com;",
          },
        ]
      },
    ],

Documentation, Adoption, Migration Strategy

If you can, explain how users will be able to use this and how it might be documented. Maybe a mock-up?

Additional context

Add any other context or screenshots about the feature request here.


  • I've tried to find similar issues and pull requests
  • I would like to work on this feature ๐Ÿ’ช๐Ÿป

X-XSS-Protection: header should be disabled by default

๐ŸŒฑ Feature Request

Is your feature request related to a problem? Please describe.

The X-XSS-Protection header seems to be falling out of favor across similar projects, since it causes more problems than it solves.

Describe the solution you'd like

The default value for X-XSS-Protection should be changed from 1 to 0. That ensures legacy browsers disable their buggy XSS Protection filters.

Describe alternatives you've considered

An alternative would be to update the README, suggesting projects configure xssProtection: false manually. And potentially updating this chart.

Documentation, Adoption, Migration Strategy

Helmet included this change as part of a major version bump. That's probably the safest way to go?

It's easy enough to work around in the meantime. I'm mainly opening up an issue since there weren't any similar discussions here yet, and I was curious if xssProtection: false is generally recommended now.

Additional context

helmetjs/helmet#230
https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#x-xss-protection-header


  • I've tried to find similar issues and pull requests
  • I would like to work on this feature ๐Ÿ’ช๐Ÿป

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.