mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
This PR factors out the inline script into an own static method; fixes #4934.
This commit is contained in:
parent
1fe1f7fc49
commit
87f5df2454
48
examples/with-strict-csp-hash/README.md
Normal file
48
examples/with-strict-csp-hash/README.md
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-strict-csp-hash)
|
||||||
|
|
||||||
|
# Example app with strict CSP generating script hash
|
||||||
|
|
||||||
|
## How to use
|
||||||
|
|
||||||
|
### Using `create-next-app`
|
||||||
|
|
||||||
|
Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx create-next-app --example with-strict-csp-hash with-strict-csp-hash-app
|
||||||
|
# or
|
||||||
|
yarn create next-app --example with-strict-csp-hash with-strict-csp-hash-app
|
||||||
|
```
|
||||||
|
|
||||||
|
### Download manually
|
||||||
|
|
||||||
|
Download the example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-strict-csp-hash
|
||||||
|
cd with-strict-csp-hash
|
||||||
|
```
|
||||||
|
|
||||||
|
Install it and run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
# or
|
||||||
|
yarn
|
||||||
|
yarn dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
|
||||||
|
|
||||||
|
```bash
|
||||||
|
now
|
||||||
|
```
|
||||||
|
|
||||||
|
## The idea behind the example
|
||||||
|
|
||||||
|
This example features how you can set up a strict CSP for your pages whitelisting next's inline bootstrap script by hash.
|
||||||
|
In contrast to the example `with-strict-csp` based on nonces, this way doesn't require running a server to generate fresh nonce values on every document request.
|
||||||
|
It defines the CSP by document `meta` tag.
|
||||||
|
|
||||||
|
Note: There are still valid cases for using a nonce in case you need to inline scripts or styles for which calculating a hash is not feasible.
|
15
examples/with-strict-csp-hash/package.json
Normal file
15
examples/with-strict-csp-hash/package.json
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
{
|
||||||
|
"name": "with-strict-csp-hash",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"next": "latest",
|
||||||
|
"react": "^16.0.0",
|
||||||
|
"react-dom": "^16.0.0"
|
||||||
|
},
|
||||||
|
"license": "ISC"
|
||||||
|
}
|
26
examples/with-strict-csp-hash/pages/_document.js
Normal file
26
examples/with-strict-csp-hash/pages/_document.js
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
import crypto from 'crypto'
|
||||||
|
import Document, { Head, Main, NextScript } from 'next/document'
|
||||||
|
|
||||||
|
const cspHashOf = (text) => {
|
||||||
|
const hash = crypto.createHash('sha256')
|
||||||
|
hash.update(text)
|
||||||
|
return `'sha256-${hash.digest('base64')}'`
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class extends Document {
|
||||||
|
render () {
|
||||||
|
const csp = `default-src 'self'; script-src 'self' ${cspHashOf(NextScript.getInlineScriptSource(this.props))}`
|
||||||
|
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<Head>
|
||||||
|
<meta httpEquiv='Content-Security-Policy' content={csp} />
|
||||||
|
</Head>
|
||||||
|
<body>
|
||||||
|
<Main />
|
||||||
|
<NextScript />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
3
examples/with-strict-csp-hash/pages/index.js
Normal file
3
examples/with-strict-csp-hash/pages/index.js
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
export default () => (
|
||||||
|
<div>Hello World</div>
|
||||||
|
)
|
|
@ -176,6 +176,28 @@ export class NextScript extends Component {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static getInlineScriptSource (documentProps) {
|
||||||
|
const { __NEXT_DATA__ } = documentProps
|
||||||
|
const { page, pathname } = __NEXT_DATA__
|
||||||
|
|
||||||
|
return `
|
||||||
|
__NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)}
|
||||||
|
module={}
|
||||||
|
__NEXT_LOADED_PAGES__ = []
|
||||||
|
|
||||||
|
__NEXT_REGISTER_PAGE = function (route, fn) {
|
||||||
|
__NEXT_LOADED_PAGES__.push({ route: route, fn: fn })
|
||||||
|
}${page === '_error' ? `
|
||||||
|
|
||||||
|
__NEXT_REGISTER_PAGE(${htmlescape(pathname)}, function() {
|
||||||
|
var error = new Error('Page does not exist: ${htmlescape(pathname)}')
|
||||||
|
error.statusCode = 404
|
||||||
|
|
||||||
|
return { error: error }
|
||||||
|
})`: ''}
|
||||||
|
`
|
||||||
|
}
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const { staticMarkup, assetPrefix, __NEXT_DATA__ } = this.context._documentProps
|
const { staticMarkup, assetPrefix, __NEXT_DATA__ } = this.context._documentProps
|
||||||
const { page, pathname, buildId } = __NEXT_DATA__
|
const { page, pathname, buildId } = __NEXT_DATA__
|
||||||
|
@ -183,22 +205,7 @@ export class NextScript extends Component {
|
||||||
|
|
||||||
return <Fragment>
|
return <Fragment>
|
||||||
{staticMarkup ? null : <script nonce={this.props.nonce} dangerouslySetInnerHTML={{
|
{staticMarkup ? null : <script nonce={this.props.nonce} dangerouslySetInnerHTML={{
|
||||||
__html: `
|
__html: NextScript.getInlineScriptSource(this.context._documentProps)
|
||||||
__NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)}
|
|
||||||
module={}
|
|
||||||
__NEXT_LOADED_PAGES__ = []
|
|
||||||
|
|
||||||
__NEXT_REGISTER_PAGE = function (route, fn) {
|
|
||||||
__NEXT_LOADED_PAGES__.push({ route: route, fn: fn })
|
|
||||||
}${page === '_error' ? `
|
|
||||||
|
|
||||||
__NEXT_REGISTER_PAGE(${htmlescape(pathname)}, function() {
|
|
||||||
var error = new Error('Page does not exist: ${htmlescape(pathname)}')
|
|
||||||
error.statusCode = 404
|
|
||||||
|
|
||||||
return { error: error }
|
|
||||||
})`: ''}
|
|
||||||
`
|
|
||||||
}} />}
|
}} />}
|
||||||
{page !== '/_error' && <script async id={`__NEXT_PAGE__${pathname}`} src={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}`} nonce={this.props.nonce} />}
|
{page !== '/_error' && <script async id={`__NEXT_PAGE__${pathname}`} src={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}`} nonce={this.props.nonce} />}
|
||||||
<script async id={`__NEXT_PAGE__/_app`} src={`${assetPrefix}/_next/static/${buildId}/pages/_app.js`} nonce={this.props.nonce} />
|
<script async id={`__NEXT_PAGE__/_app`} src={`${assetPrefix}/_next/static/${buildId}/pages/_app.js`} nonce={this.props.nonce} />
|
||||||
|
|
|
@ -1,5 +1,12 @@
|
||||||
|
import crypto from 'crypto'
|
||||||
import Document, { Head, Main, NextScript } from 'next/document'
|
import Document, { Head, Main, NextScript } from 'next/document'
|
||||||
|
|
||||||
|
const cspHashOf = (text) => {
|
||||||
|
const hash = crypto.createHash('sha256')
|
||||||
|
hash.update(text)
|
||||||
|
return `'sha256-${hash.digest('base64')}'`
|
||||||
|
}
|
||||||
|
|
||||||
export default class MyDocument extends Document {
|
export default class MyDocument extends Document {
|
||||||
static async getInitialProps (ctx) {
|
static async getInitialProps (ctx) {
|
||||||
let options
|
let options
|
||||||
|
@ -21,13 +28,24 @@ export default class MyDocument extends Document {
|
||||||
|
|
||||||
const result = ctx.renderPage(options)
|
const result = ctx.renderPage(options)
|
||||||
|
|
||||||
return { ...result, customProperty: 'Hello Document' }
|
return { ...result, customProperty: 'Hello Document', withCSP: ctx.query.withCSP }
|
||||||
}
|
}
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
|
let csp
|
||||||
|
switch (this.props.withCSP) {
|
||||||
|
case 'hash':
|
||||||
|
csp = `default-src 'self'; script-src 'self' ${cspHashOf(NextScript.getInlineScriptSource(this.props))}; style-src 'self' 'unsafe-inline'`
|
||||||
|
break
|
||||||
|
case 'nonce':
|
||||||
|
csp = `default-src 'self'; script-src 'self' 'nonce-test-nonce'; style-src 'self' 'unsafe-inline'`
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html>
|
<html>
|
||||||
<Head nonce='test-nonce'>
|
<Head nonce='test-nonce'>
|
||||||
|
{csp ? <meta httpEquiv='Content-Security-Policy' content={csp} /> : null}
|
||||||
<style>{`body { margin: 0 } /* custom! */`}</style>
|
<style>{`body { margin: 0 } /* custom! */`}</style>
|
||||||
</Head>
|
</Head>
|
||||||
<body className='custom_class'>
|
<body className='custom_class'>
|
||||||
|
|
21
test/integration/app-document/test/csp.js
Normal file
21
test/integration/app-document/test/csp.js
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
/* global describe, it, expect */
|
||||||
|
|
||||||
|
import webdriver from 'next-webdriver'
|
||||||
|
|
||||||
|
export default (context, render) => {
|
||||||
|
describe('With CSP enabled', () => {
|
||||||
|
it('should load inline script by hash', async () => {
|
||||||
|
const browser = await webdriver(context.appPort, '/?withCSP=hash')
|
||||||
|
const errLog = await browser.log('browser')
|
||||||
|
expect(errLog.filter((e) => e.source === 'security')).toEqual([])
|
||||||
|
browser.close()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should load inline script by nonce', async () => {
|
||||||
|
const browser = await webdriver(context.appPort, '/?withCSP=nonce')
|
||||||
|
const errLog = await browser.log('browser')
|
||||||
|
expect(errLog.filter((e) => e.source === 'security')).toEqual([])
|
||||||
|
browser.close()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
|
@ -12,6 +12,7 @@ import {
|
||||||
// test suits
|
// test suits
|
||||||
import rendering from './rendering'
|
import rendering from './rendering'
|
||||||
import client from './client'
|
import client from './client'
|
||||||
|
import csp from './csp'
|
||||||
|
|
||||||
const context = {}
|
const context = {}
|
||||||
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
|
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
|
||||||
|
@ -30,4 +31,5 @@ describe('Document and App', () => {
|
||||||
|
|
||||||
rendering(context, 'Rendering via HTTP', (p, q) => renderViaHTTP(context.appPort, p, q), (p, q) => fetchViaHTTP(context.appPort, p, q))
|
rendering(context, 'Rendering via HTTP', (p, q) => renderViaHTTP(context.appPort, p, q), (p, q) => fetchViaHTTP(context.appPort, p, q))
|
||||||
client(context, (p, q) => renderViaHTTP(context.appPort, p, q))
|
client(context, (p, q) => renderViaHTTP(context.appPort, p, q))
|
||||||
|
csp(context, (p, q) => renderViaHTTP(context.appPort, p, q))
|
||||||
})
|
})
|
||||||
|
|
Loading…
Reference in a new issue