summary refs log tree commit diff
path: root/src/api/util/utility/captcha.ts
blob: 50e2c91a61997e6961646d9053c5d7efcacde406 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { Config } from "@fosscord/util";
import fetch from "node-fetch";

export interface hcaptchaResponse {
	success: boolean;
	challenge_ts: string;
	hostname: string;
	credit: boolean;
	"error-codes": string[];
	score: number; // enterprise only
	score_reason: string[]; // enterprise only
}

export interface recaptchaResponse {
	success: boolean;
	score: number; // between 0 - 1
	action: string;
	challenge_ts: string;
	hostname: string;
	"error-codes"?: string[];
}

const verifyEndpoints = {
	hcaptcha: "https://hcaptcha.com/siteverify",
	recaptcha: "https://www.google.com/recaptcha/api/siteverify",
};

export async function verifyCaptcha(response: string, ip?: string) {
	const { security } = Config.get();
	const { service, secret, sitekey } = security.captcha;

	if (!service) throw new Error("Cannot verify captcha without service");

	const res = await fetch(verifyEndpoints[service], {
		method: "POST",
		headers: {
			"Content-Type": "application/x-www-form-urlencoded",
		},
		body:
			`response=${encodeURIComponent(response)}` +
			`&secret=${encodeURIComponent(secret!)}` +
			`&sitekey=${encodeURIComponent(sitekey!)}` +
			(ip ? `&remoteip=${encodeURIComponent(ip!)}` : ""),
	});

	return (await res.json()) as hcaptchaResponse | recaptchaResponse;
}