import { CspOptions } from '@ioc:Adonis/Addons/Shield' ; import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' ; import helmetCsp , { ContentSecurityPolicyOptions } from 'helmet-csp' ; type ValueOf < T > = T [ keyof T ] ; import { noop } from './noop' ; /**
 * Directives to inspect for the `@nonce` keyword
 */ const nonceDirectives = [ 'defaultSrc' , 'scriptSrc' , 'styleSrc' ] ; /**
 * Reads `nonce` from the ServerResponse and returns appropriate
 * string
 */ function nonceFn ( _ , response ) { return `'nonce-${ response [ 'nonce' ] }'` ; } /**
 * Transform `@nonce` keywords for a given directive
 */ function transformNonceKeywords ( directive ) { /**
     * Transform array values. There should be only one `@nonce` keyword
     */ if ( Array . isArray ( directive ) ) { const nonceIndex = directive . indexOf ( '@nonce' ) ; if ( nonceIndex > - 1 ) { directive [ nonceIndex ] = nonceFn ; } } return directive ; } /**
 * Factory that returns a function to set the `Content-Security-Policy` header based upon
 * the user config
 */ export function cspFactory ( options ) { if ( ! options . enabled ) { return noop ; } if ( options . directives ) { /**
         * Transform directives that may contain the
         * "@nonce" directive.
         */ nonceDirectives . forEach ( ( directive ) => { if ( options . directives ! [ directive ] ) { options . directives ! [ directive ] = transformNonceKeywords ( options . directives ! [ directive ] ) ; } } ) ; } const helmetCspMiddleware = helmetCsp ( options ) ; return function csp ( { response , view } ) { /**
         * Helmet csp needs the `nonce` property on the HTTP ServerResponse
         */ response . response [ 'nonce' ] = response . nonce ; view . share ( { cspNonce : response . nonce } ) ; helmetCspMiddleware ( response . request , response . response , ( ) => { } ) ; } ; }