📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
some tests
Blue Mousea187270ffd1f
diff --git a/dist/captcha-validator.js b/dist/captcha-validator.jsdeleted file mode 100644index cdee3b473..000000000--- a/dist/captcha-validator.js+++ /dev/null@@ -1 +0,0 @@-!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("https")):"function"==typeof define&&define.amd?define(["exports","https"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["captcha-validator"]={},e.https)}(this,function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=n(t);function h(e,i,c,u){return new(c=c||Promise)(function(n,t){function o(e){try{a(u.next(e))}catch(e){t(e)}}function r(e){try{a(u.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?n(e.value):((t=e.value)instanceof c?t:new c(function(e){e(t)})).then(o,r)}a((u=u.apply(e,i||[])).next())})}function v(o,r){var a,i,c,u={label:0,sent:function(){if(1&c[0])throw c[1];return c[1]},trys:[],ops:[]},s={next:e(0),throw:e(1),return:e(2)};return"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function e(n){return function(e){var t=[n,e];if(a)throw new TypeError("Generator is already executing.");for(;u=s&&t[s=0]?0:u;)try{if(a=1,i&&(c=2&t[0]?i.return:t[0]?i.throw||((c=i.return)&&c.call(i),0):i.next)&&!(c=c.call(i,t[1])).done)return c;switch(i=0,(t=c?[2&t[0],c.value]:t)[0]){case 0:case 1:c=t;break;case 4:return u.label++,{value:t[1],done:!1};case 5:u.label++,i=t[1],t=[0];continue;case 7:t=u.ops.pop(),u.trys.pop();continue;default:if(!(c=0<(c=u.trys).length&&c[c.length-1])&&(6===t[0]||2===t[0])){u=0;continue}if(3===t[0]&&(!c||t[1]>c[0]&&t[1]<c[3]))u.label=t[1];else if(6===t[0]&&u.label<c[1])u.label=c[1],c=t;else{if(!(c&&u.label<c[2])){c[2]&&u.ops.pop(),u.trys.pop();continue}u.label=c[2],u.ops.push(t)}}t=r.call(o,u)}catch(e){t=[6,e],i=0}finally{a=c=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}}var y="https://api.swetrix.com/captcha",b="/validate";e.validateToken=function(u,s,l,f,d){return h(this,void 0,void 0,function(){var t,o,c;return v(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,(r=b,n="POST",a={token:u,secret:s,timestamp:l,hash:f},i=d,h(void 0,void 0,void 0,function(){var t;return v(this,function(e){return t={method:n,headers:{"Content-Type":"application/json"}},a&&(t.body=JSON.stringify(a)),[2,new Promise(function(n,o){var e="".concat(i||y).concat(r),e=p.default.request(e,t,function(e){var t="";e.on("data",function(e){t+=e}),e.on("end",function(){if(400<=e.statusCode)o("Request failed with status code ".concat(e.statusCode,": ").concat(t));else try{n(JSON.parse(t))}catch(e){o("Unable to parse JSON response: ".concat(t))}})});e.on("error",function(e){o("Unable to make API request, error: ".concat(e))}),a&&e.write(t.body),e.end()})]})}))];case 1:return t=e.sent(),[3,3];case 2:return[2,[!1,e.sent()]];case 3:return(o=t.success,c=t.data,o)?[2,[!0,c]]:[2,[!1,"CAPTCHA validation failed"]]}var r,n,a,i})})},Object.defineProperty(e,"__esModule",{value:!0})});diff --git a/dist/captcha-validator.orig.js b/dist/captcha-validator.orig.jsdeleted file mode 100644index 7dbb6d122..000000000--- a/dist/captcha-validator.orig.js+++ /dev/null@@ -1,158 +0,0 @@-(function (global, factory) {- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('https')) :- typeof define === 'function' && define.amd ? define(['exports', 'https'], factory) :- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["captcha-validator"] = {}, global.https));-})(this, (function (exports, https) { 'use strict';-- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }-- var https__default = /*#__PURE__*/_interopDefaultLegacy(https);-- /******************************************************************************- Copyright (c) Microsoft Corporation.-- Permission to use, copy, modify, and/or distribute this software for any- purpose with or without fee is hereby granted.-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR- PERFORMANCE OF THIS SOFTWARE.- ***************************************************************************** */-- function __awaiter(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());- });- }-- function __generator(thisArg, body) {- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;- return g = { next: verb(0), "throw": verb(1), "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 };- }- }-- var DEFAULT_API_HOST = 'https://api.swetrix.com/captcha';- var ENDPOINTS = {- VALIDATE: '/validate',- };- var makeAPIRequest = function (path, method, body, apiURL) { return __awaiter(void 0, void 0, void 0, function () {- var options;- return __generator(this, function (_a) {- options = {- method: method,- headers: {- 'Content-Type': 'application/json',- },- };- if (body) {- // @ts-ignore- options.body = JSON.stringify(body);- }- return [2 /*return*/, new Promise(function (resolve, reject) {- var url = "".concat(apiURL || DEFAULT_API_HOST).concat(path);- var req = https__default["default"].request(url, options, function (res) {- var data = '';- res.on('data', function (chunk) {- data += chunk;- });- res.on('end', function () {- if (res.statusCode >= 400) {- reject("Request failed with status code ".concat(res.statusCode, ": ").concat(data));- }- else {- try {- resolve(JSON.parse(data));- }- catch (e) {- reject("Unable to parse JSON response: ".concat(data));- }- }- });- });- req.on('error', function (e) {- reject("Unable to make API request, error: ".concat(e));- });- if (body) {- // @ts-ignore- req.write(options.body);- }- req.end();- })];- });- }); };-- /**- * Function to validate the CAPTCHA token.- *- * @param {string} token The CAPTCHA token.- * @param {string} secret The secret API key.- * @param {number} timestamp The timestamp of the CAPTCHA pass.- * @param {string | null} hash The hash of the CAPTCHA pass.- * @param {string | null} apiURL The API URL to use (default: https://api.swetrix.com/captcha).- * @returns {Promise<[boolean, object | null]>} The result of the validation.- */- function validateToken(token, secret, timestamp, hash, apiURL) {- return __awaiter(this, void 0, void 0, function () {- var res, e_1, success, data;- return __generator(this, function (_a) {- switch (_a.label) {- case 0:- _a.trys.push([0, 2, , 3]);- return [4 /*yield*/, makeAPIRequest(ENDPOINTS.VALIDATE, 'POST', {- token: token,- secret: secret,- timestamp: timestamp,- hash: hash,- }, apiURL)];- case 1:- res = _a.sent();- return [3 /*break*/, 3];- case 2:- e_1 = _a.sent();- return [2 /*return*/, [false, e_1]];- case 3:- success = res.success, data = res.data;- if (!success) {- return [2 /*return*/, [false, 'CAPTCHA validation failed']];- }- return [2 /*return*/, [true, data]];- }- });- });- }-- exports.validateToken = validateToken;-- Object.defineProperty(exports, '__esModule', { value: true });--}));diff --git a/package.json b/package.jsonindex 7f865d007..0197f97a8 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@swetrix/captcha-validator",- "version": "0.0.2",+ "version": "0.0.3","description": "Swetrix CAPTCHA token validator package.","main": "dist/captcha-validator.cjs.js","module": "dist/captcha-validator.es5.js",diff --git a/src/utils.ts b/src/utils.tsindex eb6a9de33..8e1d49dc6 100644--- a/src/utils.ts+++ b/src/utils.ts@@ -1,4 +1,5 @@import https from 'https'+import http from 'http'const DEFAULT_API_HOST = 'https://api.swetrix.com/captcha'@@ -7,6 +8,9 @@ export const ENDPOINTS = {}export const makeAPIRequest = async (path: string, method: string, body: object, apiURL?: string): Promise<any> => {+ const url = `${apiURL || DEFAULT_API_HOST}${path}`+ const isHTTPSUrl = url.startsWith('https://')+const options = {method,headers: {@@ -20,27 +24,49 @@ export const makeAPIRequest = async (path: string, method: string, body: object,}return new Promise((resolve, reject) => {- const url = `${apiURL || DEFAULT_API_HOST}${path}`+ let req++ if (isHTTPSUrl) {+ req = https.request(url, options, (res: any) => {+ let data = ''- const req = https.request(url, options, (res: any) => {- let data = ''+ res.on('data', (chunk: any) => {+ data += chunk+ })- res.on('data', (chunk: any) => {- data += chunk+ res.on('end', () => {+ if (res.statusCode >= 400) {+ reject(`Request failed with status code ${res.statusCode}: ${data}`)+ } else {+ try {+ resolve(JSON.parse(data))+ } catch (e) {+ reject(`Unable to parse JSON response: ${data}`)+ }+ }+ })})+ } else {+ req = http.request(url, options, (res: any) => {+ let data = ''- res.on('end', () => {- if (res.statusCode >= 400) {- reject(`Request failed with status code ${res.statusCode}: ${data}`)- } else {- try {- resolve(JSON.parse(data))- } catch (e) {- reject(`Unable to parse JSON response: ${data}`)+ res.on('data', (chunk: any) => {+ data += chunk+ })++ res.on('end', () => {+ if (res.statusCode >= 400) {+ reject(`Request failed with status code ${res.statusCode}: ${data}`)+ } else {+ try {+ resolve(JSON.parse(data))+ } catch (e) {+ reject(`Unable to parse JSON response: ${data}`)+ }}- }+ })})- })+ }req.on('error', (e) => {reject(`Unable to make API request, error: ${e}`)