async function getTokenFromBody()

in src/createAssessment.ts [32:80]


async function getTokenFromBody(context: RecaptchaContext, request: EdgeRequest): Promise<string | null> {
  const contentType = request.getHeader("content-type");
  // The name of a regular token is `g-recaptcha-response` in POST parameteres (viewed in Request Playload).
  if (contentType && contentType.includes("application/json")) {
    try {
      // Clone to avoid consuming the original body.
      const body = await request.getBodyJson();
      return body["g-recaptcha-response"] || null;
    } catch (error) {
      context.log("error", "Error parsing data");
      return null;
    }
  } else if (contentType && contentType.includes("application/x-www-form-urlencoded")) {
    try {
      const bodyText = await request.getBodyText();
      const formData = new URLSearchParams(bodyText);
      return formData.get("g-recaptcha-response");
    } catch (error) {
      context.log("error", "Error parsing data");
      return null;
    }
  } else if (contentType && contentType.includes("multipart/form-data")) {
    try {
      const boundary = extractBoundary(contentType);
      const bodyText = await request.getBodyText();
      const body = Buffer.from(bodyText);
      const parts = parse(body, boundary);

      for (const part of parts) {
        // Check filename directly, or a custom header if controlling the upload.
        if (part.filename === "g-recaptcha-response" || (part.type && part.type.includes("text/plain") && part.data)) {
          return part.data.toString("utf-8");
        }
      }
      return null;
    } catch (error) {
      if (error instanceof TypeError) {
        context.log("error", "Unsupported operations");
        return null;
      } else {
        context.log("error", "Error parsing data");
        return null;
      }
    }
  } else {
    context.log("error", "Unsupported Content-Type or no Content-Type header found.");
    return null;
  }
}