All files / src/worker/fingerprint identificationClient.ts

100% Statements 78/78
87.5% Branches 21/24
100% Functions 5/5
100% Lines 78/78

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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309                                                                    4x                 4x                                                                                   42x 42x 42x   42x 42x 42x                                   22x 20x 18x 16x   16x 16x 16x   16x 16x     16x   5x 5x 5x 5x       16x               16x 5x     16x 16x 16x     16x 16x   16x           16x   16x 16x       16x 3x 3x 3x     13x 13x 3x   3x           10x 10x   10x   10x                           2x     2x 2x 2x   2x 2x   2x 2x     2x                                   42x   41x     1x                               28x 28x 19x 19x   19x 19x                     9x   9x 5x 3x   3x 3x   3x   3x 3x     1x   1x     3x                         2x     6x      
import { Region } from './region'
import { SIGNALS_KEY } from '../../shared/const'
import { IdentificationRequestFailedError, SignalsNotAvailableError } from '../errors'
import { getHeaderOrThrow, getIp, hasContentType } from '../utils/headers'
import { findCookie } from '../cookies'
import { RuleAction } from './ruleset'
import { copyRequest } from '../utils/request'
import { z } from 'zod/v4'
import { handleTampering } from './tampering'
 
type RulesetContext = {
  ruleset_id: string
}
/**
 * Request body structure for sending fingerprint data to the identification service.
 *
 */
export type SendBody = {
  /** Fingerprint data with signals */
  fingerprint_data: string
  /** Client's host header value */
  client_host: string
  /** Client's IP address from Cloudflare headers */
  client_ip: string
  /** Client's user agent string */
  client_user_agent: string
  /** Optional client cookie data (filtered to include only _iidt cookie) */
  client_cookie?: string
  /** Optional additional client headers (excluding cookies) */
  client_headers?: Record<string, string>
  /** Ruleset context for rule action evaluation */
  ruleset_context?: RulesetContext
}
 
export const IdentificationEvent = z.object({
  replayed: z.boolean(),
  timestamp: z.coerce.date(),
  url: z.url(),
  ip_address: z.ipv4().or(z.ipv6()),
})
 
export type IdentificationEvent = z.infer<typeof IdentificationEvent>
 
export const SendResponse = z.object({
  // Agent data returned by the identification service
  agent_data: z.string(),
  // Rule action resolved by the identification service
  rule_action: RuleAction.optional(),
  // Cookies that need to be set in the origin response
  set_cookie_headers: z.array(z.string()).optional(),
 
  event: IdentificationEvent,
})
 
export type SendResponse = z.infer<typeof SendResponse>
/**
 * Extended response structure that includes both agent data and cookie headers.
 */
export type SendResult = {
  /** Agent data returned by the identification service */
  agentData: string
  /** Array of Set-Cookie header values to be sent to the client */
  setCookieHeaders?: string[] | undefined
  /** Optional rule action that was resolved by ingress */
  ruleAction: RuleAction | undefined
}
 
/**
 * Client for communicating with the identification service.
 * Handles region-based URL resolution, request formatting, and response processing.
 */
export class IdentificationClient {
  private readonly url: URL
 
  /**
   * Creates a new IdentificationClient instance.
   * @param region - The region for URL resolution (e.g., 'us', 'eu')
   * @param baseUrl - Base URL hostname for the identification service, e.g. "api.fpjs.io"
   * @param apiKey - API key for authentication with the identification service
   * @param routePrefix - Path prefix for worker requests.
   * @param rulesetId - If of ruleset that will be evaluated by the identification service.
   */
  constructor(
    region: Region,
    baseUrl: string,
    private readonly apiKey: string,
    private readonly routePrefix: string,
    private readonly rulesetId?: string
  ) {
    const resolvedUrl = IdentificationClient.resolveUrl(region, baseUrl)
    console.debug('Resolved identification URL:', resolvedUrl)
    this.url = new URL(resolvedUrl)
  }
 
  /**
   * Sends fingerprint data to the identification service and returns the response with agent data.
   *
   * This method:
   * 1. Processes cookies to extract only the _iidt cookie if present
   * 2. Sends the data to the POST /send
   * 3. Returns the agent data along with any Set-Cookie headers received from the identification
   *
   * @param clientRequest - The incoming client request containing fingerprint data and headers
   * @param signals - Fingerprint signals extracted from the request
   * @returns Promise resolving to SendResult containing agent data and cookie headers
   * @throws {SignalsNotAvailableError} When fingerprint signals are missing from the request
   * @throws {IdentificationRequestFailedError} When the identification service request fails or returns invalid data
   */
  async send(clientRequest: Request, signals: string): Promise<SendResult> {
    const clientIP = await getIp(clientRequest.headers)
    const clientHost = getHeaderOrThrow(clientRequest.headers, 'host')
    const clientUserAgent = getHeaderOrThrow(clientRequest.headers, 'user-agent')
    const clientCookie = clientRequest.headers.get('cookie')
 
    const headers = new Headers()
    headers.set('Content-Type', 'application/json')
    headers.set('Authorization', `Bearer ${this.apiKey}`)
 
    const clientHeaders = new Headers(clientRequest.headers)
    clientHeaders.delete('cookie')
 
    let cookieToSend: string | undefined
    if (clientCookie) {
      // Try to find _iidt cookie
      const iidtMatch = findCookie(clientCookie, '_iidt')
      Eif (iidtMatch) {
        console.debug('Found _iidt cookie', iidtMatch)
        cookieToSend = iidtMatch
      }
    }
 
    const sendBody: SendBody = {
      client_ip: clientIP,
      client_host: clientHost,
      client_user_agent: clientUserAgent,
      fingerprint_data: signals,
      ...(this.rulesetId ? { ruleset_context: { ruleset_id: this.rulesetId } } : {}),
    }
 
    if (cookieToSend) {
      sendBody.client_cookie = cookieToSend
    }
 
    const clientHeadersEntries = Array.from(clientHeaders.entries())
    Eif (clientHeadersEntries.length) {
      sendBody.client_headers = Object.fromEntries(clientHeadersEntries)
    }
 
    const requestUrl = new URL(this.url)
    requestUrl.pathname = '/v4/send'
 
    const identificationRequest = new Request(requestUrl, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(sendBody),
    })
 
