summaryrefslogtreecommitdiff
path: root/packages/backend/src/core/CaptchaService.ts
blob: 13200bf7b3798c4a979638a6195acff40631cbed (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { Injectable } from '@nestjs/common';
import { HttpRequestService } from '@/core/HttpRequestService.js';
import { bindThis } from '@/decorators.js';
import { MetaService } from '@/core/MetaService.js';
import { MiMeta } from '@/models/Meta.js';
import Logger from '@/logger.js';
import { LoggerService } from './LoggerService.js';

export const supportedCaptchaProviders = ['none', 'hcaptcha', 'mcaptcha', 'recaptcha', 'turnstile', 'fc', 'testcaptcha'] as const;
export type CaptchaProvider = typeof supportedCaptchaProviders[number];

export const captchaErrorCodes = {
	invalidProvider: Symbol('invalidProvider'),
	invalidParameters: Symbol('invalidParameters'),
	noResponseProvided: Symbol('noResponseProvided'),
	requestFailed: Symbol('requestFailed'),
	verificationFailed: Symbol('verificationFailed'),
	unknown: Symbol('unknown'),
} as const;
export type CaptchaErrorCode = typeof captchaErrorCodes[keyof typeof captchaErrorCodes];

export type CaptchaSetting = {
	provider: CaptchaProvider;
	hcaptcha: {
		siteKey: string | null;
		secretKey: string | null;
	}
	mcaptcha: {
		siteKey: string | null;
		secretKey: string | null;
		instanceUrl: string | null;
	}
	recaptcha: {
		siteKey: string | null;
		secretKey: string | null;
	}
	turnstile: {
		siteKey: string | null;
		secretKey: string | null;
	}
	fc: {
		siteKey: string | null;
		secretKey: string | null;
	}
};

export class CaptchaError extends Error {
	public readonly code: CaptchaErrorCode;
	public readonly cause?: unknown;

	constructor(code: CaptchaErrorCode, message: string, cause?: unknown) {
		super(message);
		this.code = code;
		this.cause = cause;
		this.name = 'CaptchaError';
	}
}

export type CaptchaSaveSuccess = {
	success: true;
};
export type CaptchaSaveFailure = {
	success: false;
	error: CaptchaError;
};
export type CaptchaSaveResult = CaptchaSaveSuccess | CaptchaSaveFailure;

type CaptchaResponse = {
	success: boolean;
	'error-codes'?: string[];
	'errors'?: string[];
};

@Injectable()
export class CaptchaService {
	private readonly logger: Logger;

	constructor(
		private httpRequestService: HttpRequestService,
		private metaService: MetaService,
		loggerService: LoggerService,
	) {
		this.logger = loggerService.getLogger('captcha');
	}

	@bindThis
	private async getCaptchaResponse(url: string, secret: string, response: string): Promise<CaptchaResponse> {
		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',
			},
		}, { throwErrorWhenResponseNotOk: false });

		if (!res.ok) {
			throw new Error(`${res.status}`);
		}

		return await res.json() as CaptchaResponse;
	}

	@bindThis
	public async verifyRecaptcha(secret: string, response: string | null | undefined): Promise<void> {
		if (response == null) {
			throw new CaptchaError(captchaErrorCodes.noResponseProvided, 'recaptcha-failed: no response provided');
		}

		const result = await this.getCaptchaResponse('https://www.recaptcha.net/recaptcha/api/siteverify', secret, response).catch(err => {
			throw new CaptchaError(captchaErrorCodes.requestFailed, `recaptcha-request-failed: ${err}`);
		});

		if (result.success !== true) {
			const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
			throw new CaptchaError(captchaErrorCodes.verificationFailed, `recaptcha-failed: ${errorCodes}`);
		}
	}

	@bindThis
	public async verifyHcaptcha(secret: string, response: string | null | undefined): Promise<void> {
		if (response == null) {
			throw new CaptchaError(captchaErrorCodes.noResponseProvided, 'hcaptcha-failed: no response provided');
		}

		const result = await this.getCaptchaResponse('https://hcaptcha.com/siteverify', secret, response).catch(err => {
			throw new CaptchaError(captchaErrorCodes.requestFailed, `hcaptcha-request-failed: ${err}`);
		});

		if (result.success !== true) {
			const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
			throw new CaptchaError(captchaErrorCodes.verificationFailed, `hcaptcha-failed: ${errorCodes}`);
		}
	}

	@bindThis
	public async verifyFriendlyCaptcha(secret: string, response: string | null | undefined): Promise<void> {
		if (response == null) {
			throw new CaptchaError(captchaErrorCodes.noResponseProvided, 'frc-failed: no response provided');
		}

		const result = await this.httpRequestService.send('https://api.friendlycaptcha.com/api/v1/siteverify', {
			method: 'POST',
			body: JSON.stringify({
				secret: secret,
				solution: response,
			}),
			headers: {
				'Content-Type': 'application/json',
			},
		}, { throwErrorWhenResponseNotOk: false });

		if (result.status !== 200) {
			throw new CaptchaError(captchaErrorCodes.requestFailed, `frc-request-failed: ${result.status}`);
		}

		const resp = await result.json() as CaptchaResponse;

		if (resp.success !== true) {
			const errorCodes = resp['errors'] ? resp['errors'].join(', ') : '';
			throw new CaptchaError(captchaErrorCodes.verificationFailed, `frc-failed: ${errorCodes}`);
		}
	}

	// https://codeberg.org/Gusted/mCaptcha/src/branch/main/mcaptcha.go
	@bindThis
	public async verifyMcaptcha(secret: string, siteKey: string, instanceHost: string, response: string | null | undefined): Promise<void> {
		if (response == null) {
			throw new CaptchaError(captchaErrorCodes.noResponseProvided, 'mcaptcha-failed: no response provided');
		}

		const endpointUrl = new URL('/api/v1/pow/siteverify', instanceHost);
		const result = await this.httpRequestService.send(endpointUrl.toString(), {
			method: 'POST',
			body: JSON.stringify({
				key: siteKey,
				secret: secret,
				token: response,
			}),
			headers: {
				'Content-Type': 'application/json',
			},
		}, { throwErrorWhenResponseNotOk: false });

		if (result.status !== 200) {
			throw new CaptchaError(captchaErrorCodes.requestFailed, 'mcaptcha-failed: mcaptcha didn\'t return 200 OK');
		}

		const resp = (await result.json()) as { valid: boolean };

		if (!resp.valid) {
			throw new CaptchaError(captchaErrorCodes.verificationFailed, 'mcaptcha-request-failed');
		}
	}

	@bindThis
	public async verifyTurnstile(secret: string, response: string | null | undefined): Promise<void> {
		if (response == null) {
			throw new CaptchaError(captchaErrorCodes.noResponseProvided, 'turnstile-failed: no response provided');
		}

		const result = await this.getCaptchaResponse('https://challenges.cloudflare.com/turnstile/v0/siteverify', secret, response).catch(err => {
			throw new CaptchaError(captchaErrorCodes.requestFailed, `turnstile-request-failed: ${err}`);
		});

		if (result.success !== true) {
			const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
			throw new CaptchaError(captchaErrorCodes.verificationFailed, `turnstile-failed: ${errorCodes}`);
		}
	}

	@bindThis
	public async verifyTestcaptcha(response: string | null | undefined): Promise<void> {
		if (response == null) {
			throw new CaptchaError(captchaErrorCodes.noResponseProvided, 'testcaptcha-failed: no response provided');
		}

		const success = response === 'testcaptcha-passed';

		if (!success) {
			throw new CaptchaError(captchaErrorCodes.verificationFailed, 'testcaptcha-failed');
		}
	}

	@bindThis
	public async get(): Promise<CaptchaSetting> {
		const meta = await this.metaService.fetch(true);

		let provider: CaptchaProvider;
		switch (true) {
			case meta.enableHcaptcha: {
				provider = 'hcaptcha';
				break;
			}
			case meta.enableMcaptcha: {
				provider = 'mcaptcha';
				break;
			}
			case meta.enableRecaptcha: {
				provider = 'recaptcha';
				break;
			}
			case meta.enableTurnstile: {
				provider = 'turnstile';
				break;
			}
			case meta.enableTestcaptcha: {
				provider = 'testcaptcha';
				break;
			}
			case meta.enableFC: {
				provider = 'fc';
				break;
			}
			default: {
				provider = 'none';
				break;
			}
		}

		return {
			provider: provider,
			hcaptcha: {
				siteKey: meta.hcaptchaSiteKey,
				secretKey: meta.hcaptchaSecretKey,
			},
			mcaptcha: {
				siteKey: meta.mcaptchaSitekey,
				secretKey: meta.mcaptchaSecretKey,
				instanceUrl: meta.mcaptchaInstanceUrl,
			},
			recaptcha: {
				siteKey: meta.recaptchaSiteKey,
				secretKey: meta.recaptchaSecretKey,
			},
			turnstile: {
				siteKey: meta.turnstileSiteKey,
				secretKey: meta.turnstileSecretKey,
			},
			fc: {
				siteKey: meta.fcSiteKey,
				secretKey: meta.fcSecretKey,
			},
		};
	}

	/**
	 * captchaの設定を更新します. その際、フロントエンド側で受け取ったcaptchaからの戻り値を検証し、passした場合のみ設定を更新します.
	 * 実際の検証処理はサービス内で定義されている各captchaプロバイダの検証関数に委譲します.
	 *
	 * @param provider 検証するcaptchaのプロバイダ
	 * @param params
	 * @param params.sitekey hcaptcha, recaptcha, turnstile, mcaptchaの場合に指定するsitekey. それ以外のプロバイダでは無視されます
	 * @param params.secret hcaptcha, recaptcha, turnstile, mcaptchaの場合に指定するsecret. それ以外のプロバイダでは無視されます
	 * @param params.instanceUrl mcaptchaの場合に指定するインスタンスのURL. それ以外のプロバイダでは無視されます
	 * @param params.captchaResult フロントエンド側で受け取ったcaptchaプロバイダからの戻り値. この値を使ってサーバサイドでの検証を行います
	 * @see verifyHcaptcha
	 * @see verifyMcaptcha
	 * @see verifyRecaptcha
	 * @see verifyTurnstile
	 * @see verifyTestcaptcha
	 */
	@bindThis
	public async save(
		provider: CaptchaProvider,
		params?: {
			sitekey?: string | null;
			secret?: string | null;
			instanceUrl?: string | null;
			captchaResult?: string | null;
		},
	): Promise<CaptchaSaveResult> {
		if (!supportedCaptchaProviders.includes(provider)) {
			return {
				success: false,
				error: new CaptchaError(captchaErrorCodes.invalidProvider, `Invalid captcha provider: ${provider}`),
			};
		}

		const operation = {
			none: async () => {
				await this.updateMeta(provider, params);
			},
			hcaptcha: async () => {
				if (!params?.secret || !params.captchaResult) {
					throw new CaptchaError(captchaErrorCodes.invalidParameters, 'hcaptcha-failed: secret and captureResult are required');
				}

				await this.verifyHcaptcha(params.secret, params.captchaResult);
				await this.updateMeta(provider, params);
			},
			mcaptcha: async () => {
				if (!params?.secret || !params.sitekey || !params.instanceUrl || !params.captchaResult) {
					throw new CaptchaError(captchaErrorCodes.invalidParameters, 'mcaptcha-failed: secret, sitekey, instanceUrl and captureResult are required');
				}

				await this.verifyMcaptcha(params.secret, params.sitekey, params.instanceUrl, params.captchaResult);
				await this.updateMeta(provider, params);
			},
			recaptcha: async () => {
				if (!params?.secret || !params.captchaResult) {
					throw new CaptchaError(captchaErrorCodes.invalidParameters, 'recaptcha-failed: secret and captureResult are required');
				}

				await this.verifyRecaptcha(params.secret, params.captchaResult);
				await this.updateMeta(provider, params);
			},
			turnstile: async () => {
				if (!params?.secret || !params.captchaResult) {
					throw new CaptchaError(captchaErrorCodes.invalidParameters, 'turnstile-failed: secret and captureResult are required');
				}

				await this.verifyTurnstile(params.secret, params.captchaResult);
				await this.updateMeta(provider, params);
			},
			testcaptcha: async () => {
				if (!params?.captchaResult) {
					throw new CaptchaError(captchaErrorCodes.invalidParameters, 'turnstile-failed: captureResult are required');
				}

				await this.verifyTestcaptcha(params.captchaResult);
				await this.updateMeta(provider, params);
			},
			fc: async () => {
				if (!params?.secret || !params.captchaResult) {
					throw new CaptchaError(captchaErrorCodes.invalidParameters, 'frc-failed: secret and captureResult are required');
				}

				await this.verifyFriendlyCaptcha(params.secret, params.captchaResult);
				await this.updateMeta(provider, params);
			},
		}[provider];

		return operation()
			.then(() => ({ success: true }) as CaptchaSaveSuccess)
			.catch(err => {
				this.logger.info(err);
				const error = err instanceof CaptchaError
					? err
					: new CaptchaError(captchaErrorCodes.unknown, `unknown error: ${err}`);
				return {
					success: false,
					error,
				};
			});
	}

	@bindThis
	private async updateMeta(
		provider: CaptchaProvider,
		params?: {
			sitekey?: string | null;
			secret?: string | null;
			instanceUrl?: string | null;
		},
	) {
		const metaPartial: Partial<
			Pick<
				MiMeta,
				('enableHcaptcha' | 'hcaptchaSiteKey' | 'hcaptchaSecretKey') |
				('enableMcaptcha' | 'mcaptchaSitekey' | 'mcaptchaSecretKey' | 'mcaptchaInstanceUrl') |
				('enableRecaptcha' | 'recaptchaSiteKey' | 'recaptchaSecretKey') |
				('enableTurnstile' | 'turnstileSiteKey' | 'turnstileSecretKey') |
				('enableTestcaptcha' | 'enableFC' | 'fcSiteKey' | 'fcSecretKey')
			>
		> = {
			enableHcaptcha: provider === 'hcaptcha',
			enableMcaptcha: provider === 'mcaptcha',
			enableRecaptcha: provider === 'recaptcha',
			enableTurnstile: provider === 'turnstile',
			enableTestcaptcha: provider === 'testcaptcha',
			enableFC: provider === 'fc',
		};

		const updateIfNotUndefined = <K extends keyof typeof metaPartial>(key: K, value: typeof metaPartial[K]) => {
			if (value !== undefined) {
				metaPartial[key] = value;
			}
		};
		switch (provider) {
			case 'hcaptcha': {
				updateIfNotUndefined('hcaptchaSiteKey', params?.sitekey);
				updateIfNotUndefined('hcaptchaSecretKey', params?.secret);
				break;
			}
			case 'mcaptcha': {
				updateIfNotUndefined('mcaptchaSitekey', params?.sitekey);
				updateIfNotUndefined('mcaptchaSecretKey', params?.secret);
				updateIfNotUndefined('mcaptchaInstanceUrl', params?.instanceUrl);
				break;
			}
			case 'recaptcha': {
				updateIfNotUndefined('recaptchaSiteKey', params?.sitekey);
				updateIfNotUndefined('recaptchaSecretKey', params?.secret);
				break;
			}
			case 'turnstile': {
				updateIfNotUndefined('turnstileSiteKey', params?.sitekey);
				updateIfNotUndefined('turnstileSecretKey', params?.secret);
				break;
			}
			case 'fc': {
				updateIfNotUndefined('fcSiteKey', params?.sitekey);
				updateIfNotUndefined('fcSecretKey', params?.secret);
			}
		}

		await this.metaService.update(metaPartial);
	}
}