jagaapple / next-secure-headers Goto Github PK
View Code? Open in Web Editor NEWSets secure response headers for Next.js.
License: MIT License
Sets secure response headers for Next.js.
License: MIT License
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.
This is next.config.js
const { createSecureHeaders } = require('next-secure-headers');
module.exports = {
async headers() {
return [{ source: '/(.*)', headers: createSecureHeaders() }];
},
};
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 )
.
No warnings from ESLint
v2.0.0
v12.16.0
macOS 10.15.6
Add any other context about the problem here, or a screenshot if applicable.
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.
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',
],
},
},
}),
},
];
},
Code above
Load scripts while keeping secure headers.
v2.1.0
v14.15.3
macOS 11.4
Add any other context about the problem here, or a screenshot if applicable.
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.
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'
}
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
.
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
v2.2.0
v16.3.0
Ubuntu 16.04
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-
.
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
I haven't considered any way of approaching this yet but I'll continue to try.
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.
Configured headers is not applied in some cases.
It should be applied even if an application uses Next.js built-in I18n routings.
Use "/:path*"
instead.
The spec defines directives in kebab-case, e.g. script-src
, these are currently not picked up, but appear as undefined
.
Since the camel-cased directives are sensible as well, supporting both would be nice.
Next.js supports to set any headers, but some developers don't know about it.
Readme should be written how to set unsupported headers in next-secure-headers using the standard way in Next.js.
None.
None.
This will be released in 2.3.0.
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
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.
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.
v2.0.0
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?
A clear and concise description of what you want to happen.
A new parameter like "upgradeInsecureRequest" of type bool (default false)
A clear and concise description of any alternative solutions or features you've considered.
If you can, explain how users will be able to use this and how it might be documented. Maybe a mock-up?
Add any other context or screenshots about the feature request here.
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.
Implementing the support for those headers.
Same way as other headers in the package.
I think the empty bin field should be dropped.
Hi, when using this module you get this message
Warning: You have opted-out of Automatic Static Optimization due to `getInitialProps` in `pages/_app`.
Read more: https://err.sh/next.js/opt-out-auto-static-optimization
Is it possible to use modify this module so this doesn't happen?
Using i18n internationalization will cause secure headers to disappear
If you have this in your next.config.js:
i18n: {
defaultLocale: "de",
locales: ["de"]
},
Your headers will not be used.
Steps to reproduce the behavior, please provide code snippets or a repository.
i18n: { defaultLocale: "de", locales: ["de"] },
CSP Headers to work when i18n locales are set.
v2.2.0
v14.15.4
Windows 10
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'"
}
}
})
}]
}
Using reportTo
or reportURI
leads to an undefined
entry in the generated CSP.
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.
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[]
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)
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']
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
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.
Consumers need to maintain a basic set of default directives for helmet independently when this should rest with the package.
If you can, explain how users will be able to use this and how it might be documented. Maybe a mock-up?
Add any other context or screenshots about the feature request here.
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;
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"
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;",
},
]
},
],
If you can, explain how users will be able to use this and how it might be documented. Maybe a mock-up?
Add any other context or screenshots about the feature request here.
The X-XSS-Protection header seems to be falling out of favor across similar projects, since it causes more problems than it solves.
The default value for X-XSS-Protection should be changed from 1
to 0
. That ensures legacy browsers disable their buggy XSS Protection filters.
An alternative would be to update the README, suggesting projects configure xssProtection: false
manually. And potentially updating this chart.
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.
helmetjs/helmet#230
https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#x-xss-protection-header
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.