72 lines
2.6 KiB
JavaScript
72 lines
2.6 KiB
JavaScript
import { createErrorResponse } from '../utils';
|
|
|
|
import hCaptchaPlugin from "@cloudflare/pages-plugin-hcaptcha";
|
|
import turnstilePlugin from "@cloudflare/pages-plugin-turnstile";
|
|
|
|
export const captchaPlugins = [
|
|
async (context) => {
|
|
// ensure content-type is set to form-data
|
|
const contentType = context.request.headers.get("content-type");
|
|
if (!contentType || !contentType.includes("multipart/form-data")) {
|
|
return createErrorResponse("Invalid request", 400);
|
|
}
|
|
|
|
const formData = await context.request.clone().formData();
|
|
if (!formData.has("h-captcha-response")) return createErrorResponse("hCaptcha verification failed", 400);
|
|
if (!formData.has("g-recaptcha-response")) return createErrorResponse("reCAPTCHA verification failed", 400);
|
|
if (!formData.has("cf-turnstile-response")) return createErrorResponse("Turnstile verification failed", 400);
|
|
|
|
return context.next();
|
|
},
|
|
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);
|
|
}
|
|
}
|
|
] |