UNPKG

@trustcomponent/trustcaptcha-nodejs

Version:

TrustCaptcha – Privacy-first CAPTCHA solution for Node.js and TypeScript. GDPR-compliant, bot protection made in Europe.

251 lines (250 loc) 14.6 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClientReportedServerUnreachableException = exports.ServerUnreachableException = exports.FailoverException = exports.VerificationResultRetrievalLimitReachedException = exports.VerificationResultExpiredException = exports.VerificationNotFinishedException = exports.VerificationNotFoundException = exports.VerificationTokenInvalidException = exports.ApiKeyInvalidException = exports.TrustCaptcha = void 0; var axios_1 = require("axios"); var verificationToken_1 = require("./model/verificationToken"); var verificationResult_1 = require("./model/verificationResult"); var LIBRARY_VERSION = '3.0.0'; var LIBRARY_LANGUAGE = 'nodejs'; var DEFAULT_API_HOST = 'https://api.trustcomponent.com'; var DEFAULT_CONNECT_TIMEOUT_MS = 3000; var DEFAULT_READ_TIMEOUT_MS = 5000; var TrustCaptcha = /** @class */ (function () { function TrustCaptcha(options) { var _a, _b, _c; if (!options || !options.apiKey) { throw new Error('apiKey must not be null or empty'); } this.apiKey = options.apiKey; this.apiHost = (_a = options.apiHost) !== null && _a !== void 0 ? _a : DEFAULT_API_HOST; this.connectTimeoutMs = (_b = options.connectTimeoutMs) !== null && _b !== void 0 ? _b : DEFAULT_CONNECT_TIMEOUT_MS; this.readTimeoutMs = (_c = options.readTimeoutMs) !== null && _c !== void 0 ? _c : DEFAULT_READ_TIMEOUT_MS; this.proxy = options.proxy; } TrustCaptcha.getVerificationResult = function (apiKey, base64verificationToken) { return new TrustCaptcha({ apiKey: apiKey }).getVerificationResult(base64verificationToken); }; TrustCaptcha.prototype.getVerificationResult = function (base64verificationToken) { return __awaiter(this, void 0, void 0, function () { var verificationToken, params, url, headers, response, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: verificationToken = verificationToken_1.VerificationToken.fromBase64(base64verificationToken); params = verificationToken.clientFailover ? "?clientFailover=true" : ""; url = "".concat(this.apiHost, "/v2/verifications/").concat(verificationToken.verificationId, "/results").concat(params); headers = { "Authorization": "Bearer ".concat(this.apiKey), "User-Agent": buildUserAgent(), }; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, axios_1.default.get(url, { headers: headers, timeout: this.readTimeoutMs, maxRedirects: 0, proxy: this.proxy, })]; case 2: response = _a.sent(); return [2 /*return*/, verificationResult_1.VerificationResult.fromObject(response.data)]; case 3: error_1 = _a.sent(); if (error_1.response && error_1.response.status === 403) { throw new ApiKeyInvalidException(); } if (error_1.response && error_1.response.status === 404) { throw new VerificationNotFoundException(); } if (error_1.response && error_1.response.status === 423) { throw new VerificationNotFinishedException(); } if (error_1.response && error_1.response.status === 410) { throw new VerificationResultExpiredException(); } if (error_1.response && error_1.response.status === 412) { throw new ClientReportedServerUnreachableException(); } if (error_1.response && error_1.response.status === 429) { throw new VerificationResultRetrievalLimitReachedException(); } if (error_1.response) { throw new Error('Failed to retrieve verification result, response code: ' + error_1.response.status); } // No HTTP response at all → genuine network/connection failure on our side. throw new ServerUnreachableException(); case 4: return [2 /*return*/]; } }); }); }; return TrustCaptcha; }()); exports.TrustCaptcha = TrustCaptcha; function buildUserAgent() { var payload = { language: LIBRARY_LANGUAGE, version: LIBRARY_VERSION, }; var encoded = Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64'); return "Trustcaptcha/".concat(encoded); } var ApiKeyInvalidException = /** @class */ (function (_super) { __extends(ApiKeyInvalidException, _super); function ApiKeyInvalidException(message) { if (message === void 0) { message = 'The provided api key is invalid. Please verify the api key from your captcha settings.'; } var _this = _super.call(this, message) || this; _this.name = 'ApiKeyInvalidException'; Object.setPrototypeOf(_this, ApiKeyInvalidException.prototype); return _this; } return ApiKeyInvalidException; }(Error)); exports.ApiKeyInvalidException = ApiKeyInvalidException; var VerificationTokenInvalidException = /** @class */ (function (_super) { __extends(VerificationTokenInvalidException, _super); function VerificationTokenInvalidException(message) { if (message === void 0) { message = 'The verification token is malformed or could not be parsed.'; } var _this = _super.call(this, message) || this; _this.name = 'VerificationTokenInvalidException'; Object.setPrototypeOf(_this, VerificationTokenInvalidException.prototype); return _this; } return VerificationTokenInvalidException; }(Error)); exports.VerificationTokenInvalidException = VerificationTokenInvalidException; var VerificationNotFoundException = /** @class */ (function (_super) { __extends(VerificationNotFoundException, _super); function VerificationNotFoundException(message) { if (message === void 0) { message = 'No verification could be found for the given verification token.'; } var _this = _super.call(this, message) || this; _this.name = 'VerificationNotFoundException'; Object.setPrototypeOf(_this, VerificationNotFoundException.prototype); return _this; } return VerificationNotFoundException; }(Error)); exports.VerificationNotFoundException = VerificationNotFoundException; var VerificationNotFinishedException = /** @class */ (function (_super) { __extends(VerificationNotFinishedException, _super); function VerificationNotFinishedException(message) { if (message === void 0) { message = 'The verification is not yet completed. Please wait until the user has finished solving the captcha before requesting the result.'; } var _this = _super.call(this, message) || this; _this.name = 'VerificationNotFinishedException'; Object.setPrototypeOf(_this, VerificationNotFinishedException.prototype); return _this; } return VerificationNotFinishedException; }(Error)); exports.VerificationNotFinishedException = VerificationNotFinishedException; var VerificationResultExpiredException = /** @class */ (function (_super) { __extends(VerificationResultExpiredException, _super); function VerificationResultExpiredException(message) { if (message === void 0) { message = 'The verification result has expired and can no longer be retrieved.'; } var _this = _super.call(this, message) || this; _this.name = 'VerificationResultExpiredException'; Object.setPrototypeOf(_this, VerificationResultExpiredException.prototype); return _this; } return VerificationResultExpiredException; }(Error)); exports.VerificationResultExpiredException = VerificationResultExpiredException; var VerificationResultRetrievalLimitReachedException = /** @class */ (function (_super) { __extends(VerificationResultRetrievalLimitReachedException, _super); function VerificationResultRetrievalLimitReachedException(message) { if (message === void 0) { message = 'The verification result has reached its maximum retrieval count and can no longer be retrieved.'; } var _this = _super.call(this, message) || this; _this.name = 'VerificationResultRetrievalLimitReachedException'; Object.setPrototypeOf(_this, VerificationResultRetrievalLimitReachedException.prototype); return _this; } return VerificationResultRetrievalLimitReachedException; }(Error)); exports.VerificationResultRetrievalLimitReachedException = VerificationResultRetrievalLimitReachedException; var FailoverException = /** @class */ (function (_super) { __extends(FailoverException, _super); function FailoverException(message) { var _this = _super.call(this, message) || this; _this.name = 'FailoverException'; Object.setPrototypeOf(_this, FailoverException.prototype); return _this; } return FailoverException; }(Error)); exports.FailoverException = FailoverException; var ServerUnreachableException = /** @class */ (function (_super) { __extends(ServerUnreachableException, _super); function ServerUnreachableException(message) { if (message === void 0) { message = 'Could not reach the TrustCaptcha server. This is a high-trust failover signal — your backend was unable to contact our servers.'; } var _this = _super.call(this, message) || this; _this.name = 'ServerUnreachableException'; Object.setPrototypeOf(_this, ServerUnreachableException.prototype); return _this; } return ServerUnreachableException; }(FailoverException)); exports.ServerUnreachableException = ServerUnreachableException; var ClientReportedServerUnreachableException = /** @class */ (function (_super) { __extends(ClientReportedServerUnreachableException, _super); function ClientReportedServerUnreachableException(message) { if (message === void 0) { message = 'The client reported it could not reach the TrustCaptcha server, but the gateway has no record of a recent outage. Treat this with caution: a malicious client may be claiming a failover that did not happen.'; } var _this = _super.call(this, message) || this; _this.name = 'ClientReportedServerUnreachableException'; Object.setPrototypeOf(_this, ClientReportedServerUnreachableException.prototype); return _this; } return ClientReportedServerUnreachableException; }(FailoverException)); exports.ClientReportedServerUnreachableException = ClientReportedServerUnreachableException;