Skip to content

Commit

Permalink
csp: rework nonce structure
Browse files Browse the repository at this point in the history
  • Loading branch information
mimecuvalo committed Mar 4, 2023
1 parent f6b508f commit c207f6d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
1 change: 1 addition & 0 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const clientSideEmotionCache = createEmotionCache();
export interface CustomAppProps extends AppProps {
[APOLLO_STATE_PROP_NAME]: NormalizedCacheObject;
emotionCache: EmotionCache;
nonce: string;
}

const CURRENT_USER_QUERY = gql`
Expand Down
20 changes: 12 additions & 8 deletions pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,7 @@ import createEmotionServer from '@emotion/server/create-instance';
import crypto from 'crypto';
import { v4 } from 'uuid';

const generateCsp = (): [csp: string, nonce: string] => {
const hash = crypto.createHash('sha256');
hash.update(v4());
const nonce = hash.digest('base64');

const generateCsp = (nonce: string) => {
const isDevelopment = process.env.NODE_ENV === 'development';
const cspDirectives: { [key: string]: string[] } = {
'connect-src': isDevelopment
Expand Down Expand Up @@ -47,11 +43,12 @@ const generateCsp = (): [csp: string, nonce: string] => {
.map((directive) => `${directive} ${cspDirectives[directive].join(' ')}`)
.join('; ');

return [csp, nonce];
return csp;
};

export interface CustomDocumentInitialProps extends DocumentInitialProps {
emotionStyleTags: ReactNode[];
nonce: string;
}

export default class MyDocument extends Document {
Expand All @@ -64,12 +61,16 @@ export default class MyDocument extends Document {
const cache = createEmotionCache();
const { extractCriticalToChunks } = createEmotionServer(cache);

const hash = crypto.createHash('sha256');
hash.update(v4());
const nonce = hash.digest('base64');

ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) =>
function EnhanceApp(props) {
// @ts-ignore not sure how to fix this yet
return <App emotionCache={cache} {...props} />;
return <App emotionCache={cache} nonce={nonce} {...props} />;
},
});

Expand All @@ -89,12 +90,15 @@ export default class MyDocument extends Document {
return {
...initialProps,
emotionStyleTags,
nonce,
};
}

render(): JSX.Element {
const { locale } = this.props;
const [csp, nonce] = generateCsp();
// @ts-ignore not sure how to fix this yet
const { nonce } = this.props;
const csp = generateCsp(nonce);

return (
<StrictMode>
Expand Down

0 comments on commit c207f6d

Please sign in to comment.