diff --git a/eslint.config.mjs b/eslint.config.mjs index 0e1c956204..be7cd8db19 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -445,7 +445,7 @@ export default [ }, }, { - files: [ 'tests/js/style-live-preview.test.mjs', 'tests/js/paypalBootstrap.test.mjs', 'tests/js/inlineSubmitAlignment.test.mjs', 'tests/js/squareVerifyBuyer.test.mjs' ], + files: [ 'tests/js/style-live-preview.test.mjs', 'tests/js/paypalBootstrap.test.mjs', 'tests/js/inlineSubmitAlignment.test.mjs', 'tests/js/squareVerifyBuyer.test.mjs', 'tests/js/invisibleRecaptcha.test.mjs' ], rules: { // The harnesses execute only checked-in scripts. 'sonarjs/code-eval': 'off', diff --git a/js/formidable.js b/js/formidable.js index b9df92f366..429d4f8029 100644 --- a/js/formidable.js +++ b/js/formidable.js @@ -1079,7 +1079,8 @@ function frmFrontFormJS() { const recaptcha = form.querySelector( '.frm-g-recaptcha[data-size="invisible"], .g-recaptcha[data-size="invisible"]' ); if ( recaptcha ) { const recaptchaID = recaptcha.dataset.rid; - if ( typeof grecaptcha === 'undefined' || recaptchaID === undefined ) { + // Google renders the default widget without assigning a data-rid. + if ( typeof grecaptcha === 'undefined' || ( recaptchaID === undefined && ! recaptcha.classList.contains( 'g-recaptcha' ) ) ) { return false; } diff --git a/js/formidable.min.js b/js/formidable.min.js index a74f34c3fa..bab3dc0235 100644 --- a/js/formidable.min.js +++ b/js/formidable.min.js @@ -31,7 +31,7 @@ if(""!==field.value&&pattern.test(field.value)===false)errors[fieldID]=getFieldV getFieldId(field,true);if(!(fieldID in errors))errors[fieldID]=getFieldValidationMessage(field,"data-invmsg")}}function checkPatternField(field,errors){let fieldID;const text=field.value;let format=getFieldValidationMessage(field,"pattern");if(format!==""&&text!==""){fieldID=getFieldId(field,true);if(!(fieldID in errors))if("object"===typeof window.frmProForm&&"function"===typeof window.frmProForm.isIntlPhoneInput&&window.frmProForm.isIntlPhoneInput(field)){if(!window.frmProForm.validateIntlPhoneInput(field))errors[fieldID]= getFieldValidationMessage(field,"data-invmsg")}else{format=new RegExp(`^${format}$`,"i");if(format.test(text)===false)errors[fieldID]=getFieldValidationMessage(field,"data-invmsg")}}}function setSelectPlaceholderColor(){const selects=document.querySelectorAll(".form-field select");const styleElement=document.querySelector(".with_frm_style");const textColorDisabled=styleElement?getComputedStyle(styleElement).getPropertyValue("--text-color-disabled").trim():"";if(!selects.length||!textColorDisabled)return; const changeSelectColor=function(select){if(select.options[select.selectedIndex]&&hasClass(select.options[select.selectedIndex],"frm-select-placeholder"))select.style.setProperty("color",textColorDisabled,"important");else select.style.color=""};Array.prototype.forEach.call(selects,function(select){changeSelectColor(select);select.addEventListener("change",function(){changeSelectColor(select)})})}function hasInvisibleRecaptcha(object){if(isGoingToPrevPage(object))return false;const form=object instanceof -jQuery?object.get(0):object;if(!form)return false;const recaptcha=form.querySelector('.frm-g-recaptcha[data-size="invisible"], .g-recaptcha[data-size="invisible"]');if(recaptcha){const recaptchaID=recaptcha.dataset.rid;if(typeof grecaptcha==="undefined"||recaptchaID===undefined)return false;let alreadyChecked;try{alreadyChecked=grecaptcha.getResponse(recaptchaID)}catch(e){return false}if(alreadyChecked.length===0)return recaptcha}return false}function executeInvisibleRecaptcha(invisibleRecaptcha){const recaptchaID= +jQuery?object.get(0):object;if(!form)return false;const recaptcha=form.querySelector('.frm-g-recaptcha[data-size="invisible"], .g-recaptcha[data-size="invisible"]');if(recaptcha){const recaptchaID=recaptcha.dataset.rid;if(typeof grecaptcha==="undefined"||recaptchaID===undefined&&!recaptcha.classList.contains("g-recaptcha"))return false;let alreadyChecked;try{alreadyChecked=grecaptcha.getResponse(recaptchaID)}catch(e){return false}if(alreadyChecked.length===0)return recaptcha}return false}function executeInvisibleRecaptcha(invisibleRecaptcha){const recaptchaID= invisibleRecaptcha.dataset.rid;grecaptcha.reset(recaptchaID);grecaptcha.execute(recaptchaID)}function validateRecaptcha(form,errors){const formEl=form instanceof jQuery?form.get(0):form;if(!formEl)return errors;const recaptcha=formEl.querySelector(".frm-g-recaptcha");if(!recaptcha)return errors;const recaptchaID=recaptcha.dataset.rid;let response;try{response=grecaptcha.getResponse(recaptchaID)}catch(e){if(recaptcha.dataset.saveAsSpam==="1"||formEl.querySelector('input[name="recaptcha_checked"]'))return errors; response=""}if(response.length===0){const fieldContainer=recaptcha.closest(".frm_form_field");if(fieldContainer?.id){const fieldID=fieldContainer.id.replace("frm_field_","").replace("_container","");errors[fieldID]=""}}return errors}function getFieldValidationMessage(field,messageType){let msg=field.getAttribute(messageType);if(null===msg)msg="";if(""!==msg&&shouldWrapErrorHtmlAroundMessageType(messageType))msg=wrapErrorHtml(msg,field);return msg}function wrapErrorHtml(msg,field,keyOverride=""){let errorHtml= field.getAttribute("data-error-html");if(null===errorHtml)return msg;errorHtml=errorHtml.replace(/\+/g,"%20");msg=decodeURIComponent(errorHtml).replace("[error]",msg);if(keyOverride)return msg.replace("[key]",keyOverride);const fieldId=getFieldId(field,false);const split=fieldId.split("-");const fieldIdParts=field.id.split("_");fieldIdParts.shift();split[0]=fieldIdParts.join("_");const errorKey=split.join("-");return msg.replace("[key]",errorKey)}function shouldWrapErrorHtmlAroundMessageType(type){return"pattern"!== diff --git a/tests/js/invisibleRecaptcha.test.mjs b/tests/js/invisibleRecaptcha.test.mjs new file mode 100644 index 0000000000..9746ad685b --- /dev/null +++ b/tests/js/invisibleRecaptcha.test.mjs @@ -0,0 +1,82 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; +import { runInNewContext } from 'node:vm'; + +const source = readFileSync( new URL( '../../js/formidable.js', import.meta.url ), 'utf8' ); + +/** + * Submit a form with an invisible reCAPTCHA and record what it does. + * + * @param {string} widgetClass The widget's rendering class. + * @param {string|void} widgetId The ID assigned by Formidable's explicit renderer. + * @param {Function} getResponse Returns the current response from reCAPTCHA. + * @param {Object} proForm Optional Pro form methods. + * @return {Array} Calls made to reCAPTCHA and the immediate submission handler. + */ +function submitForm( widgetClass, widgetId, getResponse, proForm ) { + const calls = []; + const widget = { + classList: { contains: name => name === widgetClass }, + dataset: { rid: widgetId } + }; + const form = { + classList: { contains: () => false }, + querySelector: selector => selector.includes( `.${ widgetClass }[data-size="invisible"]` ) ? widget : null + }; + function jQuery() { + return { ready() {}, hasClass: () => true, querySelectorAll: () => [] }; + } + const context = { + window: {}, + document: { body: { classList: { contains: () => false } } }, + jQuery, + grecaptcha: getResponse && { + getResponse: id => { + calls.push( [ 'getResponse', id ] ); + return getResponse( id ); + }, + reset: id => calls.push( [ 'reset', id ] ), + execute: id => calls.push( [ 'execute', id ] ) + }, + frmProForm: proForm + }; + + runInNewContext( source, context ); + const { frmFrontForm } = context.window; + context.frmFrontForm = frmFrontForm; + frmFrontForm.submitFormNow = () => calls.push( [ 'submit' ] ); + frmFrontForm.submitFormManual( { preventDefault() {} }, form ); + + return calls; +} + +test( 'Invisible reCAPTCHA executes the auto-rendered widget without an ID', () => { + const calls = submitForm( 'g-recaptcha', undefined, () => '' ); + + assert.deepEqual( calls, [ [ 'getResponse', undefined ], [ 'reset', undefined ], [ 'execute', undefined ] ] ); +} ); + +test( 'Invisible reCAPTCHA executes the explicitly rendered widget by ID with Pro', () => { + const calls = submitForm( 'frm-g-recaptcha', '0', () => '', { goingToPreviousPage: () => false } ); + + assert.deepEqual( calls, [ [ 'getResponse', '0' ], [ 'reset', '0' ], [ 'execute', '0' ] ] ); +} ); + +test( 'An explicit invisible widget without an ID cannot run the default widget', () => { + const calls = submitForm( 'frm-g-recaptcha', undefined, () => '' ); + + assert.deepEqual( calls, [ [ 'submit' ] ] ); +} ); + +test( 'An unavailable reCAPTCHA API allows the submission to reach server validation', () => { + assert.deepEqual( submitForm( 'g-recaptcha' ), [ [ 'submit' ] ] ); +} ); + +test( 'An auto-rendered widget that is not ready allows the submission to reach server validation', () => { + const calls = submitForm( 'g-recaptcha', undefined, () => { + throw new Error( 'No reCAPTCHA clients exist.' ); + } ); + + assert.deepEqual( calls, [ [ 'getResponse', undefined ], [ 'submit' ] ] ); +} );