All files / src/handlers handleStatusPage.ts

71.13% Statements 69/97
47.61% Branches 20/42
76.92% Functions 10/13
71.13% Lines 69/97

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 310 311 312                                                2x 2x 2x 2x 48x   2x       2x 2x 2x       2x       2x 2x 2x 2x                 2x 2x   2x       2x 2x       2x 2x 2x 2x 2x 2x   2x 2x   2x 2x   2x       2x     2x                                                                     2x               12x   12x 12x             12x                                           2x 2x                                         2x 2x   2x 2x 6x   2x   2x       2x                                                 2x 2x   2x 2x 6x     2x           2x   2x       2x                                                                           2x   2x 2x 2x 2x   2x         2x       3x 1x     2x 2x 2x   2x            
import {
  IntegrationEnv,
  isScriptDownloadPathSet,
  isGetResultPathSet,
  isProxySecretSet,
  agentScriptDownloadPathVarName,
  getResultPathVarName,
  proxySecretVarName,
  isOpenClientResponseSet,
  openClientResponseVarName,
  decryptionKeyVarName,
  isOpenClientResponseEnabled,
  isDecryptionKeySet,
  saveToKvStorePluginEnabledVarName,
  isSaveToKvStorePluginEnabled,
  isSaveToKvStorePluginEnabledSet,
  getDecryptionKey,
} from '../env'
import packageJson from '../../package.json'
import { env } from 'fastly:env'
import { getBuiltinKVStore, getNamesForStores } from '../utils/getStore'
import { Backend } from 'fastly:backend'
 
function generateNonce() {
  let result = ''
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const indices = crypto.getRandomValues(new Uint8Array(24))
  for (const index of indices) {
    result += characters[index % characters.length]
  }
  return btoa(result)
}
 
function buildHeaders(styleNonce: string): Headers {
  const headers = new Headers()
  headers.append('Content-Type', 'text/html')
  headers.append(
    'Content-Security-Policy',
    `default-src 'none'; img-src https://fingerprint.com; style-src 'nonce-${styleNonce}'`
  )
  return headers
}
 
function createVersionElement(): string {
  const fastlyServiceVersion = env('FASTLY_SERVICE_VERSION')
  let result = ''
  result += '<ul>'
  result += `
    <li>
    ℹ️ Integration version: <strong>${packageJson.version}</strong>
    </li>
    <li>
    ℹ️ Fastly Compute Service version: <strong>${fastlyServiceVersion}</strong>
    </li>
  `
 
  result += getBackendsInformation()
  result += '</ul>'
 
  return result
}
 
function getBackendsInformation(): string {
  let information = ''
  Iif (!Backend.exists('fpcdn.io')) {
    information += '<li>⚠️ Your integration is missing "fpcdn.io" backend host.</li>'
  }
 
  const usResultBackend = Backend.exists('api.fpjs.io')
  const euResultBackend = Backend.exists('eu.api.fpjs.io')
  const apResultBackend = Backend.exists('ap.api.fpjs.io')
  const supportedRegions = []
  Eif (usResultBackend) {
    supportedRegions.push('US')
  }
  Eif (euResultBackend) {
    supportedRegions.push('EU')
  }
  Eif (apResultBackend) {
    supportedRegions.push('AP')
  }
  Iif (supportedRegions.length === 0) {
    information +=
      '<li>⚠️ Your integration is missing backend hosts for <a href="https://dev.fingerprint.com/docs/regions">region support</a>. Please add at least one of the backends "api.fpjs.io", "eu.api.fpjs.io", or "ap.api.fpjs.io"</li>'
  } else {
    information += `<li>ℹ️ Integration is configured for these <a href="https://dev.fingerprint.com/docs/regions">regions</a>: <strong>${supportedRegions.join(', ')}</strong></li>`
  }
 
  return information
}
 
function isValidBase64(str: string | null | undefined): boolean {
  // Check if the string matches the base64 pattern
  const base64Pattern = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/
 
  if (!str) {
    return false
  }
 
  // Validate the string length (should be a multiple of 4)
  if (str.length % 4 !== 0) {
    return false
  }
 
  // Test against the Base64 pattern
  return base64Pattern.test(str)
}
 
async function checkKVStoreAvailability() {
  try {
    const kvStore = getBuiltinKVStore()
    const testKeyName = 'kvStoreCheck'
    await kvStore.put(testKeyName, 'true')
    const entry = await kvStore.get(testKeyName)
    const value = await entry?.text()
    await kvStore.delete(testKeyName)
    return value === 'true'
  } catch (_) {
    return false
  }
}
 
function createContactInformationElement(): string {
  return `
  <p>
  ❓Please <a href="https://fingerprint.com/support">reach out to our support team</a> if you have any issues.
  </p>
  `
}
 
function buildConfigurationMessage(config: ConfigurationStatus, env: IntegrationEnv): string {
  const { isSet, label, required, value, showValue } = config
 
  let message = isSet ? '' : config.message
  Iif (label === decryptionKeyVarName && isSet) {
    const isDecryptionKeyAValidBase64 = isValidBase64(getDecryptionKey(env))
    if (!isDecryptionKeyAValidBase64) {
      message += `Invalid value provided ⚠️. Please copy and paste the correct value from the dashboard.`
    }
  }
 
  return `<li><code>${label}</code> (${required ? 'Required' : 'Optional'}) is ${isSet ? `${showValue ? `<code>${value}</code>` : 'set'} ✅` : `${required ? 'missing ❌' : 'not set ⚠️'}`}. ${message ?? ''}</li>`
}
 
