11import type { HashWithAlgorithm } from "@strict-csp/builder" ;
22import type { ExcludeList } from "../csp-trustify/types" ;
3- import type { CspDocumentInitialPropsOptions } from "./types" ;
3+ import type {
4+ CspDocumentInitialProps ,
5+ CspDocumentInitialPropsOptions ,
6+ } from "./types" ;
47import Document from "next/document" ;
58import {
69 hash ,
@@ -91,17 +94,20 @@ export const getCspInitialProps = async ({
9194 hashRawCss = [ ] ,
9295 processHtmlOptions,
9396 hashBasedByProxy = true ,
94- } : CspDocumentInitialPropsOptions ) => {
97+ } : CspDocumentInitialPropsOptions ) : Promise < CspDocumentInitialProps > => {
9598 const initialProps =
9699 passInitialProps || ( await Document . getInitialProps ( ctx ) ) ;
97100 if ( process . env . NODE_ENV !== "production" ) {
98- return initialProps ;
101+ return { ... initialProps , nonce : undefined } ;
99102 }
100103 const excludeList = [
101104 ...( ! trustifyScripts ? [ "scripts" ] : [ ] ) ,
102105 ...( ! trustifyStyles ? [ "styles" ] : [ ] ) ,
103106 ] as ExcludeList ;
104107
108+ setExcludeList ( excludeList ) ;
109+ setIsHashProxy ( hashBasedByProxy ) ;
110+
105111 const nonce = getCtxNonce ( ctx ) ;
106112
107113 trustifyInitialPropsSafeParts ( initialProps , nonce , hashRawCss , excludeList ) ;
@@ -113,24 +119,28 @@ export const getCspInitialProps = async ({
113119 excludeList
114120 ) ;
115121
116- const builder = getCtxCsp ( ctx ) ;
117-
118- if ( ! excludeList . includes ( "styles" ) ) {
119- builder . withStyleHashes ( pullStyleElem ( ) , pullStyleAttr ( ) ) ;
122+ if ( ! nonce ) {
123+ return {
124+ ...initialProps ,
125+ nonce : undefined ,
126+ } ;
120127 }
121- if ( nonce ) {
128+ // for pages with getServerSideProps/getInitialProps that injected a nonce
129+ const builder = getCtxCsp ( ctx ) ;
130+ if ( ! builder . isEmpty ( ) ) {
131+ // this will apply inline styles in dynamic page collected during SSR
132+ if ( ! excludeList . includes ( "styles" ) ) {
133+ builder . withStyleHashes ( pullStyleElem ( ) , pullStyleAttr ( ) ) ;
134+ }
135+ // this will consistently apply the nonce to all set directives in CSP that need it
122136 builder . withNonceApplied ( nonce ) ;
137+ // set updated CSP back to req/res of context
138+ setCtxCsp ( ctx , builder ) ;
123139 }
124- setCtxCsp ( ctx , builder ) ;
125- setExcludeList ( excludeList ) ;
126- setIsHashProxy ( hashBasedByProxy ) ;
127140 return {
128141 ...initialProps ,
129142 nonce,
130143 } ;
131144} ;
132145
133- type PromiseInnerType < T > = T extends Promise < infer U > ? U : never ;
134- export type CspInitialProps = PromiseInnerType <
135- ReturnType < typeof getCspInitialProps >
136- > ;
146+ export * from "./types" ;
0 commit comments