跳转到内容
搜索文档

有条件地强制执行 Turnstile

最后更新 查看 MarkdownAgent 设置

本教程说明如何根据传入请求(例如请求头中的预共享密钥或特定 IP 地址)有条件地强制执行 Turnstile。

概述

您可能有自动化测试等设置,这些设置无法加载或运行 Turnstile 质询。本教程将展示如何在使用 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()
+        // 移除 script 标签
+        .on(
+          'script[src="https://challenges.cloudflare.com/turnstile/v0/api.js"]',
+          new RemoveHandler(),
+        )
+       // 移除隐式渲染使用的容器
+				.on(
+					'.cf-turnstile',
+					new RemoveHandler(),
+				)
+       // 移除显式渲染使用的容器
+				.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')
+  }
	// 按正常流程继续验证!
	const body = await request.formData();
  // Turnstile 会在 "cf-turnstile-response" 中注入令牌。
  const token = body.get('cf-turnstile-response');
  const ip = request.headers.get('CF-Connecting-IP');
  // ...
}

通过这些修改,Turnstile 将不会对带有 x-bypass-turnstile: VerySecretValue 请求头的请求强制执行。

演示

在项目文件夹中运行 npm run dev 后,您可以通过运行以下命令来测试更改:

curl -X POST http://localhost:8787/handler -H "x-bypass-turnstile: VerySecretValue"
此请求未强制执行 Turnstile

这篇文档对您有帮助吗?