このチュートリアルでは、受信リクエスト(ヘッダー内の事前共有シークレットや特定の IP アドレスなど)に応じて、Turnstile を条件付きで適用する方法を説明します。
自動化など、Turnstile Challenge を読み込めない、または実行できない構成がある場合があります。HTMLRewriter を使い、特定の条件を満たしたときに クライアント側ウィジェット と Siteverify API を条件付きで扱う方法を示します。
既存の Turnstile デモ ↗ を変更し、既存の script とウィジェットのコンテナー要素を条件付きで削除します。
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",
},
});
},
};クライアント側要素を削除したときと同じロジックがある場合は、検証を途中で終了します。
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