    console.debug(`Sending identification request to ${requestUrl}`, identificationRequest)
 
    const identificationResponse = await fetch(identificationRequest)
    console.debug(
      `Received identification response for ${requestUrl} request with status:`,
      identificationResponse.status
    )
    if (!identificationResponse.ok) {
      const errorText = await identificationResponse.text()
      console.error(`Identification request failed with status: ${identificationResponse.status}`, errorText)
      throw new IdentificationRequestFailedError(errorText, identificationResponse.status)
    }
 
    const identificationDataValidation = SendResponse.safeParse(await identificationResponse.json())
    if (!identificationDataValidation.success) {
      console.error(`Identification response data is invalid:`, identificationDataValidation.error)
 
      throw new IdentificationRequestFailedError(
        `Identification response data is invalid: ${identificationDataValidation.error.message}`,
        identificationResponse.status
      )
    }
 
    const identificationData = identificationDataValidation.data
    console.debug(`Identification response data:`, identificationData)
 
    await handleTampering(identificationData.event, clientRequest)
 
    return {
      setCookieHeaders: identificationData.set_cookie_headers,
      agentData: identificationData.agent_data,
      ruleAction: identificationData.rule_action,
    }
  }
 
  /**
   * Handles the browser cache request by modifying the client request and forwarding it to the configured ingress URL.
   *
   * @param {Request} clientRequest - The original request from the client.
   * @return {Promise<Response>} - A promise that resolves to the response from the forwarded request.
   */
  async browserCache(clientRequest: Request): Promise<Response> {
    const clientRequestUrl = new URL(clientRequest.url)
 
    // Remove the route prefix from the path
    const path = clientRequestUrl.pathname.replace(`/${this.routePrefix}`, '')
    const ingressUrl = new URL(path, this.url)
    ingressUrl.search = clientRequestUrl.search
 
    const headers = new Headers(clientRequest.headers)
    headers.delete('cookie')
 
    const request = copyRequest({ request: clientRequest, init: { headers }, url: ingressUrl })
    console.debug(`Sending browser cache request to ${ingressUrl}`, request)
 
    // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
    return fetch(request as unknown as Request<unknown, IncomingRequestCfProperties>)
  }
 
  /**
   * Resolves the full identification service URL based on the region and host.
   *
   * For the 'us' region, uses the host directly without a regional prefix.
   * For all other regions, prefixes the host with the region name.
   *
   * @param region - The target region (e.g., 'us', 'eu', 'ap')
   * @param host - The base host name for the identification service
   * @returns The complete HTTPS URL for the identification service
   *
   * @example
   * resolveUrl('us', 'api.example.com') // returns 'https://api.example.com'
   * resolveUrl('eu', 'api.example.com') // returns 'https://eu.api.example.com'
   */
  private static resolveUrl(region: Region, host: string) {
    switch (region) {
      case 'us':
        return `https://${host}`
 
      default:
        return `https://${region}.${host}`
    }
  }
 
  /**
   * Parses an incoming request to extract signals, while returning a modified iteration of the request with signals removed.
   *
   * @param {Request} request The incoming HTTP request to be processed.
   * @return {Promise<{signals: string, request: Request}>} A promise that resolves with a object containing the extracted signals and a new request object with the signals removed.
   * @throws {SignalsNotAvailableError} If signals are not found in the request headers or body.
   */
  static async parseIncomingRequest(request: Request): Promise<{
    signals: string
    request: Request
  }> {
    // First, try to find signals in headers
    const signals = request.headers.get(SIGNALS_KEY)
    if (signals) {
      const requestHeaders = new Headers(request.headers)
      requestHeaders.delete(SIGNALS_KEY)
 
      console.debug('Found signals in headers:', signals)
      return {
        signals,
        request: copyRequest({
          request,
          init: {
            headers: requestHeaders,
          },
        }),
      }
    }
 
    try {
      // Otherwise, try to find signals in the request body
      if (hasContentType(request.headers, 'application/x-www-form-urlencoded', 'multipart/form-data')) {
        const data = await request.clone().formData()
        const signals = data.get(SIGNALS_KEY)
 
        Eif (typeof signals === 'string') {
          console.debug('Found signals in request body:', signals)
 
          data.delete(SIGNALS_KEY)
 
          const requestHeaders = new Headers(request.headers)
          if (hasContentType(request.headers, 'multipart/form-data')) {
            // When modifying FormData for multipart/form-data, we also need to remove the old Content-Type header. Otherwise, the boundary will be different and the request will fail.
            // The new content type will be set automatically when constructing the new request.
            requestHeaders.delete('content-type')
 
            console.debug('Removed content-type header from request')
          }
 
          return {
            signals,
            request: copyRequest({
              request,
              init: {
                body: data,
                headers: requestHeaders,
              },
            }),
          }
        }
      }
    } catch (error) {
      console.error('Error parsing incoming request:', error)
    }
 
    throw new SignalsNotAvailableError()
  }
}