Unverified Commit b91e570a authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Move csp examples (#13221)

Fixes #12042
parent fca88d1c
# Example app with strict CSP generating script hash
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.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-strict-csp-hash)
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npm init 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 [Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
This example was moved to [with-strict-csp](https://github.com/zeit/next.js/tree/canary/examples/with-strict-csp)
{
"name": "with-strict-csp-hash",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0"
},
"license": "ISC"
}
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 MyDocument 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>
)
}
}
export default function Home() {
return <div>Hello World</div>
}
# Strict CSP example
# Example app with strict CSP generating script hash
If you want to implement a CSP, the most effective way is to follow the [strict CSP](https://csp.withgoogle.com/docs/strict-csp.html) approach. For it to work, we need to generate a nonce on every request.
This example features how you can set up a strict CSP for your pages including Next.js' inline bootstrap script by hash.
It defines the CSP by document `meta` tag.
This example uses [Helmet](https://github.com/helmetjs/helmet) to configure the CSP and add the appropriate headers to all server responses. The nonce is generated with [uuid](https://github.com/kelektiv/node-uuid). Then we can pass the nonce to `<Head>` and `<NextScript>` in the custom `<Document>`.
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.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-strict-csp-hash)
## How to use
......@@ -11,9 +18,9 @@ This example uses [Helmet](https://github.com/helmetjs/helmet) to configure the
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npm init next-app --example with-strict-csp with-strict-csp-app
npm init next-app --example with-strict-csp-hash with-strict-csp-hash-app
# or
yarn create next-app --example with-strict-csp with-strict-csp-app
yarn create next-app --example with-strict-csp-hash with-strict-csp-hash-app
```
### Download manually
......@@ -21,8 +28,8 @@ yarn create next-app --example with-strict-csp with-strict-csp-app
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
cd with-strict-csp
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:
......
const helmet = require('helmet')
const uuidv4 = require('uuid/v4')
module.exports = function csp(app) {
// Create a nonce on every request and make it available to other middleware
app.use((req, res, next) => {
res.locals.nonce = Buffer.from(uuidv4()).toString('base64')
next()
})
const nonce = (req, res) => `'nonce-${res.locals.nonce}'`
const scriptSrc = [nonce, "'strict-dynamic'", "'unsafe-inline'", 'https:']
// In dev we allow 'unsafe-eval', so HMR doesn't trigger the CSP
if (process.env.NODE_ENV !== 'production') {
scriptSrc.push("'unsafe-eval'")
}
app.use(
helmet({
contentSecurityPolicy: {
directives: {
baseUri: ["'none'"],
objectSrc: ["'none'"],
scriptSrc,
},
},
})
)
}
{
"name": "with-strict-csp",
"name": "with-strict-csp-hash",
"version": "1.0.0",
"scripts": {
"dev": "node server.js",
"dev": "next",
"build": "next build",
"start": "NODE_ENV=production node server.js"
"start": "next start"
},
"dependencies": {
"express": "^4.14.0",
"helmet": "3.13.0",
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"uuid": "3.3.2"
}
"react-dom": "^16.7.0"
},
"license": "ISC"
}
import crypto from 'crypto'
import Document, { Head, Main, NextScript } from 'next/document'
const inlineScript = (body, nonce) => (
<script
type="text/javascript"
dangerouslySetInnerHTML={{ __html: body }}
nonce={nonce}
/>
)
const cspHashOf = (text) => {
const hash = crypto.createHash('sha256')
hash.update(text)
return `'sha256-${hash.digest('base64')}'`
}
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
const { nonce } = ctx.res.locals
return { ...initialProps, nonce }
}
render() {
const { nonce } = this.props
const csp = `default-src 'self'; script-src 'self' ${cspHashOf(
NextScript.getInlineScriptSource(this.props)
)}`
return (
<html>
<Head nonce={nonce}>
{inlineScript(`console.log('Inline script with nonce')`, nonce)}
<Head>
<meta httpEquiv="Content-Security-Policy" content={csp} />
</Head>
<body>
<Main />
<NextScript nonce={nonce} />
<NextScript />
</body>
</html>
)
......
const express = require('express')
const next = require('next')
const csp = require('./csp')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
csp(server)
server.use(handle)
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment