summaryrefslogtreecommitdiff
path: root/packages/backend/src/core/CaptchaService.ts
diff options
context:
space:
mode:
authorsyuilo <Syuilotan@yahoo.co.jp>2022-09-18 03:27:08 +0900
committerGitHub <noreply@github.com>2022-09-18 03:27:08 +0900
commitb75184ec8e3436200bacdcd832e3324702553d20 (patch)
tree8b7e316f29e95df921db57289c8b8da476d18f07 /packages/backend/src/core/CaptchaService.ts
parentUpdate ROADMAP.md (diff)
downloadsharkey-b75184ec8e3436200bacdcd832e3324702553d20.tar.gz
sharkey-b75184ec8e3436200bacdcd832e3324702553d20.tar.bz2
sharkey-b75184ec8e3436200bacdcd832e3324702553d20.zip
なんかもうめっちゃ変えた
Diffstat (limited to 'packages/backend/src/core/CaptchaService.ts')
-rw-r--r--packages/backend/src/core/CaptchaService.ts70
1 files changed, 70 insertions, 0 deletions
diff --git a/packages/backend/src/core/CaptchaService.ts b/packages/backend/src/core/CaptchaService.ts
new file mode 100644
index 0000000000..891e5315c2
--- /dev/null
+++ b/packages/backend/src/core/CaptchaService.ts
@@ -0,0 +1,70 @@
+import { Inject, Injectable } from '@nestjs/common';
+import { DI } from '@/di-symbols.js';
+import type { UsersRepository } from '@/models/index.js';
+import { Config } from '@/config.js';
+import { HttpRequestService } from './HttpRequestService.js';
+
+type CaptchaResponse = {
+ success: boolean;
+ 'error-codes'?: string[];
+};
+
+@Injectable()
+export class CaptchaService {
+ constructor(
+ @Inject(DI.config)
+ private config: Config,
+
+ private httpRequestService: HttpRequestService,
+ ) {
+ }
+
+ async #getCaptchaResponse(url: string, secret: string, response: string): Promise<CaptchaResponse> {
+ const params = new URLSearchParams({
+ secret,
+ response,
+ });
+
+ const res = await fetch(url, {
+ method: 'POST',
+ body: params,
+ headers: {
+ 'User-Agent': this.config.userAgent,
+ },
+ // TODO
+ //timeout: 10 * 1000,
+ agent: (url, bypassProxy) => this.httpRequestService.getAgentByUrl(url, bypassProxy),
+ }).catch(err => {
+ throw `${err.message ?? err}`;
+ });
+
+ if (!res.ok) {
+ throw `${res.status}`;
+ }
+
+ return await res.json() as CaptchaResponse;
+ }
+
+ public async verifyRecaptcha(secret: string, response: string): Promise<void> {
+ const result = await this.#getCaptchaResponse('https://www.recaptcha.net/recaptcha/api/siteverify', secret, response).catch(e => {
+ throw `recaptcha-request-failed: ${e}`;
+ });
+
+ if (result.success !== true) {
+ const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
+ throw `recaptcha-failed: ${errorCodes}`;
+ }
+ }
+
+ public async verifyHcaptcha(secret: string, response: string): Promise<void> {
+ const result = await this.#getCaptchaResponse('https://hcaptcha.com/siteverify', secret, response).catch(e => {
+ throw `hcaptcha-request-failed: ${e}`;
+ });
+
+ if (result.success !== true) {
+ const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
+ throw `hcaptcha-failed: ${errorCodes}`;
+ }
+ }
+}
+