async function buildKVStoreCheckMessage(): Promise<string> {
  const isKVStoreAvailable = await checkKVStoreAvailability()
  if (isKVStoreAvailable) {
    return ''
  }
 
  const { kvStoreName } = getNamesForStores()
  return `⚠️You have <code>${saveToKvStorePluginEnabledVarName}</code> enabled, but we couldn't reach your KVStore named <code>${kvStoreName}</code>. <code>${saveToKvStorePluginEnabledVarName}</code> related plugin is not working correctly.`
}
 
type ConfigurationStatus = {
  label: string
  isSet: boolean
  required: boolean
  message?: string
  value?: string | null
  showValue?: boolean
}
function createEnvVarsInformationElement(env: IntegrationEnv): string {
  const incorrectConfigurationMessage = 'Your integration is not working correctly.'
  const configurations: ConfigurationStatus[] = [
    {
      label: agentScriptDownloadPathVarName,
      isSet: isScriptDownloadPathSet(env),
      required: true,
      message: incorrectConfigurationMessage,
    },
    {
      label: getResultPathVarName,
      isSet: isGetResultPathSet(env),
      required: true,
      message: incorrectConfigurationMessage,
    },
    {
      label: proxySecretVarName,
      isSet: isProxySecretSet(env),
      required: true,
      message: incorrectConfigurationMessage,
    },
  ]
 
  let result = ''
  result += '<p>🛠️ Your integration’s configuration values:</p>'
 
  result += '<ul>'
  for (const config of configurations) {
    result += buildConfigurationMessage(config, env)
  }
  result += '</ul>'
 
  return result
}
 
async function createOpenClientResponseInformationElement(env: IntegrationEnv): Promise<string> {
  const configurations: ConfigurationStatus[] = [
    {
      label: openClientResponseVarName,
      isSet: isOpenClientResponseSet(env),
      required: false,
      value: env.OPEN_CLIENT_RESPONSE_PLUGINS_ENABLED,
      showValue: true,
      message: 'Open client response plugins are disabled.',
    },
    {
      label: decryptionKeyVarName,
      isSet: isDecryptionKeySet(env),
      required: false,
      message:
        'Open client response plugins are not working correctly. This is required if you want to use Open client response plugins.',
    },
    {
      label: saveToKvStorePluginEnabledVarName,
      isSet: isSaveToKvStorePluginEnabledSet(env),
      required: false,
      value: env.SAVE_TO_KV_STORE_PLUGIN_ENABLED,
      showValue: true,
    },
  ]
 
  let result = ''
  result += `<p style="display: block">🔌 Open client response configuration values:<br>(Optional, only relevant if you are using <a href="https://dev.fingerprint.com/docs/using-open-client-response-with-fastly-compute-proxy-integration-plugins">Open client response plugins</a>)</p>`
 
  result += '<ul>'
  for (const config of configurations) {
    result += buildConfigurationMessage(config, env)
  }
 
  Iif (isOpenClientResponseEnabled(env) && isSaveToKvStorePluginEnabled(env)) {
    const errorMessage = await buildKVStoreCheckMessage()
    if (errorMessage) {
      result += `<li>${errorMessage}</li>`
    }
  }
  result += '</ul>'
 
  return result
}
 
async function buildBody(env: IntegrationEnv, styleNonce: string): Promise<string> {
  let body = `
  <html lang='en-US'>
  <head>
    <meta charset='utf-8'/>
    <title>Fingerprint Pro Fastly Compute Integration</title>
    <link rel='icon' type='image/x-icon' href='https://fingerprint.com/img/favicon.ico'>
    <style nonce='${styleNonce}'>
      body {
        display: flex;
        flex-direction: column;
        align-items: center;     
      }
      div {
        width: 60%;
        max-width: 800px;
      }
      h1 {
        display: block;
        padding-top: 1em;
        padding-bottom: 1em;
      }
      p {
        padding-top: 1em;
      }
      code {
        background:rgba(135,131,120,.15);
        color:#EB5757;
        border-radius:4px;
        font-size:85%;
        padding:0.2em 0.4em
      }
    </style>
  </head>
  <body>
  <div>
    <h1>Fingerprint Pro Fastly Compute Integration</h1>
  `
 
  body += `<p>🎉 Your Fastly Integration is deployed!</p>`
 
  body += createVersionElement()
  body += createEnvVarsInformationElement(env)
  body += createContactInformationElement()
  body += await createOpenClientResponseInformationElement(env)
 
  body += `
  </div>  
  </body>
  </html>
  `
  return body
}
 
export async function handleStatusPage(request: Request, env: IntegrationEnv): Promise<Response> {
  if (request.method !== 'GET') {
    return new Response(null, { status: 405 })
  }
 
  const styleNonce = generateNonce()
  const headers = buildHeaders(styleNonce)
  const body = await buildBody(env, styleNonce)
 
  return new Response(body, {
    status: 200,
    statusText: 'OK',
    headers,
  })
}