hippofish/packages/backend/src/core/CaptchaService.ts

88 lines
2.6 KiB
TypeScript
Raw Normal View History

import { Injectable } from '@nestjs/common';
2022-12-04 02:16:03 +01:00
import { HttpRequestService } from '@/core/HttpRequestService.js';
import { bindThis } from '@/decorators.js';
2022-09-17 20:27:08 +02:00
type CaptchaResponse = {
success: boolean;
'error-codes'?: string[];
};
@Injectable()
export class CaptchaService {
constructor(
private httpRequestService: HttpRequestService,
) {
}
@bindThis
2022-09-18 20:11:50 +02:00
private async getCaptchaResponse(url: string, secret: string, response: string): Promise<CaptchaResponse> {
2022-09-17 20:27:08 +02:00
const params = new URLSearchParams({
secret,
response,
});
const res = await this.httpRequestService.send(url, {
method: 'POST',
body: params.toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
2022-09-17 20:27:08 +02:00
},
}, { throwErrorWhenResponseNotOk: false });
2022-09-17 20:27:08 +02:00
if (!res.ok) {
throw new Error(`${res.status}`);
2022-09-17 20:27:08 +02:00
}
return await res.json() as CaptchaResponse;
}
@bindThis
public async verifyRecaptcha(secret: string, response: string | null | undefined): Promise<void> {
if (response == null) {
throw new Error('recaptcha-failed: no response provided');
}
const result = await this.getCaptchaResponse('https://www.recaptcha.net/recaptcha/api/siteverify', secret, response).catch(err => {
throw new Error(`recaptcha-request-failed: ${err}`);
2022-09-17 20:27:08 +02:00
});
if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
throw new Error(`recaptcha-failed: ${errorCodes}`);
2022-09-17 20:27:08 +02:00
}
}
@bindThis
public async verifyHcaptcha(secret: string, response: string | null | undefined): Promise<void> {
if (response == null) {
throw new Error('hcaptcha-failed: no response provided');
}
const result = await this.getCaptchaResponse('https://hcaptcha.com/siteverify', secret, response).catch(err => {
throw new Error(`hcaptcha-request-failed: ${err}`);
2022-09-17 20:27:08 +02:00
});
if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
throw new Error(`hcaptcha-failed: ${errorCodes}`);
2022-09-17 20:27:08 +02:00
}
}
@bindThis
public async verifyTurnstile(secret: string, response: string | null | undefined): Promise<void> {
if (response == null) {
throw new Error('turnstile-failed: no response provided');
}
const result = await this.getCaptchaResponse('https://challenges.cloudflare.com/turnstile/v0/siteverify', secret, response).catch(err => {
throw new Error(`turnstile-request-failed: ${err}`);
});
if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
throw new Error(`turnstile-failed: ${errorCodes}`);
}
}
2022-09-17 20:27:08 +02:00
}