All files / src recaptcha.ts

100% Statements 46/46
95% Branches 19/20
100% Functions 2/2
100% Lines 46/46

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        1x       1x   8x 8x 8x 8x   8x 2x 2x     6x 1x 1x     5x   5x 1x 1x     4x     8x   8x 8x 3x   1x 1x                                 10x 10x   2x 2x     8x 8x 8x 8x   8x               7x                 7x                               7x 2x 2x     5x 1x     1x     4x 1x     1x     3x     1x                 1x      
import type { HttpFunction } from "@google-cloud/functions-framework";
import fetch from "node-fetch";
 
// アクションごとの閾値定義(一元管理)
export const RECAPTCHA_THRESHOLDS: Record<string, number> = {
  AUTHENTICATE: 0.3,
};
 
export const recaptchaVerifier: HttpFunction = async (req, res) => {
  // CORS configuration
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Methods", "POST, OPTIONS");
  res.set("Access-Control-Allow-Headers", "Content-Type");
  res.set("Access-Control-Max-Age", "3600");
 
  if (req.method === "OPTIONS") {
    res.status(204).send("");
    return;
  }
 
  if (req.method !== "POST") {
    res.status(405).send("Method Not Allowed");
    return;
  }
 
  const { token, action } = req.body;
 
  if (!token) {
    res.status(400).json({ success: false, error: "reCAPTCHA token missing" });
    return;
  }
 
  const requestedAction = typeof action === "string" ? action : "";
 
  // アクションに基づく閾値の決定(デフォルトは0.3)
  const threshold = RECAPTCHA_THRESHOLDS[requestedAction] || 0.3;
 
  try {
    const isValid = await verifyRecaptcha(token, requestedAction, threshold);
    res.status(200).json({ success: isValid });
  } catch (error) {
    console.error("Error in recaptchaVerifier:", error);
    res.status(500).json({ success: false, error: "Verification failed" });
  }
};
 
/**
 * reCAPTCHA v3 トークンを検証するユーティリティ関数
 *
 * @param token 検証するトークン
 * @param action 期待されるアクション名
 * @param threshold 許容するスコアの閾値
 * @returns 検証結果(成功: true, 失敗: false)
 */
export async function verifyRecaptcha(
  token: string,
  action: string,
  threshold: number,
): Promise<boolean> {
  const secret = process.env.RECAPTCHA_V3_SECRET_KEY;
  if (!secret) {
    // 仕様変更: 設定漏れは致命的なのでErrorをスロー (Fail Closed)
    console.error("RECAPTCHA_V3_SECRET_KEY is not set.");
    throw new Error("RECAPTCHA_V3_SECRET_KEY is not set.");
  }
 
  try {
    const params = new URLSearchParams();
    params.append("secret", secret);
    params.append("response", token);
 
    const response = await fetch(
      "https://www.google.com/recaptcha/api/siteverify",
      {
        method: "POST",
        body: params,
      },
    );
 
    const data = (await response.json()) as {
      success: boolean;
      score: number;
      action: string;
      hostname: string;
      "error-codes"?: string[];
    };
 
    // 構造化ログの出力
    console.log(
      JSON.stringify({
        severity: "INFO",
        component: "recaptcha",
        token_verification: {
          success: data.success,
          score: data.score,
          action: data.action,
          hostname: data.hostname,
          expected_action: action,
          threshold: threshold,
          error_codes: data["error-codes"],
        },
      }),
    );
 
    if (!data.success) {
      console.warn("reCAPTCHA verification failed:", data["error-codes"]);
      return false;
    }
 
    if (data.action !== action) {
      console.warn(
        `reCAPTCHA action mismatch: expected '${action}', got '${data.action}'`,
      );
      return false;
    }
 
    if (data.score < threshold) {
      console.warn(
        `reCAPTCHA score too low: ${data.score} < ${threshold} (action: ${action})`,
      );
      return false;
    }
 
    return true;
  } catch (error) {
    // 仕様変更: Google APIエラー時はログを出して通す (Fail Open)
    console.error(
      JSON.stringify({
        severity: "ERROR",
        component: "recaptcha",
        result: "error_skipped", // 指示通りの識別子
        message: "Error during reCAPTCHA verification, allowing request.",
        error: error instanceof Error ? error.message : String(error),
      }),
    );
    return true;
  }
}