UNPKG

recaptcha-node

Version:

A Node.js library to verify reCAPTCHA v2/v3 response tokens received from a client.

89 lines 3.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RecaptchaV3 = exports.RecaptchaV2 = void 0; const recaptcha_result_1 = require("./recaptcha-result"); const client_1 = require("./client"); const url_1 = require("url"); class Recaptcha { /** * * @param {string} secretKey - The secret key used for communication between * your site and reCAPTCHA. */ constructor(secretKey, options = {}) { if (typeof secretKey !== 'string') { throw new Error('A secret key must be provided.'); } this._protocol = 'https'; this.httpAgent = options.httpAgent; this.hostname = options.hostname || 'google.com'; this.protocol = options.protocol || 'https'; this.timeout = options.timeout; this.secretKey = secretKey; if (options.port) this.port = options.port; else this.port = this.protocol === 'https' ? 443 : 80; } set protocol(value) { if (value !== 'http' && value !== 'https') { throw new Error(`Protocol ${value} not supported. Expected "http" or "https"`); } this._protocol = value; } get protocol() { return this._protocol; } _getData(responseToken, remoteIP) { const searchParams = new url_1.URLSearchParams({ secret: this.secretKey, response: responseToken, remoteip: remoteIP || '', }); return searchParams.toString(); } _getClientOptions(responseToken, remoteIP) { return { hostname: this.hostname, agent: this.httpAgent, port: this.port, protocol: this.protocol, path: '/recaptcha/api/siteverify', data: this._getData(responseToken, remoteIP), timeout: this.timeout, }; } _request(responseToken, remoteIP) { const options = this._getClientOptions(responseToken, remoteIP); return client_1.request(options); } } class RecaptchaV2 extends Recaptcha { /** * Verify the reCAPTCHA v2 response token received from the client. * @param {string} responseToken - The user response token provided by the * reCAPTCHA client-side integration on your site. * @param {string} [remoteIP] - The user's IP address. */ verify(responseToken, remoteIP) { return this._request(responseToken, remoteIP).then(rawResult => { return new recaptcha_result_1.RecaptchaV2Result(rawResult); }); } } exports.RecaptchaV2 = RecaptchaV2; class RecaptchaV3 extends Recaptcha { /** * Verify the reCAPTCHA v3 response token received from the client. * @param {string} responseToken - The user response token provided by the * reCAPTCHA client-side integration on your site. * @param {string} [remoteIP] - The user's IP address. */ verify(responseToken, remoteIP) { return this._request(responseToken, remoteIP).then(rawResult => { return new recaptcha_result_1.RecaptchaV3Result(rawResult); }); } } exports.RecaptchaV3 = RecaptchaV3; //# sourceMappingURL=recaptcha.js.map