import { compose , find , head , isEmpty , map , reduce , split } from 'ramda' ; import { IOClients } from '../../../../../clients/IOClients' ; import { ParamsContext , RecorderState , ServiceContext } from '../../typings' ; const BLACKLISTED_COOKIES = new Set < string > ( [ 'checkout.vtex.com' ] ) ; const warnMessage = ( keys ) => `Removing set-cookie from response since cache-control has as public scope.
This can be a huge security risk. Please remove either the public scope or set-cookie from your response.
Cookies dropped:

  ${ keys . join ( '\n\t' ) }
` ; const findStr = ( target , set ) => find ( ( a ) => a . toLocaleLowerCase ( ) === target , set ) ; const findScopeInCacheControl = ( cacheControl ) => { const splitted = cacheControl && cacheControl . split ( /\s*,\s*/g ) ; const scopePublic = splitted && findStr ( 'public' , splitted ) ; return scopePublic ; } ; const cookieKey = ( cookie ) => compose < string , string [ ] , string > ( head , split ( '=' ) ) ( cookie ) ; const indexCookieByKeys = ( setCookie ) => map ( ( cookie ) => [ cookieKey ( cookie ) , cookie ] as [ string , string ] , setCookie ) ; interface CookieAccumulator { addedPayload : string [ ] ; droppedKeys : string [ ] ; } export async function removeSetCookie < T extends IOClients , U extends RecorderState , V extends ParamsContext > ( ctx , next ) { const { vtex : { logger } } = ctx ; await next ( ) ; const setCookie = ctx . response . headers [ 'set-cookie' ] ; if ( ! setCookie || isEmpty ( setCookie ) ) { return ; } const cacheControl = ctx . response . headers [ 'cache-control' ] ; const scope = findScopeInCacheControl ( cacheControl ) ; if ( scope === 'public' ) { const indexedCookies = indexCookieByKeys ( setCookie ) ; const cookies = reduce ( ( acc , [ key , payload ] ) => { if ( BLACKLISTED_COOKIES . has ( key ) ) { acc . droppedKeys . push ( key ) ; } else { acc . addedPayload . push ( payload ) ; } return acc ; } , { addedPayload : [ ] , droppedKeys : [ ] , } as CookieAccumulator , indexedCookies ) ; if ( cookies . droppedKeys . length > 0 ) { ctx . set ( 'set-cookie' , cookies . addedPayload ) ; console . warn ( warnMessage ( cookies . droppedKeys ) ) ; logger ! . warn ( { cookieKeys : cookies . droppedKeys , message : 'Setting cookies in a public route!' , } ) ; } } }