@nathapp/nestjs-captcha 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.eslintrc.js +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +14 -0
  4. package/bun.lockb +0 -0
  5. package/dist/enum/captcha-type.enum.d.ts +4 -0
  6. package/dist/enum/captcha-type.enum.js +8 -0
  7. package/dist/enum/index.d.ts +1 -0
  8. package/dist/enum/index.js +17 -0
  9. package/dist/extractor/extractor.d.ts +12 -0
  10. package/dist/extractor/extractor.js +32 -0
  11. package/dist/extractor/index.d.ts +1 -0
  12. package/dist/extractor/index.js +17 -0
  13. package/dist/guard/captcha.guard.d.ts +10 -0
  14. package/dist/guard/captcha.guard.js +71 -0
  15. package/dist/guard/index.d.ts +1 -0
  16. package/dist/guard/index.js +17 -0
  17. package/dist/index.d.ts +5 -0
  18. package/dist/index.js +21 -0
  19. package/dist/module/captcha-module.factory.d.ts +9 -0
  20. package/dist/module/captcha-module.factory.js +47 -0
  21. package/dist/module/captcha-module.interface.d.ts +35 -0
  22. package/dist/module/captcha-module.interface.js +5 -0
  23. package/dist/module/captcha.module.d.ts +5 -0
  24. package/dist/module/captcha.module.js +31 -0
  25. package/dist/module/captcha.provider.d.ts +2 -0
  26. package/dist/module/captcha.provider.js +16 -0
  27. package/dist/module/index.d.ts +3 -0
  28. package/dist/module/index.js +19 -0
  29. package/dist/provider/index.d.ts +2 -0
  30. package/dist/provider/index.js +18 -0
  31. package/dist/provider/provider.d.ts +19 -0
  32. package/dist/provider/provider.factory.d.ts +5 -0
  33. package/dist/provider/provider.factory.js +16 -0
  34. package/dist/provider/provider.interface.d.ts +12 -0
  35. package/dist/provider/provider.interface.js +2 -0
  36. package/dist/provider/provider.js +77 -0
  37. package/index.d.ts +1 -0
  38. package/index.js +6 -0
  39. package/package.json +52 -0
