Skip to content

Commit

Permalink
add csp
Browse files Browse the repository at this point in the history
  • Loading branch information
austinsamsel committed Aug 24, 2021
1 parent 18825d1 commit c5aa720
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
3 changes: 3 additions & 0 deletions next-env.d.ts
@@ -1,3 +1,6 @@
/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
62 changes: 62 additions & 0 deletions pages/_document.tsx
@@ -0,0 +1,62 @@
import Document, {Html, Head, Main, NextScript} from "next/document";

const getCsp = (): [csp: string, nonce: string] => {
const nonce = "abc12345";

const isDev = process.env.NODE_ENV === "development";

const scriptSrc = [
`'self'`,
`'unsafe-inline'`,
"https:", // reserve unsafe-eval only for dev
...(isDev ? [`'unsafe-eval'`] : [`'nonce-${nonce}'`, `'strict-dynamic'`]),
];

const csp = [
`base-uri 'none';`,
`child-src 'none';`,
`connect-src 'self';`,
`default-src 'self';`,
`font-src 'self';`,
`form-action 'self';`,
`frame-src 'self';`,
`img-src 'self' data:;`,
`manifest-src 'self';`,
`media-src 'self';`,
`object-src 'none';`,
`prefetch-src 'self';`,
`script-src ${scriptSrc.join(" ")};`,
`style-src 'self' 'unsafe-inline' https:;`,
`upgrade-insecure-requests;`,
`worker-src 'self';`,
].join(" ");

return [csp, nonce];
};

class MyDocument extends Document {
static async getInitialProps(ctx: any) {
const initialProps = await Document.getInitialProps(ctx);
return {...initialProps};
}

render() {
const [csp, nonce] = getCsp();

return (
<Html>
<Head nonce={nonce}>
<meta property="csp-nonce" content={nonce} />
<meta httpEquiv="Content-Security-Policy" content={csp} />
<meta name="referrer" content="strict-origin" />
</Head>
<body>
<Main />
<NextScript nonce={nonce} />
</body>
</Html>
);
}
}

export default MyDocument;

0 comments on commit c5aa720

Please sign in to comment.