All files / proxy/handlers handleAgentDowloading.ts

96.29% Statements 26/27
66.66% Branches 6/9
100% Functions 8/8
96.15% Lines 25/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70    2x   2x     11x     2x 11x 11x   11x 11x 11x 11x   11x   11x             10x 10x       10x   10x   10x 10x 10x                     11x 1x 1x                 11x         11x 11x    
import { AgentOptions } from '../model'
import { CloudFrontResultResponse } from 'aws-lambda'
import https from 'https'
 
import { updateResponseHeadersForAgentDownload, addTrafficMonitoringSearchParamsForProCDN } from '../utils'
 
function copySearchParams(oldSearchString: string, newURL: URL): void {
  newURL.search = oldSearchString
}
 
export function downloadAgent(options: AgentOptions): Promise<CloudFrontResultResponse> {
  return new Promise((resolve) => {
    const data: any[] = []
 
    const url = new URL(`https://${options.fpCdnUrl}`)
    url.pathname = getEndpoint(options.apiKey, options.version, options.loaderVersion)
    copySearchParams(options.querystring, url)
    addTrafficMonitoringSearchParamsForProCDN(url)
 
    console.debug(`Downloading agent from: ${url.toString()}`)
 
    const request = https.request(
      url,
      {
        method: options.method,
        headers: options.headers,
      },
      (response) => {
        let binary = false
        Iif (response.headers['content-encoding']) {
          binary = true
        }
 
        response.setEncoding(binary ? 'binary' : 'utf8')
 
        response.on('data', (chunk) => data.push(Buffer.from(chunk, 'binary')))
 
        response.on('end', () => {
          const body = Buffer.concat(data)
          resolve({
            status: response.statusCode ? response.statusCode.toString() : '500',
            statusDescription: response.statusMessage,
            headers: updateResponseHeadersForAgentDownload(response.headers),
            bodyEncoding: 'base64',
            body: body.toString('base64'),
          })
        })
      }
    )
 
    request.on('error', (error) => {
      console.error('unable to download agent', { error })
      resolve({
        status: '500',
        statusDescription: 'Bad request',
        headers: {},
        bodyEncoding: 'text',
        body: 'error',
      })
    })
 
    request.end()
  })
}
 
function getEndpoint(apiKey: string | undefined, version: string, loaderVersion: string | undefined): string {
  const lv: string = loaderVersion !== undefined && loaderVersion !== '' ? `/loader_v${loaderVersion}.js` : ''
  return `/v${version}/${apiKey}${lv}`
}