better-auth
Version:
The most comprehensive authentication framework for TypeScript.
33 lines (32 loc) • 1.62 kB
JavaScript
import { middlewareResponse } from "../../../utils/middleware-response.mjs";
import { CAPTCHA_VERIFY_TIMEOUT_MS } from "../constants.mjs";
import { EXTERNAL_ERROR_CODES, INTERNAL_ERROR_CODES } from "../error-codes.mjs";
import { encodeToURLParams } from "../utils.mjs";
import { betterFetch } from "@better-fetch/fetch";
//#region src/plugins/captcha/verify-handlers/google-recaptcha.ts
const isV3 = (response) => {
return "score" in response && typeof response.score === "number";
};
const googleRecaptcha = async ({ siteVerifyURL, captchaResponse, secretKey, minScore = .5, remoteIP, expectedAction, allowedHostnames }) => {
const response = await betterFetch(siteVerifyURL, {
method: "POST",
timeout: CAPTCHA_VERIFY_TIMEOUT_MS,
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encodeToURLParams({
secret: secretKey,
response: captchaResponse,
...remoteIP && { remoteip: remoteIP }
})
});
if (!response.data || response.error) throw new Error(INTERNAL_ERROR_CODES.SERVICE_UNAVAILABLE.message);
const verificationFailed = () => middlewareResponse({
message: EXTERNAL_ERROR_CODES.VERIFICATION_FAILED.message,
code: EXTERNAL_ERROR_CODES.VERIFICATION_FAILED.code,
status: 403
});
if (!response.data.success || isV3(response.data) && response.data.score < minScore) return verificationFailed();
if (expectedAction && response.data.action !== expectedAction) return verificationFailed();
if (allowedHostnames && allowedHostnames.length > 0 && !allowedHostnames.includes(response.data.hostname)) return verificationFailed();
};
//#endregion
export { googleRecaptcha };