All files / src/worker handler.ts

80% Statements 12/15
85.71% Branches 6/7
100% Functions 1/1
80% Lines 12/15

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 71 72 73 74 75 76 77 78 79 80                                                42x   42x               42x 42x   42x   2x     6x                     6x 2x     4x   4x     28x                                  
import { TypedEnv } from './types'
import { matchUrl } from './urlMatching'
import { handleScriptsInjection } from './handlers/handleScriptsInjection'
import { handleScript } from './handlers/handleScript'
import {
  getCDNHost,
  getFallbackRuleAction,
  getFpLogLevel,
  getFpRegion,
  getIngressBaseHost,
  getProtectedApis,
  getPublicKey,
  getRoutePrefix,
  getRulesetId,
  getSecretKey,
  isMonitorMode,
} from './env'
 
import { handleError } from './handlers/handleError'
import { fetchOrigin } from './utils/origin'
import { handleProtectedApiCall } from './handlers/handleProtectedApi'
import { IdentificationClient } from './fingerprint/identificationClient'
 
export async function handleRequest(request: Request, env: TypedEnv): Promise<Response> {
  console.info('Handling request', request)
 
  const identificationClient = new IdentificationClient(
    getFpRegion(env),
    getIngressBaseHost(env),
    getSecretKey(env),
    getRoutePrefix(env),
    getRulesetId(env)
  )
 
  try {
    const matchedUrl = matchUrl(new URL(request.url), request.method, env)
 
    switch (matchedUrl?.type) {
      case 'identification':
        return await handleScriptsInjection({ request, env })
 
      case 'script':
        return await handleScript({
          request,
          script: matchedUrl.script,
          publicApiKey: getPublicKey(env),
          cdnHost: getCDNHost(env),
          protectedApis: getProtectedApis(env),
          routePrefix: getRoutePrefix(env),
          logLevel: getFpLogLevel(env),
        })
 
      case 'browserCache':
        if (request.method === 'GET') {
          return identificationClient.browserCache(request)
        }
 
        console.warn(`Invalid method for browser cache request: ${request.method}. Falling back to origin.`)
 
        return fetchOrigin(request)
 
      case 'protection':
        return await handleProtectedApiCall({
          request,
          identificationClient,
          fallbackRule: getFallbackRuleAction(env),
          routePrefix: getRoutePrefix(env),
          isMonitorMode: isMonitorMode(env),
        })
 
      default:
        console.info('No matched url')
 
        return fetchOrigin(request)
    }
  } catch (error) {
    return handleError(error)
  }
}