package/.eslintrc.js ADDED
@@ -0,0 +1,24 @@
1
+ module.exports = {
2
+ parser: '@typescript-eslint/parser',
3
+ parserOptions: {
4
+ project: 'tsconfig.json',
5
+ sourceType: 'module',
6
+ },
7
+ plugins: ['@typescript-eslint/eslint-plugin'],
8
+ extends: [
9
+ 'plugin:@typescript-eslint/recommended',
10
+ 'plugin:prettier/recommended',
11
+ ],
12
+ root: true,
13
+ env: {
14
+ node: true,
15
+ jest: true,
16
+ },
17
+ ignorePatterns: ['.eslintrc.js'],
18
+ rules: {
19
+ '@typescript-eslint/interface-name-prefix': 'off',
20
+ '@typescript-eslint/explicit-function-return-type': 'off',
21
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
22
+ '@typescript-eslint/no-explicit-any': 'off',
23
+ },
24
+ };
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 KnowYourself
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # nestjs-captcha Library
2
+
3
+
4
+ # DefaultCaptchaModuleFactory support configService with env as below
5
+
6
+ 1. CAPTCHA_ENABLED = true/false, 1/0
7
+ 2. CAPTCHA_TYPE = recaptcha, turnstile
8
+ 3. CAPTCHA_SECRET = the secret
9
+ 4. CAPTCHA_ENDPOINT = custom endpoint
10
+ 5. CAPTCHA_THRESHOLD = for recaptcha
11
+
12
+ DefaultCaptchaModuleFactory is extract token from header and with key x-captcha-token
13
+
14
+ chatbot: 0
package/bun.lockb ADDED
Binary file
@@ -0,0 +1,4 @@
1
+ export declare enum CaptchaType {
2
+ Turnstile = "turnstile",
3
+ Recaptcha = "recaptcha"
4
+ }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CaptchaType = void 0;
4
+ var CaptchaType;
5
+ (function (CaptchaType) {
6
+ CaptchaType["Turnstile"] = "turnstile";
7
+ CaptchaType["Recaptcha"] = "recaptcha";
8
+ })(CaptchaType || (exports.CaptchaType = CaptchaType = {}));
@@ -0,0 +1 @@
1
+ export * from './captcha-type.enum';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./captcha-type.enum"), exports);
@@ -0,0 +1,12 @@
1
+ export interface TokenExtractFunction {
2
+ (request: any): string | null;
3
+ }
4
+ export interface ExtractOptions {
5
+ type: 'header' | 'body' | 'query';
6
+ key: string;
7
+ }
8
+ export declare const Extract: {
9
+ fromHeader: (header_name: string) => TokenExtractFunction;
10
+ fromBodyField: (field_name: string) => TokenExtractFunction;
11
+ fromUrlQueryParameter: (param_name: string) => TokenExtractFunction;
12
+ };
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Extract = void 0;
4
+ exports.Extract = {
5
+ fromHeader: (header_name) => {
6
+ return (request) => {
7
+ var token = null;
8
+ if (request.headers[header_name]) {
9
+ token = request.headers[header_name];
10
+ }
11
+ return token;
12
+ };
13
+ },
14
+ fromBodyField: (field_name) => {
15
+ return (request) => {
16
+ var token = null;
17
+ if (request.body && request.body[field_name]) {
18
+ token = request.body[field_name];
19
+ }
20
+ return token;
21
+ };
22
+ },
23
+ fromUrlQueryParameter: (param_name) => {
24
+ return (request) => {
25
+ var token = null;
26
+ if (request.query && request.query[param_name]) {
27
+ token = request.query[param_name];
28
+ }
29
+ return token;
30
+ };
31
+ }
32
+ };
@@ -0,0 +1 @@
1
+ export * from './extractor';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./extractor"), exports);
@@ -0,0 +1,10 @@
1
+ import { CanActivate, ExecutionContext } from "@nestjs/common";
2
+ import { CaptchaModuleOptions } from "../module";
3
+ import { CaptchaProvider } from "../provider/provider";
4
+ export declare class CaptchaGuard implements CanActivate {
5
+ private readonly options;
6
+ private readonly captchaProvider;
7
+ constructor(options: CaptchaModuleOptions, captchaProvider: CaptchaProvider);
8
+ canActivate(context: ExecutionContext): Promise<boolean>;
9
+ private extractToken;
10
+ }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.CaptchaGuard = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const module_1 = require("../module");
18
+ const provider_1 = require("../provider/provider");
19
+ const nestjs_common_1 = require("@nathapp/nestjs-common");
20
+ const extractor_1 = require("../extractor");
21
+ const captcha_exception_1 = require("@nathapp/nestjs-common/dist/exception/captcha.exception");
22
+ const common_2 = require("@nathapp/common");
23
+ let CaptchaGuard = class CaptchaGuard {
24
+ constructor(options, captchaProvider) {
25
+ this.options = options;
26
+ this.captchaProvider = captchaProvider;
27
+ }
28
+ async canActivate(context) {
29
+ const request = context.switchToHttp().getRequest();
30
+ if (!this.options || !this.options.enabled) {
31
+ return true;
32
+ }
33
+ const ip = (0, nestjs_common_1.getClientIp)(request);
34
+ const token = this.extractToken(request);
35
+ if ((0, common_2.isUndefinedOrNullOrEmpty)(token)) {
36
+ throw new captcha_exception_1.CaptchaException();
37
+ }
38
+ const tokenResult = await this.captchaProvider.verify({
39
+ token,
40
+ ip,
41
+ });
42
+ if (!tokenResult.success) {
43
+ throw new captcha_exception_1.CaptchaException();
44
+ }
45
+ return true;
46
+ }
47
+ extractToken(request) {
48
+ if (typeof this.options.extract === 'function') {
49
+ return this.options.extract(request);
50
+ }
51
+ else {
52
+ const { key, type } = this.options.extract;
53
+ switch (type) {
54
+ case 'header':
55
+ return extractor_1.Extract.fromHeader(key)(request);
56
+ case 'body':
57
+ return extractor_1.Extract.fromBodyField(key)(request);
58
+ case 'query':
59
+ return extractor_1.Extract.fromUrlQueryParameter(key)(request);
60
+ default:
61
+ return null;
62
+ }
63
+ }
64
+ }
65
+ };
66
+ exports.CaptchaGuard = CaptchaGuard;
67
+ exports.CaptchaGuard = CaptchaGuard = __decorate([
68
+ (0, common_1.Injectable)(),
69
+ __param(0, (0, common_1.Inject)(module_1.CAPTCHA_MODULE_OPTIONS)),
70
+ __metadata("design:paramtypes", [Object, provider_1.CaptchaProvider])
71
+ ], CaptchaGuard);
@@ -0,0 +1 @@
1
+ export * from './captcha.guard';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./captcha.guard"), exports);
@@ -0,0 +1,5 @@
1
+ export * from './enum';
2
+ export * from './extractor';
3
+ export * from './module';
4
+ export * from './provider';
5
+ export * from './guard';
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./enum"), exports);
18
+ __exportStar(require("./extractor"), exports);
19
+ __exportStar(require("./module"), exports);
20
+ __exportStar(require("./provider"), exports);
21
+ __exportStar(require("./guard"), exports);
@@ -0,0 +1,9 @@
1
+ import { CaptchaModuleFactory, CaptchaModuleOptions } from "./captcha-module.interface";
2
+ import { ConfigService } from "@nestjs/config";
3
+ export declare class DefaultCaptchaModuleFactory implements CaptchaModuleFactory {
4
+ private readonly configService;
5
+ private readonly options;
6
+ constructor(configService: ConfigService);
7
+ private parseOption;
8
+ createOptions(): Promise<CaptchaModuleOptions> | CaptchaModuleOptions;
9
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DefaultCaptchaModuleFactory = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const config_1 = require("@nestjs/config");
15
+ const common_2 = require("@nathapp/common");
16
+ let DefaultCaptchaModuleFactory = class DefaultCaptchaModuleFactory {
17
+ constructor(configService) {
18
+ this.configService = configService;
19
+ this.options = {
20
+ enabled: this.parseOption('CAPTCHA_ENABLED', true),
21
+ extract: {
22
+ type: 'header',
23
+ key: 'x-captcha-token',
24
+ },
25
+ type: this.configService.get('CAPTCHA_TYPE'),
26
+ options: {
27
+ secret: this.configService.get('CAPTCHA_SECRET'),
28
+ endpoint: this.configService.get('CAPTCHA_ENDPOINT'),
29
+ },
30
+ };
31
+ }
32
+ parseOption(key, defaultValue) {
33
+ const str = this.configService.get(key);
34
+ if ((0, common_2.isUndefinedOrNullOrEmpty)(str)) {
35
+ return defaultValue;
36
+ }
37
+ return str.toLowerCase() == 'true' || str == '1';
38
+ }
39
+ createOptions() {
40
+ return this.options;
41
+ }
42
+ };
43
+ exports.DefaultCaptchaModuleFactory = DefaultCaptchaModuleFactory;
44
+ exports.DefaultCaptchaModuleFactory = DefaultCaptchaModuleFactory = __decorate([
45
+ (0, common_1.Injectable)(),
46
+ __metadata("design:paramtypes", [config_1.ConfigService])
47
+ ], DefaultCaptchaModuleFactory);
@@ -0,0 +1,35 @@
1
+ import { ModuleMetadata, Type } from "@nestjs/common";
2
+ import { CaptchaType } from "../enum";
3
+ import { ExtractOptions, TokenExtractFunction } from "../extractor";
4
+ export declare const CAPTCHA_MODULE_OPTIONS = "CAPTCHA_MODULE_OPTIONS";
5
+ export declare const CAPTCHA_PROVIDER = "CAPTCHA_PROVIDER";
6
+ export type CaptchaOptions = RecaptchaOptions | TurnstileOptions;
7
+ export interface RecaptchaOptions {
8
+ type: CaptchaType.Recaptcha;
9
+ options: CaptchaCommonOptions & {
10
+ threshold?: number;
11
+ };
12
+ }
13
+ export interface TurnstileOptions {
14
+ type: CaptchaType.Turnstile;
15
+ options: CaptchaCommonOptions & {
16
+ idempotency?: boolean;
17
+ };
18
+ }
19
+ export interface CaptchaCommonOptions {
20
+ secret: string;
21
+ endpoint?: string;
22
+ }
23
+ export type CaptchaModuleOptions = {
24
+ enabled: boolean;
25
+ extract: TokenExtractFunction | ExtractOptions;
26
+ } & CaptchaOptions;
27
+ export interface CaptchaModuleFactory {
28
+ createOptions(): Promise<CaptchaModuleOptions> | CaptchaModuleOptions;
29
+ }
30
+ export interface CaptchaAsyncModuleOptions extends Pick<ModuleMetadata, 'imports'> {
31
+ useExisting?: Type<CaptchaModuleFactory>;
32
+ useClass?: Type<CaptchaModuleFactory>;
33
+ useFactory?: (...args: any[]) => CaptchaModuleOptions | Promise<CaptchaModuleOptions>;
34
+ inject?: any[];
35
+ }
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CAPTCHA_PROVIDER = exports.CAPTCHA_MODULE_OPTIONS = void 0;
4
+ exports.CAPTCHA_MODULE_OPTIONS = 'CAPTCHA_MODULE_OPTIONS';
5
+ exports.CAPTCHA_PROVIDER = 'CAPTCHA_PROVIDER';
@@ -0,0 +1,5 @@
1
+ import { CaptchaModuleOptions } from "./captcha-module.interface";
2
+ declare const CaptchaModule_base: import("@nathapp/nestjs-common").ConfigurableModuleCls<CaptchaModuleOptions, "register", "createOptions", {}>;
3
+ export declare class CaptchaModule extends CaptchaModule_base {
4
+ }
5
+ export {};
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.CaptchaModule = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const captcha_module_interface_1 = require("./captcha-module.interface");
12
+ const nestjs_common_1 = require("@nathapp/nestjs-common");
13
+ const captcha_provider_1 = require("./captcha.provider");
14
+ const provider_1 = require("../provider/provider");
15
+ const captcha_guard_1 = require("../guard/captcha.guard");
16
+ let CaptchaModule = class CaptchaModule extends (0, nestjs_common_1.ConfigurableModuleClass)(captcha_module_interface_1.CAPTCHA_MODULE_OPTIONS) {
17
+ };
18
+ exports.CaptchaModule = CaptchaModule;
19
+ exports.CaptchaModule = CaptchaModule = __decorate([
20
+ (0, common_1.Module)({
21
+ providers: [
22
+ (0, captcha_provider_1.createCaptchaProvider)(),
23
+ {
24
+ provide: provider_1.CaptchaProvider,
25
+ useExisting: captcha_module_interface_1.CAPTCHA_PROVIDER,
26
+ },
27
+ captcha_guard_1.CaptchaGuard,
28
+ ],
29
+ exports: [captcha_guard_1.CaptchaGuard, provider_1.CaptchaProvider, captcha_module_interface_1.CAPTCHA_PROVIDER, captcha_module_interface_1.CAPTCHA_MODULE_OPTIONS],
30
+ })
31
+ ], CaptchaModule);
@@ -0,0 +1,2 @@
1
+ import { Provider } from "@nestjs/common";
2
+ export declare const createCaptchaProvider: () => Provider;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createCaptchaProvider = void 0;
4
+ const provider_factory_1 = require("../provider/provider.factory");
5
+ const captcha_module_interface_1 = require("./captcha-module.interface");
6
+ const createCaptchaProvider = () => {
7
+ return {
8
+ provide: captcha_module_interface_1.CAPTCHA_PROVIDER,
9
+ useFactory: async (options) => {
10
+ const provider = provider_factory_1.CaptchaProviderFactory.createProvider(options);
11
+ return provider;
12
+ },
13
+ inject: [captcha_module_interface_1.CAPTCHA_MODULE_OPTIONS],
14
+ };
15
+ };
16
+ exports.createCaptchaProvider = createCaptchaProvider;
@@ -0,0 +1,3 @@
1
+ export * from './captcha-module.interface';
2
+ export * from './captcha.module';
3
+ export * from './captcha-module.factory';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./captcha-module.interface"), exports);
18
+ __exportStar(require("./captcha.module"), exports);
19
+ __exportStar(require("./captcha-module.factory"), exports);
@@ -0,0 +1,2 @@
1
+ export * from "./provider.interface";
2
+ export * from "./provider";
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./provider.interface"), exports);
18
+ __exportStar(require("./provider"), exports);
@@ -0,0 +1,19 @@
1
+ import { RecaptchaOptions, TurnstileOptions } from "../module";
2
+ import { CaptchaVerifyResult, CaptchaVerifyToken } from "./provider.interface";
3
+ export interface ICaptchaProvider {
4
+ verify(token: CaptchaVerifyToken): Promise<CaptchaVerifyResult>;
5
+ }
6
+ export declare abstract class CaptchaProvider implements ICaptchaProvider {
7
+ abstract verify(token: CaptchaVerifyToken): Promise<CaptchaVerifyResult>;
8
+ }
9
+ export declare class TurnstileCaptchaProvider extends CaptchaProvider {
10
+ private options;
11
+ constructor(options: TurnstileOptions["options"]);
12
+ verify(tokenPayload: CaptchaVerifyToken): Promise<CaptchaVerifyResult>;
13
+ private siteVerify;
14
+ }
15
+ export declare class RecaptchaCaptchaProvider implements CaptchaProvider {
16
+ private options;
17
+ constructor(options: RecaptchaOptions["options"]);
18
+ verify(tokenPayload: CaptchaVerifyToken): Promise<CaptchaVerifyResult>;
19
+ }
@@ -0,0 +1,5 @@
1
+ import { CaptchaOptions } from "../module";
2
+ import { CaptchaProvider } from "./provider";
3
+ export declare class CaptchaProviderFactory {
4
+ static createProvider(options: CaptchaOptions): CaptchaProvider;
5
+ }
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CaptchaProviderFactory = void 0;
4
+ const enum_1 = require("../enum");
5
+ const provider_1 = require("./provider");
6
+ class CaptchaProviderFactory {
7
+ static createProvider(options) {
8
+ switch (options.type) {
9
+ case enum_1.CaptchaType.Turnstile:
10
+ return new provider_1.TurnstileCaptchaProvider(options['options']);
11
+ case enum_1.CaptchaType.Recaptcha:
12
+ return new provider_1.RecaptchaCaptchaProvider(options['options']);
13
+ }
14
+ }
15
+ }
16
+ exports.CaptchaProviderFactory = CaptchaProviderFactory;
@@ -0,0 +1,12 @@
1
+ export interface CaptchaVerifyToken {
2
+ token: string;
3
+ ip: string;
4
+ }
5
+ export interface CaptchaVerifyResult {
6
+ success: boolean;
7
+ hostname: string;
8
+ score?: number;
9
+ action?: string;
10
+ challengeTs?: string;
11
+ errorCodes?: string[];
12
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RecaptchaCaptchaProvider = exports.TurnstileCaptchaProvider = exports.CaptchaProvider = void 0;
4
+ const crypto = require("crypto");
5
+ class CaptchaProvider {
6
+ }
7
+ exports.CaptchaProvider = CaptchaProvider;
8
+ class TurnstileCaptchaProvider extends CaptchaProvider {
9
+ constructor(options) {
10
+ super();
11
+ this.options = Object.assign({ idempotency: true }, options);
12
+ }
13
+ async verify(tokenPayload) {
14
+ const url = this.options.endpoint ||
15
+ "https://challenges.cloudflare.com/turnstile/v0/siteverify";
16
+ const idempotencyKey = this.options.idempotency
17
+ ? crypto.randomUUID()
18
+ : undefined;
19
+ const result = await this.siteVerify(url, tokenPayload, idempotencyKey);
20
+ if (result.success || (!result.success && !this.options.idempotency)) {
21
+ return result;
22
+ }
23
+ return this.siteVerify(url, tokenPayload, idempotencyKey);
24
+ }
25
+ async siteVerify(url, tokenPayload, idempotencyKey) {
26
+ const response = await fetch(url, {
27
+ body: JSON.stringify({
28
+ secret: this.options.secret,
29
+ response: tokenPayload.token,
30
+ remoteip: tokenPayload.ip,
31
+ idempotency_key: idempotencyKey,
32
+ }),
33
+ method: "POST",
34
+ headers: {
35
+ "Content-Type": "application/json",
36
+ },
37
+ });
38
+ const result = await response.json();
39
+ return {
40
+ success: result.success,
41
+ hostname: result.hostname,
42
+ challengeTs: result.challenge_ts,
43
+ errorCodes: result["error-codes"],
44
+ };
45
+ }
46
+ }
47
+ exports.TurnstileCaptchaProvider = TurnstileCaptchaProvider;
48
+ class RecaptchaCaptchaProvider {
49
+ constructor(options) {
50
+ this.options = options;
51
+ }
52
+ async verify(tokenPayload) {
53
+ const url = this.options.endpoint ||
54
+ "https://www.google.com/recaptcha/api/siteverify";
55
+ const response = await fetch(url, {
56
+ body: JSON.stringify({
57
+ secret: this.options.secret,
58
+ response: tokenPayload.token,
59
+ remoteip: tokenPayload.ip,
60
+ }),
61
+ method: "POST",
62
+ headers: {
63
+ "Content-Type": "application/json",
64
+ },
65
+ });
66
+ const result = await response.json();
67
+ return {
68
+ success: result.success,
69
+ hostname: result.hostname,
70
+ challengeTs: result.challenge_ts,
71
+ score: result.score,
72
+ action: result.action,
73
+ errorCodes: result["error-codes"],
74
+ };
75
+ }
76
+ }
77
+ exports.RecaptchaCaptchaProvider = RecaptchaCaptchaProvider;
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./dist";
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ function __export(m) {
3
+ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
+ }
5
+ exports.__esModule = true;
6
+ __export(require("./dist"));
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@nathapp/nestjs-captcha",
3
+ "version": "1.0.0",
4
+ "description": "nestjs-captcha",
5
+ "scripts": {
6
+ "build": "rimraf dist && tsc -p tsconfig.json",
7
+ "precommit": "lint-staged",
8
+ "test": "jest --config ./test/jest-test.json",
9
+ "test:cov": "jest --config ./test/jest-test.json --coverage",
10
+ "test:watch": "jest --config ./test/jest-test.json --watch",
11
+ "lint": "eslint -c .eslintrc.js"
12
+ },
13
+ "author": "William Khoo",
14
+ "license": "ISC",
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "devDependencies": {
19
+ "@golevelup/ts-jest": "^0.4.0",
20
+ "@nestjs/platform-express": "^10.0.0",
21
+ "@nestjs/platform-fastify": "^10.0.0",
22
+ "@nestjs/testing": "^10.0.0",
23
+ "@types/jest": "^29.5.2",
24
+ "@types/node": "18.11.18",
25
+ "@types/supertest": "^2.0.12",
26
+ "@typescript-eslint/eslint-plugin": "^7.1.0",
27
+ "@typescript-eslint/parser": "^7.1.0",
28
+ "eslint": "^8.57.1",
29
+ "eslint-config-prettier": "^6",
30
+ "eslint-plugin-prettier": "^3",
31
+ "jest": "^29.5.0",
32
+ "prettier": "^2",
33
+ "supertest": "^6.3.3",
34
+ "ts-jest": "^29.1.0",
35
+ "typescript": "^5"
36
+ },
37
+ "types": "./index.d.ts",
38
+ "main": "index.js",
39
+ "directories": {
40
+ "lib": "lib"
41
+ },
42
+ "dependencies": {},
43
+ "peerDependencies": {
44
+ "@nathapp/nestjs-common": "^1.0.2-rc.1",
45
+ "@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0",
46
+ "@nestjs/config": "^1.0.0 || ^2.0.0 || ^3.0.0",
47
+ "@nestjs/core": "^8.0.0 || ^9.0.0 || ^10.0.0",
48
+ "class-transformer": "*",
49
+ "class-validator": "*",
50
+ "rxjs": "*"
51
+ }
52
+ }