Turnstile は、Cloudflare のスマートな CAPTCHA 代替です。
Turnstile Pages Plugin は、Cloudflare Turnstile トークンを検証します。
npm i @cloudflare/pages-plugin-turnstileyarn add @cloudflare/pages-plugin-turnstilepnpm add @cloudflare/pages-plugin-turnstilebun add @cloudflare/pages-plugin-turnstileimport turnstilePlugin from "@cloudflare/pages-plugin-turnstile";
/**
* POST /api/submit-with-plugin
*/
export const onRequestPost = [
turnstilePlugin({
// This is the demo secret key. In prod, we recommend you store
// your secret key(s) safely.
secret: "0x4AAAAAAASh4E5cwHGsTTePnwcPbnFru6Y",
}),
// Alternatively, this is how you can use a secret key which has been stored as an environment variable
// (async (context) => {
// return turnstilePlugin({secret: context.env.SECRET_KEY})(context)
// }),
async (context) => {
// Request has been validated as coming from a human
const formData = await context.request.formData();
// Additional solve metadata data is available at context.data.turnstile
return new Response(
`Successfully verified! ${JSON.stringify(context.data.turnstile)}`,
);
},
];この Plugin は、POST 内の受信 Turnstile レスポンスを cf-turnstile-response パラメーターとして検証するルートを 1 つだけ公開します。マウントした場所で利用できます。上の例では functions/register.ts にマウントしています。その結果、/register へのリクエストを検証します。
Plugin は、次のプロパティを持つオブジェクト 1 つを引数にしてマウントします。
secret ↗ は必須で、Turnstile ダッシュボードで確認できます。
response と remoteip は任意の文字列です。response は検証する Turnstile トークンです。指定しない場合、Plugin は multipart/form-data リクエストから cf-turnstile-response の値を取り出します。remoteip はリクエスターの IP アドレスです。デフォルトはリクエストの CF-Connecting-IP ヘッダーです。
onError は任意の関数で、Pages Function の context オブジェクトを受け取り、Response の Promise を返します。デフォルトでは、人が読めるエラーの Response を返します。
context.data.turnstile は、後続の Pages Functions(onError 関数を含む)で Turnstile Siteverify のレスポンスオブジェクト として設定されます。