Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

条件付きで Turnstile を適用する

最終更新 Markdown で表示Agent セットアップ

このチュートリアルでは、受信リクエスト(ヘッダー内の事前共有シークレットや特定の IP アドレスなど)に応じて、Turnstile を条件付きで適用する方法を説明します。

概要

自動化など、Turnstile Challenge を読み込めない、または実行できない構成がある場合があります。HTMLRewriter を使い、特定の条件を満たしたときに クライアント側ウィジェットSiteverify API を条件付きで扱う方法を示します。

実装

既存の Turnstile デモ を変更し、既存の script とウィジェットのコンテナー要素を条件付きで削除します。

src/index.mjsdiff
export default {
  async fetch(request) {
    // ...

+    if (request.headers.get("x-bypass-turnstile") === "VerySecretValue") {
+      class RemoveHandler {
+        element(element) {
+          element.remove();
+        }
+      }
+
+      return new HTMLRewriter()
+        // Remove the script tag
+        .on(
+          'script[src="https://challenges.cloudflare.com/turnstile/v0/api.js"]',
+          new RemoveHandler(),
+        )
+       // Remove the container used in implicit rendering
+				.on(
+					'.cf-turnstile',
+					new RemoveHandler(),
+				)
+       // Remove the container used in explicit rendering
+				.on(
+					'#myWidget',
+					new RemoveHandler(),
+				)
+        .transform(body);
+    }

    return new Response(body, {
      headers: {
        "Content-Type": "text/html",
      },
    });
  },
};

サーバー側の統合

クライアント側要素を削除したときと同じロジックがある場合は、検証を途中で終了します。

src/index.mjsdiff
async function handlePost(request) {
+  if (request.headers.get("x-bypass-turnstile") === "VerySecretValue") {
+    return new Response('Turnstile not enforced on this request')
+  }
	// Proceed with validation as normal!
	const body = await request.formData();
  // Turnstile injects a token in "cf-turnstile-response".
  const token = body.get('cf-turnstile-response');
  const ip = request.headers.get('CF-Connecting-IP');
  // ...
}

この変更により、ヘッダー x-bypass-turnstile: VerySecretValue があるリクエストでは Turnstile を適用しません。

動作確認

プロジェクトフォルダーで npm run dev を実行したあと、次のコマンドで変更を確認できます。

curl -X POST http://localhost:8787/handler -H "x-bypass-turnstile: VerySecretValue"
Turnstile not enforced on this request

役に立ちましたか?