jormungandr-bite/packages/backend/src/misc/captcha.ts

74 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-01-12 21:40:33 -07:00
import fetch from "node-fetch";
import { URLSearchParams } from "node:url";
import { getAgentByUrl } from "./fetch.js";
import config from "@/config/index.js";
2021-02-05 19:46:47 -07:00
export async function verifyRecaptcha(secret: string, response: string) {
2023-01-12 21:40:33 -07:00
const result = await getCaptchaResponse(
"https://www.recaptcha.net/recaptcha/api/siteverify",
secret,
response,
).catch((e) => {
2022-08-04 03:00:02 -06:00
throw new Error(`recaptcha-request-failed: ${e.message}`);
2021-02-05 19:46:47 -07:00
});
if (result.success !== true) {
2023-01-12 21:40:33 -07:00
const errorCodes = result["error-codes"]
? result["error-codes"]?.join(", ")
: "";
2022-08-04 03:00:02 -06:00
throw new Error(`recaptcha-failed: ${errorCodes}`);
2021-02-05 19:46:47 -07:00
}
}
export async function verifyHcaptcha(secret: string, response: string) {
2023-01-12 21:40:33 -07:00
const result = await getCaptchaResponse(
"https://hcaptcha.com/siteverify",
secret,
response,
).catch((e) => {
2022-08-04 03:00:02 -06:00
throw new Error(`hcaptcha-request-failed: ${e.message}`);
2021-02-05 19:46:47 -07:00
});
if (result.success !== true) {
2023-01-12 21:40:33 -07:00
const errorCodes = result["error-codes"]
? result["error-codes"]?.join(", ")
: "";
2022-08-04 03:00:02 -06:00
throw new Error(`hcaptcha-failed: ${errorCodes}`);
2021-02-05 19:46:47 -07:00
}
}
type CaptchaResponse = {
success: boolean;
2023-01-12 21:40:33 -07:00
"error-codes"?: string[];
2021-02-05 19:46:47 -07:00
};
2023-01-12 21:40:33 -07:00
async function getCaptchaResponse(
url: string,
secret: string,
response: string,
): Promise<CaptchaResponse> {
2021-02-05 19:46:47 -07:00
const params = new URLSearchParams({
secret,
2021-12-09 07:58:30 -07:00
response,
2021-02-05 19:46:47 -07:00
});
const res = await fetch(url, {
2023-01-12 21:40:33 -07:00
method: "POST",
2021-02-05 19:46:47 -07:00
body: params,
headers: {
2023-01-12 21:40:33 -07:00
"User-Agent": config.userAgent,
2021-02-05 19:46:47 -07:00
},
2022-04-03 01:30:22 -06:00
// TODO
//timeout: 10 * 1000,
2021-12-09 07:58:30 -07:00
agent: getAgentByUrl,
2023-01-12 21:40:33 -07:00
}).catch((e) => {
2022-08-04 03:00:02 -06:00
throw new Error(`${e.message || e}`);
2021-02-05 19:46:47 -07:00
});
if (!res.ok) {
2022-08-04 03:00:02 -06:00
throw new Error(`${res.status}`);
2021-02-05 19:46:47 -07:00
}
2023-01-12 21:40:33 -07:00
return (await res.json()) as CaptchaResponse;
2021-02-05 19:46:47 -07:00
}