feat: add ReCaptchaV2 & Turnstile

This commit is contained in:
Tony Yang
2025-04-16 16:35:24 +08:00
parent 9ac3339557
commit 037ccb5781
23 changed files with 372 additions and 176 deletions
+58
View File
@@ -0,0 +1,58 @@
import { createErrorResponse } from '../utils';
import hCaptchaPlugin from "@cloudflare/pages-plugin-hcaptcha";
import turnstilePlugin from "@cloudflare/pages-plugin-turnstile";
export const captchaPlugins = [
async (context) => {
try {
return hCaptchaPlugin({
secret: context.env.hcaptcha_secret_key,
sitekey: context.env.hcaptcha_site_key,
onError: (context) => {
console.error("hCaptcha error:", context.error);
return createErrorResponse("hCaptcha verification failed", 403);
}
})(context);
} catch (e) {
console.error("hCaptcha error:", e);
return createErrorResponse("hCaptcha verification failed", 400);
}
},
async (context) => {
try {
const recaptchaResponse = (await context.request.clone().formData()).get("g-recaptcha-response").toString();
const formData = new FormData();
formData.append("secret", context.env.recaptcha_secret_key);
formData.append("response", recaptchaResponse);
const response = await fetch("https://www.google.com/recaptcha/api/siteverify", {
method: "POST",
body: formData
});
const data = await response.json();
if (!data.success) {
console.error("reCAPTCHA error:", data);
return createErrorResponse("reCAPTCHA verification failed", 403);
}
} catch (e) {
console.error("reCAPTCHA error:", e);
return createErrorResponse("reCAPTCHA verification failed", 400);
}
return context.next();
},
async (context) => {
try {
return turnstilePlugin({
secret: context.env.turnstile_secret_key,
onError: (context) => {
console.error("Turnstile error:", context.error);
return createErrorResponse("Turnstile verification failed", 403);
}
})(context)
} catch (e) {
console.error("Turnstile error:", e);
return createErrorResponse("Turnstile verification failed", 400);
}
}
]