diff --git a/.gitattributes b/.gitattributes
index af3ad1281..78644f7db 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -2,3 +2,5 @@
/.yarn/releases/* binary
/.yarn/plugins/**/* binary
/.pnp.* binary linguist-generated
+/.githooks/* text eol=lf
+/.github/scripts/*.sh text eol=lf
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
new file mode 100644
index 000000000..60aabe10a
--- /dev/null
+++ b/.githooks/pre-commit
@@ -0,0 +1,18 @@
+#!/bin/sh
+
+set -eu
+
+cd "$(git rev-parse --show-toplevel)"
+
+if git diff --cached --quiet -- readme.txt changelog.txt; then
+ exit 0
+fi
+
+if ! git diff --quiet -- changelog.txt; then
+ echo "Stage or restore changes in changelog.txt before committing." >&2
+ exit 1
+fi
+
+php_binary=$(git config --get hcaptcha.phpPath || echo php)
+"$php_binary" .github/scripts/update-changelog.php --staged
+git add -- changelog.txt
diff --git a/.githooks/pre-push b/.githooks/pre-push
deleted file mode 100644
index e65b10c0b..000000000
--- a/.githooks/pre-push
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/bin/bash
-
-.github/scripts/update-changelog.sh
-
-# Intercept exit code from the previous command.
-exitCode="$?"
-
-echo ''
-exit $exitCode
diff --git a/.githooks/setup.php b/.githooks/setup.php
new file mode 100644
index 000000000..c86e142a2
--- /dev/null
+++ b/.githooks/setup.php
@@ -0,0 +1,35 @@
+getMessage() . "\n" );
+
+ return 1;
+ }
+
+ echo "Changelog generated from readme.txt.\n";
+
+ return 0;
+}
+
+if ( isset( $argv[0] ) && realpath( $argv[0] ) === __FILE__ ) {
+ exit( hcaptcha_update_changelog( array_slice( $argv, 1 ) ) );
+}
diff --git a/.github/scripts/update-changelog.sh b/.github/scripts/update-changelog.sh
index a9ddb6ae1..21db1ef0e 100755
--- a/.github/scripts/update-changelog.sh
+++ b/.github/scripts/update-changelog.sh
@@ -1,54 +1,6 @@
-#!/bin/bash
+#!/bin/sh
-# Check if readme.txt exists
-if [ ! -f readme.txt ]; then
- echo "readme.txt file not found!"
- exit 1
-fi
+set -eu
-# Determine the latest changelog version in readme.txt
-latest_version=$(sed -n 's/^= \([0-9]\+\.[0-9]\+\.[0-9]\+\) =$/\1/p' readme.txt | head -n 1)
-
-if [ -z "$latest_version" ]; then
- echo "No latest version found in readme.txt!"
- exit 0
-fi
-
-# Get the latest changelog section from readme.txt
-latest_section=$(sed -n "/^= $latest_version =$/,/^= [0-9]\+\.[0-9]\+\.[0-9]\+ =$/ { /^= [0-9]\+\.[0-9]\+\.[0-9]\+ =$/!p; }" readme.txt)
-latest_section="= ${latest_version} =\n${latest_section}\n"
-
-# Remove the latest changelog section from changelog.txt
-sed -i "/^= $latest_version =$/,/^= [0-9]\+\.[0-9]\+\.[0-9]\+ =$/ {/^= $latest_version =$/d; /^= [0-9]\+\.[0-9]\+\.[0-9]\+ =$/!d;}" changelog.txt
-
-# Append the latest changelog section from readme.txt to changelog.txt
-{ echo -e "$latest_section"; cat changelog.txt; } > temp.txt && mv temp.txt changelog.txt
-
-# Generate the file without changing Git configuration, committing, or pushing.
-if [ "${1:-}" = "--generate-only" ]; then
- echo "Changelog generated from readme.txt."
- exit 0
-fi
-
-# Check if there are changes in changelog.txt
-if git diff --quiet changelog.txt; then
- echo "No changes in changelog.txt."
- exit 0
-fi
-
-# Configure Git commit information
-git config --global user.email "gha@hcaptcha.com"
-git config --global user.name "hCaptcha GHA"
-
-# Add, commit, and push changes
-git add changelog.txt
-git commit -m "Update changelog from readme.txt"
-
-# Check if running in CI environment
-if [ -n "$CI" ]; then
- # Push changes if in CI environment
- git push
- echo "Changelog successfully updated and pushed to the repository."
-else
- echo "Changelog updated locally. Skipping push."
-fi
+php_binary=$(git config --get hcaptcha.phpPath || echo php)
+"$php_binary" "$(dirname "$0")/update-changelog.php" "$@"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index fd826cb72..da793b5e4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -5,20 +5,32 @@ on:
paths:
- '**/*.php'
- 'composer.*'
+ - '.php-scoper/**'
- 'package.json'
- 'yarn.lock'
- 'src/**'
- 'tests/**'
- '.github/workflows/**'
+ - '.github/scripts/**'
+ - '.githooks/**'
+ - '.gitattributes'
+ - 'readme.txt'
+ - 'changelog.txt'
pull_request:
paths:
- '**/*.php'
- 'composer.*'
+ - '.php-scoper/**'
- 'package.json'
- 'yarn.lock'
- 'src/**'
- 'tests/**'
- '.github/workflows/**'
+ - '.github/scripts/**'
+ - '.githooks/**'
+ - '.gitattributes'
+ - 'readme.txt'
+ - 'changelog.txt'
# 1. SECURITY: Default to read-only permissions for the workflow
permissions:
@@ -32,7 +44,7 @@ concurrency:
jobs:
phpcs:
name: PHPCS
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
env:
wp-plugin-directory: wordpress/wp-content/plugins/hcaptcha-wordpress-plugin
@@ -49,8 +61,6 @@ jobs:
path: ${{ env.wp-plugin-directory }}
persist-credentials: false
- # MOVED: The "Update changelog" step has been moved to the specific job below
- # to prevent giving 'contents: write' permissions to this testing job.
- name: Setup PHP 8.5
uses: hCaptcha/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # v2.37.0
with:
@@ -69,7 +79,7 @@ jobs:
js:
name: JS lint and tests
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
if: |
github.event_name == 'workflow_dispatch' ||
@@ -105,7 +115,7 @@ jobs:
php_versions:
name: Resolve PHP versions
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
if: |
github.event_name == 'workflow_dispatch' ||
@@ -116,14 +126,8 @@ jobs:
matrix: ${{ steps.resolve.outputs.matrix }}
env:
- FULL_PHP_MATRIX: >-
- ${{
- github.event_name == 'push' &&
- (
- github.ref == 'refs/heads/master' ||
- contains(github.event.head_commit.message || '', '[all]')
- )
- }}
+ # Temporarily test every supported PHP version on all branch pushes.
+ FULL_PHP_MATRIX: ${{ github.event_name == 'push' }}
steps:
- name: Resolve PHP versions
@@ -137,7 +141,7 @@ jobs:
unit:
name: Unit tests on PHP ${{ matrix.php-version }}
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
needs: php_versions
strategy:
@@ -172,7 +176,7 @@ jobs:
integration:
name: WP integration tests on PHP ${{ matrix.php-version }} (${{ matrix.shard }}/2)
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
needs: php_versions
strategy:
@@ -220,8 +224,8 @@ jobs:
extensions: json, mysqli, mbstring, zip
ini-values: register_argc_argv=On
- - name: Detect Really Simple CAPTCHA support
- id: really_simple_captcha
+ - name: Detect Contact Form 7 support
+ id: cf7
run: |
if php -r 'exit(version_compare(PHP_VERSION, "8.3", ">=") ? 0 : 1);'; then
echo "supported=true" >> "$GITHUB_OUTPUT"
@@ -304,8 +308,10 @@ jobs:
working-directory: ${{ env.wp-directory }}
env:
SHARD_DEPENDENCIES: ${{ steps.shard_dependencies.outputs.json }}
+ CF7_SUPPORTED: ${{ steps.cf7.outputs.supported }}
+ PHP_VERSION: ${{ matrix.php-version }}
run: |
- mapfile -t plugins < <(jq -r '.public_plugins[]' <<< "$SHARD_DEPENDENCIES")
+ mapfile -t plugins < <(jq -r --arg supported "$CF7_SUPPORTED" --arg php "$PHP_VERSION" '.public_plugins[] | select(. != "contact-form-7" or $supported == "true") | select(. != "easy-digital-downloads" or $php != "7.4")' <<< "$SHARD_DEPENDENCIES")
mapfile -t themes < <(jq -r '.public_themes[]' <<< "$SHARD_DEPENDENCIES")
if (( ${#plugins[@]} )); then
@@ -315,13 +321,19 @@ jobs:
done
fi
+ # EDD 3.7+ requires PHP 8.0; keep the PHP 7.4 job on its last compatible release.
+ if [[ "$PHP_VERSION" == "7.4" ]] && jq -e '.public_plugins | index("easy-digital-downloads") != null' <<< "$SHARD_DEPENDENCIES" > /dev/null; then
+ wp plugin install easy-digital-downloads --version=3.6.9.1
+ wp plugin is-installed easy-digital-downloads
+ fi
+
for theme in "${themes[@]}"; do
wp theme install "$theme"
wp theme is-installed "$theme"
done
- name: Install Really Simple CAPTCHA
- if: steps.really_simple_captcha.outputs.supported == 'true' && steps.shard_dependencies.outputs.needs_really_simple_captcha == 'true'
+ if: steps.cf7.outputs.supported == 'true' && steps.shard_dependencies.outputs.needs_really_simple_captcha == 'true'
working-directory: ${{ env.wp-directory }}
run: |
wp plugin install really-simple-captcha
@@ -374,9 +386,9 @@ jobs:
wp plugin is-installed bb-plugin
echo "available=true" >> "$GITHUB_OUTPUT"
- - name: Generate changelog for tests
+ - name: Check changelog for tests
working-directory: ${{ env.wp-plugin-directory }}
- run: .github/scripts/update-changelog.sh --generate-only
+ run: composer changelog:check
- name: Run WP tests with private test plugins
if: steps.test_plugins.outputs.available == 'true'
@@ -384,14 +396,19 @@ jobs:
run: |
integration_args=()
- if [[ "${{ steps.really_simple_captcha.outputs.supported }}" != "true" ]]; then
- integration_args+=(--skip-group cf7-really-simple-captcha)
+ if [[ "${{ steps.cf7.outputs.supported }}" != "true" ]]; then
+ integration_args+=(--skip-group cf7)
fi
if [[ "${{ steps.beaver_builder.outputs.available }}" != "true" ]]; then
integration_args+=(--skip-group beaver-builder)
fi
+ # Codeception 4 cannot bootstrap WordPress in PHPUnit's isolated PHP 7.4 process.
+ if [[ "${{ matrix.php-version }}" == "7.4" ]]; then
+ integration_args+=(--skip-group process-isolation-php74)
+ fi
+
composer integration:parallel -- --shard=${{ matrix.shard }}/2 --env github-actions "${integration_args[@]}"
- name: Run WP tests without private test plugins
@@ -400,8 +417,13 @@ jobs:
run: |
integration_args=(--skip-group acfe --skip-group avada --skip-group beaver-builder --skip-group divi --skip-group elementor-pro --skip-group gravityforms --skip-group ultimate-addons)
- if [[ "${{ steps.really_simple_captcha.outputs.supported }}" != "true" ]]; then
- integration_args+=(--skip-group cf7-really-simple-captcha)
+ if [[ "${{ steps.cf7.outputs.supported }}" != "true" ]]; then
+ integration_args+=(--skip-group cf7)
+ fi
+
+ # Codeception 4 cannot bootstrap WordPress in PHPUnit's isolated PHP 7.4 process.
+ if [[ "${{ matrix.php-version }}" == "7.4" ]]; then
+ integration_args+=(--skip-group process-isolation-php74)
fi
composer integration:parallel -- --shard=${{ matrix.shard }}/2 --env github-actions "${integration_args[@]}"
@@ -410,30 +432,3 @@ jobs:
if: matrix.shard == 1
working-directory: ${{ env.wp-plugin-directory }}
run: composer integration:multisite -- --env github-actions
-
- update_changelog:
- name: Update Changelog
- runs-on: ubuntu-latest
-
- # 2. SECURITY: Only run on PUSH, never on Pull Requests
- if: github.event_name == 'push'
- needs: [ phpcs, js, unit, integration ]
-
- # 3. SECURITY: Grant write permission ONLY to this job
- permissions:
- contents: write
-
- env:
- wp-plugin-directory: wordpress/wp-content/plugins/hcaptcha-wordpress-plugin
-
- steps:
- - name: Checkout code
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- with:
- path: ${{ env.wp-plugin-directory }}
- # Check out the branch ref to ensure we can push back to it
- ref: ${{ github.ref }}
-
- - name: Update changelog
- working-directory: ${{ env.wp-plugin-directory }}
- run: .github/scripts/update-changelog.sh
diff --git a/.github/workflows/create-zip.yml b/.github/workflows/create-zip.yml
index 6d15817d1..7be7ee12b 100644
--- a/.github/workflows/create-zip.yml
+++ b/.github/workflows/create-zip.yml
@@ -11,7 +11,7 @@ permissions:
jobs:
build-zip:
name: New zip file
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
# Security: 1. Check for [zip] tag. 2. Check if user is authorized.
if: |
diff --git a/.github/workflows/deploy-readme-assets-to-wp-org.yml b/.github/workflows/deploy-readme-assets-to-wp-org.yml
index 690c851e7..4bd72b50b 100644
--- a/.github/workflows/deploy-readme-assets-to-wp-org.yml
+++ b/.github/workflows/deploy-readme-assets-to-wp-org.yml
@@ -9,7 +9,7 @@ permissions:
jobs:
trunk:
name: Push to trunk
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
steps:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
diff --git a/.github/workflows/deploy-to-wp-org.yml b/.github/workflows/deploy-to-wp-org.yml
index 72cc0c5c8..7b987d9ca 100644
--- a/.github/workflows/deploy-to-wp-org.yml
+++ b/.github/workflows/deploy-to-wp-org.yml
@@ -9,7 +9,7 @@ jobs:
tag:
name: New release
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
# Security: 1. Check if user is authorized.
if: contains(fromJson('["kagg-design", "e271828-"]'), github.actor)
diff --git a/.gitignore b/.gitignore
index cacd06d94..f7820ba01 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,6 +13,7 @@ assets/js/**/*.min.js.map
build/
CLAUDE-SECURITY-*/
coverage/
+docs/security/
docs/tasks/
node_modules/
vendor/
diff --git a/.php-scoper/composer.json b/.php-scoper/composer.json
index 7a8542cbf..254546efe 100644
--- a/.php-scoper/composer.json
+++ b/.php-scoper/composer.json
@@ -2,9 +2,6 @@
"require": {
"humbug/php-scoper": "0.17.5 - 0.18.18"
},
- "require-dev": {
- "roave/security-advisories": "dev-latest"
- },
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
diff --git a/.php-scoper/hcaptcha-wordpress-plugin-scoper.php b/.php-scoper/hcaptcha-wordpress-plugin-scoper.php
index f08838d0c..e1a5061e7 100644
--- a/.php-scoper/hcaptcha-wordpress-plugin-scoper.php
+++ b/.php-scoper/hcaptcha-wordpress-plugin-scoper.php
@@ -53,9 +53,13 @@ static function ( string $file_path, string $prefix, string $content ): string {
}
if ( false !== strpos( $file_path, 'matthiasmullie/minify/src/JS.php' ) ) {
+ // Match the entire unscoped literal to avoid prefixing an already scoped callback.
return str_replace(
- '\\\MatthiasMullie\\\Minify\\\Minify',
- '\\' . $prefix . '\MatthiasMullie\Minify\Minify',
+ [
+ "'\\\\MatthiasMullie\\\\Minify\\\\Minify'",
+ "'\\MatthiasMullie\\Minify\\Minify'",
+ ],
+ "'" . $prefix . "\\MatthiasMullie\\Minify\\Minify'",
$content
);
}
diff --git a/AGENTS.md b/AGENTS.md
index 90da7fea0..e1fa1253a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -60,4 +60,5 @@ $subject->shouldAllowMockingProtectedMethods();
## Changelog
- When adding release notes about completed work, update the current version under `== Changelog ==` in `readme.txt`.
-- Do not edit `changelog.txt` manually. CI generates and updates it from the changelog in `readme.txt`.
+- Do not edit `changelog.txt` manually. The pre-commit Git hook generates and stages it from the staged changelog in `readme.txt`. Composer install/update enables the hooks; run `composer hooks:install` when using an existing checkout or a new worktree without installing dependencies.
+- Before testing uncommitted release-note changes, run `composer changelog`. CI checks that `changelog.txt` is current without changing or pushing it.
diff --git a/README.md b/README.md
index 8b953b77f..d044ba26a 100644
--- a/README.md
+++ b/README.md
@@ -34,6 +34,15 @@ yarn
yarn dev
```
+Composer install/update enables the repository's Git hooks in local checkouts and
+worktrees. For an existing checkout, or a cloud environment that reuses installed
+dependencies, run `composer hooks:install` during environment setup.
+
+The pre-commit hook generates and stages `changelog.txt` from the staged release notes
+in `readme.txt`, so both files are included in the same commit. Before running tests
+with uncommitted release-note changes, run `composer changelog`. CI verifies the
+generated file with `composer changelog:check`.
+
1. Sign up at [hCaptcha.com](https://www.hcaptcha.com/) to get a site key and secret.
2. Activate the plugin through the 'Plugins' menu in WordPress
3. Enter your Site Key and SECRET in the Settings -> hCaptcha menu in WordPress
diff --git a/assets/css/advanced.css b/assets/css/advanced.css
new file mode 100644
index 000000000..4cecd7f04
--- /dev/null
+++ b/assets/css/advanced.css
@@ -0,0 +1,286 @@
+#hcaptcha-options.hcaptcha-advanced h3 {
+ display: flex;
+ justify-content: space-between;
+ max-width: 760px;
+ box-sizing: border-box;
+ padding: 15px 20px;
+ margin: 1.5em 0 0;
+ background: #fff;
+ color: #5c6f8a;
+ cursor: pointer;
+}
+
+#hcaptcha-options.hcaptcha-advanced h3.disabled,
+#hcaptcha-options.hcaptcha-advanced h3.disabled + table {
+ opacity: 0.6;
+}
+
+#hcaptcha-options.hcaptcha-advanced h3 + table {
+ max-width: 760px;
+ margin-top: 0;
+ position: relative;
+}
+
+#hcaptcha-options.hcaptcha-advanced h3 + table::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ width: calc(100% - 40px);
+ max-width: 720px;
+ margin: 0 20px;
+ border-bottom: 1px solid #c3c4c7;
+}
+
+#hcaptcha-options.hcaptcha-advanced h3 + table tbody {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ padding: 15px 20px;
+ background: #fff;
+}
+
+#hcaptcha-options.hcaptcha-advanced h3 + table tbody tr {
+ display: grid;
+ align-self: start;
+}
+
+#hcaptcha-options.hcaptcha-advanced h3 + table tbody th {
+ width: auto;
+ padding: 0 0 10px;
+ color: #5c6f8a;
+}
+
+#hcaptcha-options.hcaptcha-advanced h3 + table tbody th:empty {
+ padding: 0;
+}
+
+#hcaptcha-options.hcaptcha-advanced h3 + table tbody td input[type="text"],
+#hcaptcha-options.hcaptcha-advanced h3 + table tbody td input[type="number"],
+#hcaptcha-options.hcaptcha-advanced h3 + table tbody td textarea {
+ width: 100%;
+ box-sizing: border-box;
+}
+
+#hcaptcha-options.hcaptcha-advanced .hcaptcha-section-header-toggle::after {
+ content: "\f142";
+ font: normal 20px dashicons;
+ -webkit-font-smoothing: antialiased;
+}
+
+#hcaptcha-options.hcaptcha-advanced h3.closed .hcaptcha-section-header-toggle::after {
+ content: "\f140";
+}
+
+/* Section Enterprise */
+.hcaptcha-section-enterprise + table tbody {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 10px 20px;
+ padding: 15px 20px;
+}
+
+.hcaptcha-section-enterprise + table tbody th {
+ width: auto;
+}
+
+.hcaptcha-section-enterprise + table tbody tr th {
+ padding: 0 0 10px 0;
+}
+
+.hcaptcha-section-enterprise + table tbody tr td input {
+ width: 100%;
+}
+
+/* Section Protect Content */
+.hcaptcha-section-content + table tbody {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-template-areas:
+ "content protected-urls";
+ gap: 0 20px;
+ padding: 15px 20px;
+}
+
+.hcaptcha-section-content + table tbody tr.hcaptcha-advanced-content {
+ grid-area: content;
+}
+
+.hcaptcha-section-content + table tbody tr.hcaptcha-advanced-protected-urls {
+ grid-area: protected-urls;
+}
+
+.hcaptcha-section-content + table tbody tr th {
+ padding: 0 0 10px 0;
+ width: auto;
+}
+
+.hcaptcha-section-content + table tbody tr td {
+ width: max-content;
+}
+
+.hcaptcha-section-content + table tbody tr.hcaptcha-advanced-protected-urls td {
+ width: auto;
+}
+
+.hcaptcha-section-content + table tbody tr td textarea,
+.hcaptcha-section-content + table tbody tr td input {
+ width: 100%;
+}
+
+
+/* Section Other */
+.hcaptcha-section-other + table tbody {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-template-areas:
+ "logged delay"
+ "recaptcha delay"
+ "cleanup-on-uninstall ajax"
+ ". network";
+ gap: 0 20px;
+ padding: 15px 20px;
+}
+
+.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-delay {
+ grid-area: delay;
+}
+
+.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-off-when-logged-in {
+ grid-area: logged;
+}
+
+.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-ajax-forms {
+ grid-area: ajax;
+}
+
+.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-recaptcha-compat-off {
+ grid-area: recaptcha;
+}
+
+.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-cleanup-on-uninstall {
+ grid-area: cleanup-on-uninstall;
+}
+
+.hcaptcha-section-other + table tbody tr.hcaptcha-advanced--network-wide {
+ grid-area: network;
+}
+
+.hcaptcha-section-other + table tbody tr th {
+ padding: 0 0 10px 0;
+ width: auto;
+}
+
+.hcaptcha-section-other + table tbody tr td {
+ width: max-content;
+}
+
+.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-delay td {
+ width: auto;
+}
+
+.hcaptcha-section-other + table tbody tr td input {
+ width: 100%;
+}
+
+/* Section Statistics */
+.hcaptcha-section-statistics + table tbody {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-template-areas:
+ "statistics collect-ip"
+ "anonymous collect-ua";
+ gap: 0 20px;
+ padding: 15px 20px;
+}
+
+.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics {
+ grid-area: statistics;
+}
+
+.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-anonymous {
+ grid-area: anonymous;
+}
+
+.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-collect-ip {
+ grid-area: collect-ip;
+}
+
+.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-collect-ua {
+ grid-area: collect-ua;
+}
+
+.hcaptcha-section-statistics + table tbody tr th {
+ padding: 0 0 10px 0;
+ width: auto;
+}
+
+.hcaptcha-section-statistics + table tbody tr td {
+ width: max-content;
+}
+
+.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics td {
+ width: max-content;
+ min-width: 0;
+}
+
+.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics .helper-content {
+ max-width: calc(100vw - 40px);
+ white-space: normal;
+ overflow-wrap: anywhere;
+ line-height: 1.5;
+}
+
+@media (max-width: 600px) {
+ #hcaptcha-options.hcaptcha-advanced h3 + table tbody {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ .hcaptcha-section-enterprise + table tbody {
+ grid-template-columns: repeat(1, 1fr) !important;
+ }
+
+ .hcaptcha-section-enterprise + table tbody tr td {
+ width: unset !important;
+ }
+
+ .hcaptcha-section-content + table tbody {
+ grid-template-columns: repeat(1, 1fr);
+ grid-template-areas:
+ "content"
+ "protected-urls";
+ }
+
+ .hcaptcha-section-content + table tbody tr td {
+ width: unset !important;
+ }
+
+ .hcaptcha-section-other + table tbody {
+ grid-template-columns: repeat(1, 1fr) !important;
+ grid-template-areas:
+ "delay"
+ "logged"
+ "recaptcha"
+ "cleanup-on-uninstall"
+ "ajax"
+ "network";
+ }
+
+ .hcaptcha-section-other + table tbody tr td {
+ width: unset !important;
+ }
+
+ .hcaptcha-section-statistics + table tbody {
+ grid-template-columns: repeat(1, 1fr);
+ grid-template-areas:
+ "statistics"
+ "anonymous"
+ "collect-ip"
+ "collect-ua";
+ }
+
+ .hcaptcha-section-statistics + table tbody tr td {
+ width: unset !important;
+ }
+
+ .hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics td {
+ width: max-content !important;
+ }
+}
diff --git a/assets/css/general.css b/assets/css/general.css
index 585d9a3dc..e620e1f28 100644
--- a/assets/css/general.css
+++ b/assets/css/general.css
@@ -13,6 +13,10 @@
align-self: start;
}
+#hcaptcha-options table tbody tr.hidden {
+ display: none;
+}
+
#hcaptcha-options table tbody tr th {
color: #5c6f8a;
}
@@ -83,7 +87,8 @@ h3.closed .hcaptcha-section-header-toggle:after {
grid-template-columns: repeat(4, 1fr);
grid-template-areas:
"site-key site-key secret-key secret-key"
- "sample-hcaptcha sample-hcaptcha check-config reset-notifications";
+ "sample-hcaptcha sample-hcaptcha mode mode"
+ "check-config check-config reset-notifications reset-notifications";
gap: 10px 20px;
padding: 15px 20px;
}
@@ -96,6 +101,15 @@ h3.closed .hcaptcha-section-header-toggle:after {
grid-area: site-key;
}
+.hcaptcha-section-keys + table tbody tr.hcaptcha-general-mode {
+ grid-area: mode;
+}
+
+.hcaptcha-section-keys + table tbody tr.hcaptcha-general-mode td select {
+ width: 100%;
+ max-width: none;
+}
+
.hcaptcha-section-keys + table tbody tr.hcaptcha-general-secret-key {
grid-area: secret-key;
}
@@ -108,10 +122,20 @@ h3.closed .hcaptcha-section-header-toggle:after {
grid-area: check-config;
}
-.hcaptcha-section-keys + table tbody tr.hcaptcha-reset-notifications {
+.hcaptcha-section-keys + table tbody tr.hcaptcha-general-reset-notifications {
grid-area: reset-notifications;
}
+.hcaptcha-section-keys + table tbody tr.hcaptcha-general-check-config th,
+.hcaptcha-section-keys + table tbody tr.hcaptcha-general-reset-notifications th {
+ display: none;
+}
+
+.hcaptcha-section-keys + table tbody tr.hcaptcha-general-check-config td,
+.hcaptcha-section-keys + table tbody tr.hcaptcha-general-reset-notifications td {
+ padding: 0;
+}
+
.hcaptcha-section-keys + table tbody tr.hcaptcha-general-site-key .helper,
.hcaptcha-section-keys + table tbody tr.hcaptcha-general-secret-key .helper {
display: none;
@@ -135,10 +159,10 @@ h3.closed .hcaptcha-section-header-toggle:after {
/* Section Appearance */
.hcaptcha-section-appearance + table tbody {
display: grid;
- grid-template-columns: repeat(4, 1fr);
+ grid-template-columns: repeat(3, minmax(0, 1fr));
grid-template-areas:
- "theme size language mode"
- "force force position position";
+ "theme size language"
+ "force position .";
gap: 10px 20px;
padding: 15px 20px;
}
@@ -155,10 +179,6 @@ h3.closed .hcaptcha-section-header-toggle:after {
grid-area: language;
}
-.hcaptcha-section-appearance + table tbody tr.hcaptcha-general-mode {
- grid-area: mode;
-}
-
.hcaptcha-section-appearance + table tbody tr.hcaptcha-general-force {
grid-area: force;
}
@@ -1031,177 +1051,6 @@ h3.closed .hcaptcha-section-header-toggle:after {
background: var(--hcap-verify-fill);
}
-/* Section Enterprise */
-.hcaptcha-section-enterprise + table tbody {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: 10px 20px;
- padding: 15px 20px;
-}
-
-.hcaptcha-section-enterprise + table tbody th {
- width: auto;
-}
-
-.hcaptcha-section-enterprise + table tbody tr th {
- padding: 0 0 10px 0;
-}
-
-.hcaptcha-section-enterprise + table tbody tr td input {
- width: 100%;
-}
-
-/* Section Protect Content */
-.hcaptcha-section-content + table tbody {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- grid-template-areas:
- "content protected-urls";
- gap: 0 20px;
- padding: 15px 20px;
-}
-
-.hcaptcha-section-content + table tbody tr.hcaptcha-general-content {
- grid-area: content;
-}
-
-.hcaptcha-section-content + table tbody tr.hcaptcha-general-protected-urls {
- grid-area: protected-urls;
-}
-
-.hcaptcha-section-content + table tbody tr th {
- padding: 0 0 10px 0;
- width: auto;
-}
-
-.hcaptcha-section-content + table tbody tr td {
- width: max-content;
-}
-
-.hcaptcha-section-content + table tbody tr.hcaptcha-general-protected-urls td {
- width: auto;
-}
-
-.hcaptcha-section-content + table tbody tr td textarea,
-.hcaptcha-section-content + table tbody tr td input {
- width: 100%;
-}
-
-
-/* Section Other */
-.hcaptcha-section-other + table tbody {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- grid-template-areas:
- "logged delay"
- "recaptcha delay"
- "cleanup-on-uninstall ajax"
- ". network";
- gap: 0 20px;
- padding: 15px 20px;
-}
-
-.hcaptcha-section-other + table tbody tr.hcaptcha-general-delay {
- grid-area: delay;
-}
-
-.hcaptcha-section-other + table tbody tr.hcaptcha-general-off-when-logged-in {
- grid-area: logged;
-}
-
-.hcaptcha-section-other + table tbody tr.hcaptcha-general-ajax-forms {
- grid-area: ajax;
-}
-
-.hcaptcha-section-other + table tbody tr.hcaptcha-general-recaptcha-compat-off {
- grid-area: recaptcha;
-}
-
-.hcaptcha-section-other + table tbody tr.hcaptcha-general-cleanup-on-uninstall {
- grid-area: cleanup-on-uninstall;
-}
-
-.hcaptcha-section-other + table tbody tr.hcaptcha-general--network-wide {
- grid-area: network;
-}
-
-.hcaptcha-section-other + table tbody tr th {
- padding: 0 0 10px 0;
- width: auto;
-}
-
-.hcaptcha-section-other + table tbody tr.hcaptcha-general-ajax-forms th,
-.hcaptcha-section-other + table tbody tr.hcaptcha-general-recaptcha-compat-off th,
-.hcaptcha-section-other + table tbody tr.hcaptcha-general-cleanup-on-uninstall th,
-.hcaptcha-section-other + table tbody tr.hcaptcha-general--network-wide th {
- padding: 0;
-}
-
-.hcaptcha-section-other + table tbody tr td {
- width: max-content;
-}
-
-.hcaptcha-section-other + table tbody tr.hcaptcha-general-delay td {
- width: auto;
-}
-
-.hcaptcha-section-other + table tbody tr td input {
- width: 100%;
-}
-
-/* Section Statistics */
-.hcaptcha-section-statistics + table tbody {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- grid-template-areas:
- "statistics collect-ip"
- "anonymous collect-ua";
- gap: 0 20px;
- padding: 15px 20px;
-}
-
-.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics {
- grid-area: statistics;
-}
-
-.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-anonymous {
- grid-area: anonymous;
-}
-
-.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-collect-ip {
- grid-area: collect-ip;
-}
-
-.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-collect-ua {
- grid-area: collect-ua;
-}
-
-.hcaptcha-section-statistics + table tbody tr th {
- padding: 0 0 10px 0;
- width: auto;
-}
-
-.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-anonymous th,
-.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-collect-ua th {
- padding: 0;
-}
-
-.hcaptcha-section-statistics + table tbody tr td {
- width: max-content;
-}
-
-.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics td {
- width: max-content;
- min-width: 0;
-}
-
-.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics .helper-content {
- max-width: calc(100vw - 40px);
- white-space: normal;
- overflow-wrap: anywhere;
- line-height: 1.5;
-}
-
@media (max-width: 900px) {
.hcaptcha-theme-editor {
top: 52px;
@@ -1245,6 +1094,7 @@ h3.closed .hcaptcha-section-header-toggle:after {
"site-key site-key"
"secret-key secret-key"
"sample-hcaptcha sample-hcaptcha"
+ "mode mode"
"check-config reset-notifications";
}
@@ -1252,7 +1102,7 @@ h3.closed .hcaptcha-section-header-toggle:after {
grid-template-columns: repeat(2, 1fr) !important;
grid-template-areas:
"theme size"
- "language mode"
+ "language ."
"force force"
"position position";
}
@@ -1338,54 +1188,4 @@ h3.closed .hcaptcha-section-header-toggle:after {
justify-content: flex-start;
}
- .hcaptcha-section-enterprise + table tbody {
- grid-template-columns: repeat(1, 1fr) !important;
- }
-
- .hcaptcha-section-enterprise + table tbody tr td {
- width: unset !important;
- }
-
- .hcaptcha-section-content + table tbody {
- grid-template-columns: repeat(1, 1fr);
- grid-template-areas:
- "content"
- "protected-urls";
- }
-
- .hcaptcha-section-content + table tbody tr td {
- width: unset !important;
- }
-
- .hcaptcha-section-other + table tbody {
- grid-template-columns: repeat(1, 1fr) !important;
- grid-template-areas:
- "delay"
- "logged"
- "recaptcha"
- "cleanup-on-uninstall"
- "ajax"
- "network";
- }
-
- .hcaptcha-section-other + table tbody tr td {
- width: unset !important;
- }
-
- .hcaptcha-section-statistics + table tbody {
- grid-template-columns: repeat(1, 1fr);
- grid-template-areas:
- "statistics"
- "anonymous"
- "collect-ip"
- "collect-ua";
- }
-
- .hcaptcha-section-statistics + table tbody tr td {
- width: unset !important;
- }
-
- .hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics td {
- width: max-content !important;
- }
}
diff --git a/assets/css/integrations.css b/assets/css/integrations.css
index dfd884c32..e19879e58 100644
--- a/assets/css/integrations.css
+++ b/assets/css/integrations.css
@@ -1,12 +1,3 @@
-.form-table:first-of-type tr {
- background: none;
- padding: 10px 0;
-}
-
-.form-table:first-of-type tr th {
- display: none;
-}
-
#hcaptcha-options p {
margin: 0.5em 0;
}
@@ -252,19 +243,6 @@
display: none;
}
-/* Antispam indicators toggle */
-#hcaptcha-options .hcaptcha-integrations-show-antispam-coverage td {
- width: max-content;
-}
-
-#hcaptcha-options .hcaptcha-integrations-show-antispam-coverage fieldset:disabled {
- color: #a9a9a9;
-}
-
-#hcaptcha-options .hcaptcha-integrations-show-antispam-coverage fieldset:disabled+.helper::before {
- opacity: 0.7;
-}
-
/* Antispam indicators help icon */
.hcaptcha-antispam-help {
font-size: 18px;
diff --git a/assets/css/notifications.css b/assets/css/notifications.css
index f67165d1a..1bf1e883e 100644
--- a/assets/css/notifications.css
+++ b/assets/css/notifications.css
@@ -43,6 +43,14 @@
border-bottom: 1px solid #c3c4c7;
}
+#hcaptcha-notifications .hcaptcha-notification.notice-warning {
+ border-left: 4px solid #dba617;
+}
+
+#hcaptcha-notifications.hcaptcha-setup-notice #hcaptcha-navigation {
+ display: none;
+}
+
.hcaptcha-notification .hcaptcha-notification-title {
margin: 7px 0;
padding: 2px;
diff --git a/assets/css/onboarding-wizard.css b/assets/css/onboarding-wizard.css
index fd0a5a129..f43d31baa 100644
--- a/assets/css/onboarding-wizard.css
+++ b/assets/css/onboarding-wizard.css
@@ -129,6 +129,12 @@
margin-bottom: 8px;
}
+.hcap-onb-tip .hcap-onb-signup-link,
+.hcap-onb-tip .hcap-onb-signup-link:hover,
+.hcap-onb-tip .hcap-onb-signup-link:focus {
+ color: #fff;
+}
+
.hcap-onb-tip .hcap-onb-done {
margin-top: 4px;
background: #4de1d2;
diff --git a/assets/css/settings-admin.css b/assets/css/settings-admin.css
index cb4c63de5..eb688b372 100644
--- a/assets/css/settings-admin.css
+++ b/assets/css/settings-admin.css
@@ -1,6 +1,7 @@
#toplevel_page_hcaptcha img {
width: 20px;
filter: grayscale(1);
+ opacity: 1 !important;
}
#toplevel_page_hcaptcha.wp-menu-open img {
diff --git a/assets/css/settings-base.css b/assets/css/settings-base.css
index c643d9b4c..4b514093b 100644
--- a/assets/css/settings-base.css
+++ b/assets/css/settings-base.css
@@ -103,6 +103,7 @@ body.settings_page_hcaptcha {
justify-content: flex-end;
gap: 10px;
flex-wrap: wrap;
+ transform: translateY(-1px);
}
.hcaptcha-help-button {
@@ -298,20 +299,18 @@ body.settings_page_hcaptcha {
}
#hcaptcha-message {
- display: flex;
- align-items: center;
- justify-content: space-between;
+ display: block;
+ position: relative;
+ box-sizing: border-box;
padding: 8px 12px;
+ padding-inline-end: 40px;
}
#hcaptcha-message .notice-dismiss {
- position: relative;
- top: unset;
- right: unset;
-}
-
-#hcaptcha-message {
- box-sizing: border-box;
+ position: absolute;
+ top: 50%;
+ right: 1px;
+ transform: translateY(-50%);
}
#hcaptcha-message > p {
diff --git a/assets/images/rest-api-protection.png b/assets/images/rest-api-protection.png
new file mode 100644
index 000000000..36982ff87
Binary files /dev/null and b/assets/images/rest-api-protection.png differ
diff --git a/assets/js/admin-wordfence.js b/assets/js/admin-wordfence.js
index 1f190dcc1..6940769c4 100644
--- a/assets/js/admin-wordfence.js
+++ b/assets/js/admin-wordfence.js
@@ -35,10 +35,10 @@ const wordfence = window.hCaptchaWordfence || ( function( document, window, $ )
notice.classList.add( 'wfls-block-list', 'hcaptcha-wordfence-notice' );
noticeLabel.textContent = HCaptchaWordfenceObject.noticeLabel;
- noticeDescription.innerHTML = HCaptchaWordfenceObject.noticeDescription;
+ noticeDescription.textContent = HCaptchaWordfenceObject.noticeDescription;
noticeItem.append( noticeLabel, noticeDescription );
notice.append( noticeItem );
- $settings.find( '.wfls-block-content' ).empty().append( notice );
+ $settings.find( '.wfls-block-content' ).prepend( notice );
},
getLocationHref() {
diff --git a/assets/js/general.js b/assets/js/general.js
index c68d4ff6d..a6d487a38 100644
--- a/assets/js/general.js
+++ b/assets/js/general.js
@@ -66,13 +66,10 @@ const general = function( $ ) {
const $themeEditorPreviewNote = $themeEditor.find( '[data-theme-editor-preview-note]' );
const $themeEditorPreviewDefaultContent = $themeEditorPreviewNote.contents().clone();
const $themeEditorOpen = $themeEditorLauncher.find( '[data-theme-editor-open]' );
- const $enterpriseInputs = $( '.hcaptcha-section-enterprise + table input' );
- const $recaptchaCompatOff = $( '[name="hcaptcha_settings[recaptcha_compat_off][]"]' );
const $submit = $form.find( '#submit' );
const modes = {};
let siteKeyInitVal = $siteKey.val();
let secretKeyInitVal = $secretKey.val();
- let enterpriseInitValues = getEnterpriseValues();
let defaultTheme = {};
let lastValidConfigParams = {};
let initialNormalizedConfigParams = null;
@@ -87,7 +84,6 @@ const general = function( $ ) {
modes[ HCaptchaGeneralObject.modeTestEnterpriseBotDetected ] = HCaptchaGeneralObject.modeTestEnterpriseBotDetectedSiteKey;
let credentialsChanged = false;
- let enterpriseSettingsChanged = false;
let consoleLogs = [];
@@ -169,22 +165,6 @@ const general = function( $ ) {
return logs.join( '\n' );
}
- function getValues( $inputs ) {
- const values = {};
-
- $inputs.each( function() {
- const $input = $( this );
- const name = $input.attr( 'name' ).replace( /hcaptcha_settings\[(.+)]/, '$1' );
- values[ name ] = $input.val();
- } );
-
- return values;
- }
-
- function getEnterpriseValues() {
- return getValues( $enterpriseInputs );
- }
-
function clearMessage() {
$message.remove();
// Concat below to avoid an inspection message.
@@ -956,9 +936,6 @@ const general = function( $ ) {
secretKeyInitVal = $secretKey.val();
credentialsChanged = false;
- enterpriseInitValues = getValues( $enterpriseInputs );
- enterpriseSettingsChanged = false;
-
showSuccessMessage( response.data );
$submit.attr( 'disabled', false );
} )
@@ -985,16 +962,6 @@ const general = function( $ ) {
}
}
- function checkChangeEnterpriseSettings() {
- if ( JSON.stringify( getEnterpriseValues() ) === JSON.stringify( enterpriseInitValues ) ) {
- enterpriseSettingsChanged = false;
- clearMessage();
- } else if ( ! enterpriseSettingsChanged ) {
- enterpriseSettingsChanged = true;
- showErrorMessage( HCaptchaGeneralObject.checkConfigNotice );
- }
- }
-
/**
* Set readonly and blocked state for key inputs.
*
@@ -1008,7 +975,7 @@ const general = function( $ ) {
.attr( 'aria-disabled', 'true' )
.on( 'keydown.hcaptchaHelper paste.hcaptchaHelper drop.hcaptchaHelper', ( e ) => e.preventDefault() );
} else {
- $el.removeAttr( 'readonly' )
+ $el.prop( 'readOnly', false )
.removeAttr( 'aria-disabled' )
.off( 'keydown.hcaptchaHelper paste.hcaptchaHelper drop.hcaptchaHelper' );
}
@@ -1139,7 +1106,7 @@ const general = function( $ ) {
} );
$submit.on( 'click', function( event ) {
- if ( ! ( credentialsChanged || enterpriseSettingsChanged ) ) {
+ if ( ! credentialsChanged ) {
return;
}
@@ -1529,84 +1496,6 @@ const general = function( $ ) {
setThemePreviewView( $( this ).attr( 'data-theme-preview-view' ) );
} );
- function forceHttps( host ) {
- host = host.replace( /(http|https):\/\//, '' );
-
- const url = new URL( 'https://' + host );
-
- return 'https://' + url.host;
- }
-
- function scriptUpdate() {
- const params = {
- onload: 'hCaptchaOnLoad',
- render: 'explicit',
- };
-
- if ( $recaptchaCompatOff.prop( 'checked' ) ) {
- params.recaptchacompat = 'off';
- }
-
- if ( $customThemes.prop( 'checked' ) ) {
- params.custom = 'true';
- }
-
- const enterpriseParams = {
- asset_host: 'assethost',
- endpoint: 'endpoint',
- host: 'host',
- image_host: 'imghost',
- report_api: 'reportapi',
- sentry: 'sentry',
- };
-
- const enterpriseValues = getEnterpriseValues();
-
- for ( const enterpriseParam in enterpriseParams ) {
- const value = enterpriseValues[ enterpriseParam ].trim();
-
- if ( value ) {
- params[ enterpriseParams[ enterpriseParam ] ] = encodeURIComponent( forceHttps( value ) );
- }
- }
-
- /**
- * @param enterpriseValues.api_host
- */
- let apiHost = enterpriseValues.api_host.trim();
- apiHost = apiHost ? apiHost : 'js.hcaptcha.com';
- apiHost = forceHttps( apiHost ) + '/1/api.js';
-
- const url = new URL( apiHost );
-
- for ( const name in params ) {
- url.searchParams.append( name, params[ name ] );
- }
-
- // Remove the existing API script.
- document.getElementById( 'hcaptcha-api' ).remove();
- // noinspection JSUnresolvedReference
- delete global.hcaptcha;
-
- // Remove sample hCaptcha.
- $sampleHCaptcha.html( '' );
-
- // Re-create the API script.
- const t = document.getElementsByTagName( 'head' )[ 0 ];
- const s = document.createElement( 'script' );
-
- s.type = 'text/javascript';
- s.id = 'hcaptcha-api';
- s.src = url.href;
-
- t.appendChild( s );
- }
-
- $enterpriseInputs.on( 'change', function() {
- scriptUpdate();
- checkChangeEnterpriseSettings();
- } );
-
// Prevent saving values of some form elements.
$checkConfig.removeAttr( 'name' );
$resetNotifications.removeAttr( 'name' );
diff --git a/assets/js/hcaptcha-acfe.js b/assets/js/hcaptcha-acfe.js
index 9ec35b828..8e697a4cc 100644
--- a/assets/js/hcaptcha-acfe.js
+++ b/assets/js/hcaptcha-acfe.js
@@ -1,4 +1,5 @@
/* global acf, jQuery */
+// noinspection JSUnusedGlobalSymbols
const hCaptchaACFE = window.hCaptchaACFE || ( function( window, $ ) {
const app = {
@@ -67,7 +68,7 @@ const hCaptchaACFE = window.hCaptchaACFE || ( function( window, $ ) {
document.querySelectorAll( '.acfe-field-recaptcha iframe' ).forEach( ( el ) => {
const src = el.getAttribute( 'src' ) || '';
const title = el.getAttribute( 'title' ) || '';
- const isRecaptcha = ( src + title ).toLowerCase().includes( 'recaptcha' );
+ const isRecaptcha = app.isRecaptchaUrl( src ) || title.toLowerCase().includes( 'recaptcha' );
if ( ! isRecaptcha ) {
return;
@@ -127,7 +128,15 @@ const hCaptchaACFE = window.hCaptchaACFE || ( function( window, $ ) {
window.hCaptchaOnLoad();
},
- ajaxCompleteHandler() {
+ ajaxCompleteHandler( event, xhr, settings ) {
+ const data = settings?.data;
+ const action = typeof data === 'string' ? new URLSearchParams( data ).get( 'action' ) : data?.action;
+
+ // Keep verified tokens until ACF completes the final submission.
+ if ( action === 'acf/validate_save_post' && xhr?.responseJSON?.success && xhr.responseJSON.data?.valid === 1 ) {
+ return;
+ }
+
// ACFE may perform AJAX validation; simply re-bind safely after requests.
if ( typeof window.hCaptchaBindEvents === 'function' ) {
window.hCaptchaBindEvents();
diff --git a/assets/js/hcaptcha-fst.js b/assets/js/hcaptcha-fst.js
index bdeb59878..c84357067 100644
--- a/assets/js/hcaptcha-fst.js
+++ b/assets/js/hcaptcha-fst.js
@@ -53,7 +53,41 @@ const fst = window.hCaptchaFST || ( function( document ) {
};
let currentToken = getStoredToken();
+ let tokenExpiresAt = 0;
let pendingRequest = null;
+ let issueError = '';
+ const pendingSubmissions = new WeakMap();
+ const messages = {
+ loading: 'Preparing the form. Please wait.',
+ error: 'Unable to prepare the form. Please check your connection and try submitting again.',
+ rateLimited: 'Too many requests (429). Please refresh the page and try again.',
+ ...HCaptchaFSTObject.messages,
+ };
+
+ /**
+ * Show a form preparation status outside the widget that is re-rendered.
+ *
+ * @param {HTMLElement} form Protected form or container.
+ * @param {string} message Message.
+ * @param {boolean} error Whether preparation failed.
+ */
+ const showMessage = ( form, message = '', error = false ) => {
+ let element = form.querySelector( '.hcaptcha-fst-message' );
+
+ if ( ! message ) {
+ element?.remove();
+ return;
+ }
+
+ if ( ! element ) {
+ element = document.createElement( 'div' );
+ element.className = 'hcaptcha-fst-message';
+ form.appendChild( element );
+ }
+
+ element.setAttribute( 'role', error ? 'alert' : 'status' );
+ element.textContent = message;
+ };
/**
* Update all form timing fields together.
@@ -78,6 +112,106 @@ const fst = window.hCaptchaFST || ( function( document ) {
document.addEventListener( 'hCaptchaAfterBindEvents', function() {
app.getToken();
} );
+
+ document.addEventListener( 'click', app.handleClick, true );
+ document.addEventListener( 'submit', app.handleSubmit, true );
+ },
+
+ isReady( form ) {
+ return ! pendingRequest && currentToken && Date.now() < tokenExpiresAt &&
+ form.querySelector( '[name="hcap_fst_token"]' )?.value === currentToken;
+ },
+
+ runWhenReady( form, callback, submitter = null ) {
+ if ( pendingSubmissions.has( form ) ) {
+ return pendingSubmissions.get( form );
+ }
+
+ if ( app.isReady( form ) ) {
+ showMessage( form );
+ callback();
+ return Promise.resolve( true );
+ }
+
+ const disabled = submitter?.disabled;
+ const busy = form.getAttribute( 'aria-busy' );
+
+ if ( submitter && 'disabled' in submitter ) {
+ submitter.disabled = true;
+ }
+
+ form.setAttribute( 'aria-busy', 'true' );
+ showMessage( form, messages.loading );
+
+ const submission = app.getToken().then( () => {
+ pendingSubmissions.delete( form );
+
+ if ( submitter && 'disabled' in submitter ) {
+ submitter.disabled = disabled;
+ }
+
+ if ( busy === null ) {
+ form.removeAttribute( 'aria-busy' );
+ } else {
+ form.setAttribute( 'aria-busy', busy );
+ }
+
+ if ( ! form.isConnected ) {
+ return false;
+ }
+
+ if ( ! app.isReady( form ) ) {
+ showMessage( form, issueError || messages.error, true );
+ return false;
+ }
+
+ showMessage( form );
+ callback();
+ return true;
+ } );
+
+ pendingSubmissions.set( form, submission );
+ return submission;
+ },
+
+ handleClick( event ) {
+ if ( ! ( event.target instanceof Element ) ) {
+ return;
+ }
+
+ const button = event.target.closest( window.hCaptcha?.submitButtonSelector || '[type="submit"]' );
+ const form = button?.closest( window.hCaptcha?.formSelector || 'form' ) || button?.form;
+
+ if ( ! form?.querySelector( '[name="hcap_fst_token"]' ) || app.isReady( form ) ) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ app.runWhenReady( form, () => button.click(), button );
+ },
+
+ handleSubmit( event ) {
+ const form = event.target;
+
+ if ( ! form.querySelector( '[name="hcap_fst_token"]' ) || app.isReady( form ) ) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopImmediatePropagation();
+
+ const submitter = event.submitter;
+
+ app.runWhenReady( form, () => {
+ if ( form.requestSubmit ) {
+ form.requestSubmit( submitter || undefined );
+ } else if ( submitter ) {
+ submitter.click();
+ } else if ( form.dispatchEvent( new Event( 'submit', { bubbles: true, cancelable: true } ) ) ) {
+ HTMLFormElement.prototype.submit.call( form );
+ }
+ }, submitter );
},
getToken() {
@@ -87,7 +221,10 @@ const fst = window.hCaptchaFST || ( function( document ) {
pendingRequest = ( async function() {
const formBody = new URLSearchParams();
- let issueError = '';
+ const controller = new AbortController();
+ // The timer is cleared in finally, including after a successful return.
+ let timeout = setTimeout( () => controller.abort(), 10000 );
+ issueError = '';
formBody.set( 'action', HCaptchaFSTObject.issueTokenAction );
formBody.set( 'nonce', HCaptchaFSTObject.issueTokenNonce );
@@ -98,22 +235,39 @@ const fst = window.hCaptchaFST || ( function( document ) {
formBody.set( 'replaceToken', currentToken );
}
+ const requestToken = () => fetch( HCaptchaFSTObject.ajaxUrl, {
+ method: 'POST',
+ credentials: 'same-origin',
+ cache: 'no-store',
+ signal: controller.signal,
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
+ },
+ body: formBody.toString(),
+ } );
+ let requestedAt = Date.now();
+
try {
- const res = await fetch( HCaptchaFSTObject.ajaxUrl, {
- method: 'POST',
- credentials: 'same-origin',
- cache: 'no-store',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
- },
- body: formBody.toString(),
- } );
-
- const body = await res.json();
+ let res = await requestToken();
+ let body = await res.json();
+ const freshNonce = body?.data?.nonce;
+
+ if ( 403 === res.status && 'fst-invalid-nonce' === body?.data?.code && 'string' === typeof freshNonce && freshNonce ) {
+ HCaptchaFSTObject.issueTokenNonce = freshNonce;
+ formBody.set( 'nonce', freshNonce );
+ clearTimeout( timeout );
+ timeout = setTimeout( () => controller.abort(), 10000 );
+ requestedAt = Date.now();
+ res = await requestToken();
+ body = await res.json();
+ }
const token = body?.data?.token ?? '';
if ( res.ok && body?.success && token ) {
+ const ttl = Number( body?.data?.ttl );
+ const secondsLeft = Number.isFinite( ttl ) && ttl > 0 ? Math.max( ttl - 5, 1 ) : 55;
+ tokenExpiresAt = requestedAt + ( secondsLeft * 1000 );
currentToken = token;
storeToken( currentToken );
setToken( currentToken );
@@ -122,19 +276,24 @@ const fst = window.hCaptchaFST || ( function( document ) {
}
if ( 429 === res.status && 'fst-rate-limited' === body?.data?.code ) {
- issueError = rateLimitedToken;
+ issueError = messages.rateLimited;
}
} catch {
// The server may have replaced the prior token before the response failed.
} finally {
- pendingRequest = null;
+ clearTimeout( timeout );
}
currentToken = '';
+ tokenExpiresAt = 0;
storeToken( currentToken );
- setToken( issueError );
+ setToken( issueError === messages.rateLimited ? rateLimitedToken : '' );
}() );
+ pendingRequest = pendingRequest.finally( () => {
+ pendingRequest = null;
+ } );
+
return pendingRequest;
},
};
diff --git a/assets/js/hcaptcha-givewp.js b/assets/js/hcaptcha-givewp.js
index 2aba7e152..d6984a6d5 100644
--- a/assets/js/hcaptcha-givewp.js
+++ b/assets/js/hcaptcha-givewp.js
@@ -42,15 +42,19 @@ const hCaptchaGiveWP = window.hCaptchaGiveWP || ( function( window ) {
const url = typeof resource === 'string' ? resource : ( resource?.url || '' );
let route = '';
+ let paypalOrder = false;
try {
const u = new URL( url, window.location.href );
route = u.searchParams.get( 'givewp-route' ) || '';
+ paypalOrder = u.origin === window.location.origin &&
+ u.pathname.endsWith( '/wp-admin/admin-ajax.php' ) &&
+ ( u.searchParams.get( 'action' ) || body.get( 'action' ) ) === 'give_paypal_commerce_create_order';
} catch {
// ignore
}
- if ( route !== 'donate' ) {
+ if ( route !== 'donate' && ! paypalOrder ) {
return;
}
@@ -73,12 +77,15 @@ const hCaptchaGiveWP = window.hCaptchaGiveWP || ( function( window ) {
const sigInput = giveWPForm.querySelector( `[name="${ sigName }"]` );
const hcapHp = giveWPForm.querySelector( `[id^="hcap_hp_"]` );
- body.set( responseName, response?.value );
- body.set( widgetName, widgetId?.value );
- body.set( nonceName, nonce?.value );
- body.set( tokenName, tokenInput?.value );
- body.set( sigName, sigInput?.value );
- body.set( hcapHp.id, hcapHp.value ?? '' );
+ body.set( responseName, response?.value ?? '' );
+ body.set( widgetName, widgetId?.value ?? '' );
+ body.set( nonceName, nonce?.value ?? '' );
+ body.set( tokenName, tokenInput?.value ?? '' );
+ body.set( sigName, sigInput?.value ?? '' );
+
+ if ( hcapHp ) {
+ body.set( hcapHp.id, hcapHp.value ?? '' );
+ }
config.body = body;
args[ 1 ] = config;
diff --git a/assets/js/hcaptcha-otter.js b/assets/js/hcaptcha-otter.js
index 968aa0c12..b55e32d77 100644
--- a/assets/js/hcaptcha-otter.js
+++ b/assets/js/hcaptcha-otter.js
@@ -67,12 +67,14 @@ const hCaptchaOtter = window.hCaptchaOtter || ( function( window ) {
const responseName = 'h-captcha-response';
const widgetName = 'hcaptcha-widget-id';
const nonceName = 'hcaptcha_otter_nonce';
+ const formNonceName = 'hcaptcha_otter_form_nonce';
const tokenName = 'hcap_fst_token';
const sigName = 'hcap_hp_sig';
const response = form.querySelector( `[name="${ responseName }"]` )?.value ?? '';
const widget = form.querySelector( `[name="${ widgetName }"]` )?.value ?? '';
const nonce = form.querySelector( `[name="${ nonceName }"]` )?.value ?? '';
+ const formNonce = form.querySelector( `[name="${ formNonceName }"]` )?.value ?? '';
const token = form.querySelector( `[name="${ tokenName }"]` )?.value ?? '';
const sig = form.querySelector( `[name="${ sigName }"]` )?.value ?? '';
const hcapHp = form.querySelector( `[id^="hcap_hp_"]` );
@@ -89,6 +91,8 @@ const hCaptchaOtter = window.hCaptchaOtter || ( function( window ) {
formData[ nonceName ] = nonce;
}
+ formData[ formNonceName ] = formNonce;
+
if ( token ) {
formData[ tokenName ] = token;
}
diff --git a/assets/js/hcaptcha-wc-stripe-express.js b/assets/js/hcaptcha-wc-stripe-express.js
new file mode 100644
index 000000000..3b719c488
--- /dev/null
+++ b/assets/js/hcaptcha-wc-stripe-express.js
@@ -0,0 +1,315 @@
+// noinspection JSUnusedGlobalSymbols
+
+( function() {
+ if ( window.hCaptchaWCStripeExpress ) {
+ return;
+ }
+
+ const settings = window.HCaptchaWCStripeExpressObject || {};
+ const nonceName = settings.nonceName || 'hcaptcha_wc_checkout_nonce';
+ const missingProofMessage = settings.missingProofMessage || 'Complete hCaptcha before express checkout.';
+ const wrapperSelector = '.hcaptcha-wc-stripe-express-proof';
+ const maxProofAge = 90 * 1000;
+ const proofStates = new WeakMap();
+ const controllerGates = new WeakMap();
+ const controllers = new Set();
+ const contexts = [ 'product', 'cart', 'minicart', 'express_checkout' ];
+
+ function getRoots( context ) {
+ if ( 'express_checkout' === context ) {
+ return [ ...document.querySelectorAll( 'form.checkout .hcaptcha-wc-checkout-proof' ) ];
+ }
+
+ return [ ...document.querySelectorAll( `${ wrapperSelector }[data-context="${ context }"]` ) ];
+ }
+
+ function getField( root, name ) {
+ return root.querySelector( `[name="${ name }"]` );
+ }
+
+ function getResponse( root ) {
+ return getField( root, 'h-captcha-response' )?.value || '';
+ }
+
+ function hasChallenge( root ) {
+ return !! root.querySelector( 'h-captcha.h-captcha' );
+ }
+
+ function isReady( root ) {
+ if ( ! root?.isConnected || ! getField( root, 'hcaptcha-widget-id' )?.value ) {
+ return false;
+ }
+
+ // The form may be explicitly exempted, but its signed identity is still required.
+ if ( ! hasChallenge( root ) ) {
+ return true;
+ }
+
+ const state = proofStates.get( root );
+ const response = getResponse( root );
+
+ return !! response &&
+ ! state?.spent &&
+ state?.token === response &&
+ Date.now() - state?.createdAt < maxProofAge;
+ }
+
+ function getReadyRoot( context ) {
+ return getRoots( context ).find( isReady ) || null;
+ }
+
+ function syncController( controller ) {
+ const context = controller?.context?.getPage?.();
+
+ if ( ! contexts.includes( context ) || 'expressCheckout' !== controller?.gateway?.elementType ) {
+ return;
+ }
+
+ let gate = controllerGates.get( controller );
+
+ if ( ! gate ) {
+ gate = {
+ nativeEnabled: controller.gateway._isDisabled !== true,
+ enable: controller.enablePaymentElement.bind( controller ),
+ disable: controller.disablePaymentElement.bind( controller ),
+ };
+ controllerGates.set( controller, gate );
+ controller.enablePaymentElement = ( ...args ) => {
+ gate.nativeEnabled = true;
+
+ return getReadyRoot( context ) ? gate.enable( ...args ) : gate.disable();
+ };
+ controller.disablePaymentElement = ( ...args ) => {
+ gate.nativeEnabled = false;
+
+ return gate.disable( ...args );
+ };
+ }
+
+ controllers.add( controller );
+
+ if ( ! getReadyRoot( context ) ) {
+ gate.disable();
+ } else if ( gate.nativeEnabled ) {
+ gate.enable();
+ }
+ }
+
+ function syncControllers( context ) {
+ for ( const controller of controllers ) {
+ if ( context === controller.context?.getPage?.() ) {
+ syncController( controller );
+ }
+ }
+ }
+
+ function syncAllControllers() {
+ for ( const controller of controllers ) {
+ syncController( controller );
+ }
+ }
+
+ function forgetProof( root ) {
+ const state = proofStates.get( root );
+
+ if ( state ) {
+ clearTimeout( state.timeout );
+ proofStates.delete( root );
+ }
+ }
+
+ function recordSolved( context, token ) {
+ if ( ! token ) {
+ return false;
+ }
+
+ let matched = false;
+
+ for ( const root of getRoots( context ) ) {
+ if ( ! hasChallenge( root ) || getResponse( root ) !== token ) {
+ continue;
+ }
+
+ const previous = proofStates.get( root );
+
+ if ( previous?.token === token ) {
+ matched = matched || ! previous.spent;
+ continue;
+ }
+
+ forgetProof( root );
+ const state = { token, createdAt: Date.now(), spent: false };
+ state.timeout = setTimeout( () => {
+ if ( proofStates.get( root ) === state ) {
+ proofStates.delete( root );
+ syncControllers( context );
+ }
+ }, maxProofAge );
+ proofStates.set( root, state );
+ matched = true;
+ }
+
+ if ( matched ) {
+ syncControllers( context );
+ }
+
+ return matched;
+ }
+
+ function onSolved( context, token ) {
+ if ( ! recordSolved( context, token ) ) {
+ // hCaptcha can invoke the callback before updating its response field.
+ setTimeout( () => recordSolved( context, token ), 0 );
+ }
+ }
+
+ function onExpired( context ) {
+ for ( const root of getRoots( context ) ) {
+ forgetProof( root );
+ }
+
+ syncControllers( context );
+ }
+
+ function getProofFields( root ) {
+ const hpInput = root.querySelector( 'input[id^="hcap_hp_"]' );
+ const names = [
+ 'h-captcha-response',
+ 'hcaptcha-widget-id',
+ nonceName,
+ hpInput?.name,
+ 'hcap_hp_sig',
+ 'hcap_fst_token',
+ ];
+ const fields = {};
+
+ for ( const name of names ) {
+ if ( ! name ) {
+ continue;
+ }
+
+ const field = getField( root, name );
+
+ if ( field ) {
+ fields[ name ] = field.value;
+ }
+ }
+
+ return fields;
+ }
+
+ function isStripeCheckout( options ) {
+ if ( 'POST' !== String( options?.method || '' ).toUpperCase() ) {
+ return false;
+ }
+
+ if ( typeof options.url !== 'string' ) {
+ return '/wc-stripe/v1/cart/checkout' === options.path;
+ }
+
+ let url;
+
+ try {
+ url = new URL( options.url, window.location.href );
+ } catch {
+ return false;
+ }
+
+ if ( url.origin !== window.location.origin ) {
+ return false;
+ }
+
+ if ( 'wc_stripe_frontend_request' === url.searchParams.get( 'wc-ajax' ) ) {
+ return '/wc-stripe/v1/cart/checkout' === url.searchParams.get( 'path' );
+ }
+
+ if ( '/wc-stripe/v1/cart/checkout' === url.searchParams.get( 'rest_route' ) ) {
+ return true;
+ }
+
+ return url.pathname.replace( /\/+$/, '' ).endsWith( '/wp-json/wc-stripe/v1/cart/checkout' );
+ }
+
+ function resetProof( root, context ) {
+ const widget = root.querySelector( 'h-captcha.h-captcha' );
+ forgetProof( root );
+
+ if ( widget && typeof window.hCaptchaReset === 'function' ) {
+ window.hCaptchaReset( widget );
+ }
+
+ syncControllers( context );
+ }
+
+ function addProof( options, next ) {
+ if ( ! isStripeCheckout( options ) ) {
+ return next( options );
+ }
+
+ const data = options.data;
+ const context = data?.context;
+
+ if ( ! data || Array.isArray( data ) || 'object' !== typeof data || ! contexts.includes( context ) ) {
+ return Promise.reject( new Error( missingProofMessage ) );
+ }
+
+ const root = getReadyRoot( context );
+
+ if ( ! root ) {
+ return Promise.reject( new Error( missingProofMessage ) );
+ }
+
+ const fields = getProofFields( root );
+ const state = proofStates.get( root );
+
+ if ( state ) {
+ state.spent = true;
+ clearTimeout( state.timeout );
+ syncControllers( context );
+ }
+
+ let result;
+
+ try {
+ result = next( { ...options, data: { ...data, ...fields } } );
+ } catch ( error ) {
+ resetProof( root, context );
+ throw error;
+ }
+
+ return Promise.resolve( result ).then(
+ ( response ) => {
+ resetProof( root, context );
+ return response;
+ },
+ ( error ) => {
+ resetProof( root, context );
+ throw error;
+ },
+ );
+ }
+
+ // noinspection UnnecessaryLocalVariableJS
+ const app = {
+ onProductSolved: ( token ) => onSolved( 'product', token ),
+ onCartSolved: ( token ) => onSolved( 'cart', token ),
+ onMinicartSolved: ( token ) => onSolved( 'minicart', token ),
+ onProductExpired: () => onExpired( 'product' ),
+ onCartExpired: () => onExpired( 'cart' ),
+ onMinicartExpired: () => onExpired( 'minicart' ),
+ };
+
+ window.hCaptchaWCStripeExpress = app;
+ wp.hooks.addFilter( 'hcaptcha.formSelector', 'hcaptcha-wc-stripe-express', ( selector ) => `${ selector }, ${ wrapperSelector }` );
+ wp.apiFetch.use( addProof );
+ window.wcStripe?.actions?.addAction( 'payment_element_ready', syncController );
+ window.wcStripe?.actions?.addAction( 'express_element_ready', ( availableMethods, gateway ) => {
+ syncController( gateway?.controller );
+ } );
+ if ( window.MutationObserver && document.body ) {
+ new MutationObserver( syncAllControllers ).observe( document.body, { childList: true, subtree: true } );
+ }
+ document.addEventListener( 'hCaptchaSubmitted', ( event ) => {
+ onSolved( 'express_checkout', event.detail?.token );
+ } );
+}() );
diff --git a/assets/js/integrations.js b/assets/js/integrations.js
index 2da75db3f..0e22417ef 100644
--- a/assets/js/integrations.js
+++ b/assets/js/integrations.js
@@ -39,8 +39,6 @@ const integrations = function( $ ) {
const $wpWrap = $( '#wpwrap' );
const $adminmenuwrap = $( '#adminmenuwrap' );
const $search = $( '#hcaptcha-integrations-search' );
- const $showAntispamCoverage = $( '#show_antispam_coverage_1' );
- const $antispamLegend = $( '#hcaptcha-antispam-legend' );
function clearMessage() {
$message.remove();
@@ -94,7 +92,7 @@ const integrations = function( $ ) {
}
function isActiveTable( $table ) {
- return $table.is( jQuery( '.form-table' ).eq( 1 ) );
+ return $table.is( jQuery( '.form-table' ).eq( 0 ) );
}
function swapThemes( activate, entity, newTheme ) {
@@ -103,7 +101,7 @@ const integrations = function( $ ) {
}
const $tables = $( '.form-table' );
- const $fromTable = $tables.eq( activate ? 1 : 2 );
+ const $fromTable = $tables.eq( activate ? 0 : 1 );
const dataLabel = activate ? '' : '[data-label="' + newTheme + '"]';
const $img = $fromTable.find( '.hcaptcha-integrations-logo img[data-entity="theme"]' + dataLabel );
@@ -112,7 +110,7 @@ const integrations = function( $ ) {
return;
}
- const $toTable = $tables.eq( activate ? 2 : 1 );
+ const $toTable = $tables.eq( activate ? 1 : 0 );
const $tr = $img.closest( 'tr' );
insertIntoTable( $toTable, $img.attr( 'data-label' ), $tr );
@@ -150,79 +148,6 @@ const integrations = function( $ ) {
}
}
- // Set up antispam helper
- function setupHelper( $label ) {
- let $helper = $label.next( '.helper' );
-
- // If a helper doesn't exist immediately after, insert it
- if ( ! $helper.length ) {
- $helper = $( document.createElement( 'span' ) ).addClass( 'helper' );
- $label.after( $helper );
- }
-
- // Rebuild helper icons based on helper data-* attributes.
- // The helper may have several data-antispam-* attributes (e.g., data-antispam-honeypot, data-antispam-fst).
- // We insert corresponding
nodes like
,
inside the helper.
- ( function populateHelperIcons() {
- // Remove previously added antispam icons to avoid duplicates.
- $helper.find( 'i[class^="antispam"]' ).remove();
-
- const attrs = $label.get( 0 )?.attributes ?? [];
- const classes = [];
-
- for ( let i = 0; i < attrs.length; i++ ) {
- const name = attrs[ i ].name;
-
- // Ignore 'data-antispam' as it is a general marker for the helper.
- if ( name.indexOf( 'data-antispam-' ) === 0 ) {
- // Convert attribute name to class name by stripping the 'data-' prefix.
- const className = name.replace( /^data-/, '' );
-
- if ( classes.indexOf( className ) === -1 ) {
- classes.push( className );
- }
- }
- }
-
- // Append images for each discovered class.
- classes.forEach( function( cls ) {
- const $icon = $( document.createElement( 'i' ) ).addClass( cls );
-
- $helper.prepend( $icon );
- } );
- }() );
-
- return $helper;
- }
-
- function setupHelpers() {
- const disabled = $showAntispamCoverage.prop( 'disabled' );
-
- if ( disabled ) {
- return;
- }
-
- const checked = $showAntispamCoverage.prop( 'checked' );
-
- // Find all labels that declare the antispam marker
- $( 'label[data-antispam]' ).each( function() {
- const $helper = setupHelper( $( this ) );
-
- if ( checked ) {
- $helper.css( 'display', 'inline-flex' );
- } else {
- $helper.hide();
- }
- } );
-
- // Toggle legend visibility.
- if ( checked ) {
- $antispamLegend.show();
- } else {
- $antispamLegend.hide();
- }
- }
-
/**
* Suggest an entity for activation.
*/
@@ -251,11 +176,6 @@ const integrations = function( $ ) {
};
}
- // Handle Show Antispam Indicators checkbox change: insert/clear helper spans after labels
- $showAntispamCoverage.on( 'change', function() {
- setupHelpers();
- } );
-
const latestPlanRequests = new WeakMap();
$( '.form-table img' ).on( 'click', function( event ) {
@@ -544,7 +464,7 @@ const integrations = function( $ ) {
}
if ( currStatus !== status ) {
- const $toTable = $tables.eq( status ? 1 : 2 );
+ const $toTable = $tables.eq( status ? 0 : 1 );
const alt = $logo.find( 'img' ).attr( 'alt' );
insertIntoTable( $toTable, alt, $tr );
@@ -607,7 +527,7 @@ const integrations = function( $ ) {
return;
}
- const $table = $( '.form-table' ).eq( activate ? 1 : 2 );
+ const $table = $( '.form-table' ).eq( activate ? 0 : 1 );
swapThemes( activate, entity, newTheme );
insertIntoTable( $table, alt, $tr );
@@ -817,7 +737,7 @@ const integrations = function( $ ) {
100,
) );
- $( '#hcaptcha-options' ).keydown(
+ $( '#hcaptcha-options' ).on( 'keydown',
function( e ) {
if ( $( e.target ).is( $search ) && e.which === 13 ) {
e.preventDefault();
@@ -825,7 +745,6 @@ const integrations = function( $ ) {
},
);
- setupHelpers();
suggestActivate();
};
diff --git a/assets/js/notifications.js b/assets/js/notifications.js
index ca986f972..840195f5e 100644
--- a/assets/js/notifications.js
+++ b/assets/js/notifications.js
@@ -27,6 +27,7 @@ const notifications = ( $ ) => {
const navSelectors = navPrevSelector + ', ' + navNextSelector;
const buttonsSelector = '.hcaptcha-notification-buttons';
const resetBtnSelector = 'button#reset_notifications';
+ const resetRowSelector = 'tr.hcaptcha-general-reset-notifications';
const footerSelector = '#hcaptcha-notifications-footer';
let $notifications;
@@ -150,6 +151,7 @@ const notifications = ( $ ) => {
$notification.remove();
$next.show();
+ $( resetRowSelector ).removeClass( 'hidden' );
setNavStatus();
setButtons();
@@ -208,13 +210,17 @@ const notifications = ( $ ) => {
$.post( {
url: HCaptchaNotificationsObject.ajaxUrl,
data,
- } ).success( function( response ) {
+ } ).done( function( response ) {
if ( ! response.success ) {
return;
}
- $( notificationsSelector ).remove();
- $( response.data ).insertBefore( sectionKeysSelector );
+ $( resetRowSelector ).addClass( 'hidden' );
+
+ if ( ! $( notificationsSelector ).hasClass( 'hcaptcha-setup-notice' ) ) {
+ $( notificationsSelector ).remove();
+ $( response.data ).insertBefore( sectionKeysSelector );
+ }
setButtons();
normalizeNotificationHeight();
diff --git a/assets/js/onboarding-wizard.js b/assets/js/onboarding-wizard.js
index b2402c139..1548581c8 100644
--- a/assets/js/onboarding-wizard.js
+++ b/assets/js/onboarding-wizard.js
@@ -2,6 +2,7 @@
/**
* @param HCaptchaOnboardingObject.ajaxUrl
+ * @param HCaptchaOnboardingObject.antispamUrl
* @param HCaptchaOnboardingObject.autoSetupNonce
* @param HCaptchaOnboardingObject.autoSetupParam
* @param HCaptchaOnboardingObject.currentStep
@@ -25,14 +26,16 @@
* @param HCaptchaOnboardingObject.nonceParam
* @param HCaptchaOnboardingObject.page
* @param HCaptchaOnboardingObject.selectors
- * @param HCaptchaOnboardingObject.selectors.general.antispam
* @param HCaptchaOnboardingObject.selectors.general.check_config
* @param HCaptchaOnboardingObject.selectors.general.force
* @param HCaptchaOnboardingObject.selectors.general.mode
* @param HCaptchaOnboardingObject.selectors.general.save
* @param HCaptchaOnboardingObject.selectors.general.site_key
+ * @param HCaptchaOnboardingObject.selectors.antispam.bot_detection
+ * @param HCaptchaOnboardingObject.selectors.antispam.save
* @param HCaptchaOnboardingObject.selectors.integrations.integrations_list
* @param HCaptchaOnboardingObject.selectors.integrations.save
+ * @param HCaptchaOnboardingObject.signupUrl
* @param HCaptchaOnboardingObject.stepNonce
* @param HCaptchaOnboardingObject.stepParam
* @param HCaptchaOnboardingObject.steps
@@ -53,8 +56,9 @@ const onboarding = function( $ ) {
// Steps by page
const stepsByPage = {
- general: [ 1, 2, 3, 4, 5, 6 ],
- integrations: [ 7, 8 ],
+ general: [ 1, 2, 3, 4, 5 ],
+ antispam: [ 6, 7 ],
+ integrations: [ 8, 9 ],
};
// Targets map per step
@@ -63,10 +67,11 @@ const onboarding = function( $ ) {
2: { page: 'general', selector: cfg.selectors.general.mode },
3: { page: 'general', selector: cfg.selectors.general.check_config },
4: { page: 'general', selector: cfg.selectors.general.force },
- 5: { page: 'general', selector: cfg.selectors.general.antispam },
- 6: { page: 'general', selector: cfg.selectors.general.save },
- 7: { page: 'integrations', selector: cfg.selectors.integrations.integrations_list },
- 8: { page: 'integrations', selector: cfg.selectors.integrations.save },
+ 5: { page: 'general', selector: cfg.selectors.general.save },
+ 6: { page: 'antispam', selector: cfg.selectors.antispam.bot_detection },
+ 7: { page: 'antispam', selector: cfg.selectors.antispam.save },
+ 8: { page: 'integrations', selector: cfg.selectors.integrations.integrations_list },
+ 9: { page: 'integrations', selector: cfg.selectors.integrations.save },
};
let $tooltip;
@@ -88,16 +93,27 @@ const onboarding = function( $ ) {
return m ? parseInt( m[ 1 ], 10 ) : 1;
}
- function nextStep( current ) {
- const n = stepNumber( current );
-
- return 'step ' + ( n + 1 );
- }
-
function inArray( needle, arr ) {
return arr.indexOf( needle ) !== -1;
}
+ function appendStepText( $container, step ) {
+ if ( step !== 1 ) {
+ $container.text( cfg.steps[ step ] );
+
+ return;
+ }
+
+ /* language=HTML */
+ $container.append( $( '' )
+ .attr( {
+ href: cfg.signupUrl,
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ } )
+ .text( cfg.steps[ step ] ) );
+ }
+
function setLocationHref( url ) {
if ( typeof onboarding.setLocationHref === 'function' ) {
// For testing purposes.
@@ -144,8 +160,8 @@ const onboarding = function( $ ) {
removeTooltip();
- if ( form && typeof form.submit === 'function' ) {
- form.submit();
+ if ( form ) {
+ submitSettingsForm( autoSetupUrl );
return;
}
@@ -205,15 +221,18 @@ const onboarding = function( $ ) {
/* language=HTML */
const $list = $( '
' );
- for ( let i = 1; i <= 8; i++ ) {
+ for ( let i = 1; i <= 9; i++ ) {
/* language=HTML */
const $li = $( '' )
- .text( cfg.steps[ i ] )
.attr( 'data-step', i )
- .attr( 'role', 'button' )
- .attr( 'tabindex', '0' )
.addClass( 'hcap-onb-step' );
+ appendStepText( $li, i );
+
+ if ( i !== 1 ) {
+ $li.attr( 'role', 'button' ).attr( 'tabindex', '0' );
+ }
+
if ( 'step ' + i === current ) {
$li.addClass( 'current' );
}
@@ -438,7 +457,7 @@ const onboarding = function( $ ) {
}, 0 );
}
- // Build congrats/rating popup shown after completion (step 8)
+ // Build congrats/rating popup shown after completion (step 9)
function buildCongratsModal( onDismiss = undefined ) {
/* language=HTML */
const $overlay = $( '' );
@@ -569,27 +588,8 @@ const onboarding = function( $ ) {
return;
}
- const next = nextStep( 'step ' + step );
-
- if ( step === 6 && cfg.page === 'general' ) {
- // Last General step → go Integrations
- cfg.currentStep = next; // 'step 7'
-
- postUpdate( next ).always( function() {
- setLocationHref( cfg.integrationsUrl );
- } );
-
- return;
- }
-
- if ( step >= 8 ) {
- // Completed via the Done button — show congrats popup
- postUpdate( 'completed' ).always( function() {
- buildCongratsModal( function() {
- removeTooltip();
- $( '.hcap-onb-panel' ).remove();
- } );
- } );
+ if ( [ 5, 7, 9 ].includes( step ) ) {
+ $( '#hcaptcha-options #submit' ).trigger( 'click' );
return;
}
@@ -600,10 +600,11 @@ const onboarding = function( $ ) {
/* language=HTML */
$tooltip = $( '' );
- const tipText = cfg.steps[ step ];
-
/* language=HTML */
- $tooltip.append( $( '' ).text( tipText ) );
+ const $tipText = $( '' );
+
+ appendStepText( $tipText, step );
+ $tooltip.append( $tipText );
// For step 1 add a second line with a video link
if ( step === 1 ) {
@@ -697,8 +698,13 @@ const onboarding = function( $ ) {
// Navigation helper must be available regardless of early returns below
function goToStep( n ) {
- const isGeneral = inArray( n, stepsByPage.general );
- const base = isGeneral ? cfg.generalUrl : cfg.integrationsUrl;
+ let base = cfg.integrationsUrl;
+
+ if ( inArray( n, stepsByPage.general ) ) {
+ base = cfg.generalUrl;
+ } else if ( inArray( n, stepsByPage.antispam ) ) {
+ base = cfg.antispamUrl;
+ }
setLocationHref( buildUrl( base, {
[ cfg.stepParam ]: n,
@@ -710,6 +716,10 @@ const onboarding = function( $ ) {
$( document ).off( '.hcapOnbNav' );
$( document ).on( 'click.hcapOnbNav', '.hcap-onb-list li.hcap-onb-step', function( e ) {
+ if ( $( e.target ).closest( 'a' ).length ) {
+ return;
+ }
+
e.preventDefault();
const n = parseInt( $( this ).attr( 'data-step' ), 10 );
@@ -720,6 +730,10 @@ const onboarding = function( $ ) {
} );
$( document ).on( 'keydown.hcapOnbNav', '.hcap-onb-list li.hcap-onb-step', function( e ) {
+ if ( $( e.target ).closest( 'a' ).length ) {
+ return;
+ }
+
if ( e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar' ) {
e.preventDefault();
@@ -738,25 +752,51 @@ const onboarding = function( $ ) {
}
} );
- // Also advance on real Save for steps 6 (General) and 8 (Integrations)
- // For step 8 we first show the congrats popup, then proceed with submitting.
+ function submitSettingsForm( fallbackUrl = '' ) {
+ const form = $( '#hcaptcha-options' ).get( 0 );
+
+ if ( ! form ) {
+ return;
+ }
+
+ try {
+ if ( typeof form.submit === 'function' ) {
+ form.submit();
+ } else {
+ HTMLFormElement.prototype.submit.call( form );
+ }
+ } catch {
+ if ( fallbackUrl ) {
+ setLocationHref( fallbackUrl );
+ } else {
+ $( '#hcaptcha-options #submit' ).trigger( 'click' );
+ }
+ }
+ }
+
+ // Save each page before advancing to the next one.
$( document ).on( 'submit', '#hcaptcha-options', function( e ) {
const n = stepNumber( cfg.currentStep || 'step 1' );
- if ( n === 6 && cfg.page === 'general' ) {
- const next = 'step 7';
+ if ( ( n === 5 && cfg.page === 'general' ) || ( n === 7 && cfg.page === 'antispam' ) ) {
+ e.preventDefault();
- cfg.currentStep = next;
- postUpdate( next );
+ const next = n === 5 ? 'step 6' : 'step 8';
+ const storageKey = n === 5 ? 'hcapOnbGoAntiSpam' : 'hcapOnbGoIntegrations';
- try {
- if ( window.sessionStorage ) {
- sessionStorage.setItem( 'hcapOnbGoIntegrations', '1' );
+ cfg.currentStep = next;
+ postUpdate( next ).always( function() {
+ try {
+ if ( window.sessionStorage ) {
+ sessionStorage.setItem( storageKey, '1' );
+ }
+ } catch {
+ // no-op
}
- } catch {
- // no-op
- }
- } else if ( n === 8 && cfg.page === 'integrations' ) {
+
+ submitSettingsForm();
+ } );
+ } else if ( n === 9 && cfg.page === 'integrations' ) {
if ( hcapOnbSubmitting ) {
return; // allow natural submit a second time
}
@@ -770,12 +810,7 @@ const onboarding = function( $ ) {
// After closing the modal, submit the form at once
hcapOnbSubmitting = true;
- try {
- $( '#hcaptcha-options' ).get( 0 ).submit();
- } catch {
- // fallback: trigger a click on the `submit` button
- $( '#hcaptcha-options [type="submit"]' ).first().trigger( 'click' );
- }
+ submitSettingsForm();
} );
} );
}
@@ -788,15 +823,32 @@ const onboarding = function( $ ) {
// Determine current numeric step
const num = stepNumber( current );
- if ( num === 8 && sessionStorage.getItem( 'hcapOnbAutoSetup' ) === '1' ) {
+ let autoSetupCompleted = false;
+
+ try {
+ autoSetupCompleted = num === 9 && sessionStorage.getItem( 'hcapOnbAutoSetup' ) === '1';
+
+ if ( autoSetupCompleted ) {
+ sessionStorage.removeItem( 'hcapOnbAutoSetup' );
+ }
+ } catch {
+ // no-op
+ }
+
+ if ( autoSetupCompleted ) {
postUpdate( 'completed' ).always( function() {
buildCongratsModal();
} );
}
- // If we just saved on the last General step, redirect to Integrations
+ // Redirect after saving General or Anti-Spam settings.
try {
- if ( cfg.page === 'general' && num === 7 ) {
+ if ( cfg.page === 'general' && num === 6 ) {
+ if ( window.sessionStorage && sessionStorage.getItem( 'hcapOnbGoAntiSpam' ) === '1' ) {
+ sessionStorage.removeItem( 'hcapOnbGoAntiSpam' );
+ setLocationHref( cfg.antispamUrl );
+ }
+ } else if ( cfg.page === 'antispam' && num === 8 ) {
if ( window.sessionStorage && sessionStorage.getItem( 'hcapOnbGoIntegrations' ) === '1' ) {
sessionStorage.removeItem( 'hcapOnbGoIntegrations' );
setLocationHref( cfg.integrationsUrl );
diff --git a/changelog.txt b/changelog.txt
index 1c0eb6367..e7570efcf 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -1,3 +1,39 @@
+= 5.5.0 =
+* Added compatibility with Contact Form 7 6.2.0.
+* Added support for Icegram Express Max.
+* Added safe entry data processing across supported integrations, including native form payloads and email addresses.
+* Protected configured content in WordPress REST post, page, collection, and search responses.
+* Required hCaptcha for native WordPress REST comment creation.
+* Blocked REST password attempts that bypassed the protected post and page password form.
+* Extended signed hCaptcha widget ID verification to integrations and form paths that previously skipped it.
+* Preserved WPForms spam checks and submission-time validation when hCaptcha replaces its native CAPTCHA.
+* Preserved the visible hCaptcha widget in Essential Addons registration after its form markup is sanitized.
+* Kept wpDiscuz comment reCAPTCHA active when hCaptcha protects subscriptions only.
+* Avoided duplicate CAPTCHA challenges on Wordfence-protected WordPress registration forms.
+* Simplified the settings screen with keys and setup guidance first, an optional setup wizard, and an Advanced tab for less common options.
+* Recovered form submissions on long-open pages by refreshing expired timing tokens and retrying token requests with a fresh nonce.
+* Removed the Show Anti-Spam Indicators setting and indicators from the Integrations page, because all integrations now use the Anti-Spam protection.
+* Fixed error responses for rejected hCaptcha checks in WooCommerce Store API checkout.
+* Fixed Easy Digital Downloads checkout to show hCaptcha errors in its standard notices.
+* Fixed content protection on sites using plain permalinks.
+* Fixed adaptive hCaptcha after failed login attempts in Fluent Forms, Simple Membership, Ultimate Member, Beaver Builder, and Ultimate Addons.
+* Fixed rendering and validation of existing Ninja Forms hCaptcha fields alongside the plugin's own field.
+* Fixed hCaptcha rendering in Brevo signup widgets.
+* Fixed hCaptcha rendering in Formidable Forms when the CAPTCHA field label is set to "None".
+* Fixed Kadence form CAPTCHA settings changing when saving content.
+* Fixed adaptive hCaptcha on Theme My Login AJAX login forms.
+* Fixed multisite settings being saved to the wrong scope during background updates.
+* Fixed missing Events entries for requests with long User-Agent values.
+* Fixed content protection URL patterns and preserved regular expressions in settings.
+* Fixed Automatic Verification on forms with nonstandard action URLs.
+* Fixed hCaptcha disappearing from ACF Extended forms after page load.
+* Fixed "Token replayed or expired" errors during ACF Extended form submissions.
+* Fixed "Signature mismatch" errors when guests submit custom Auto-Verification forms with Form Submit Time enabled.
+* Fixed a fatal error when rendering the "Theme My Login" login form.
+* Fixed form submission while a Form Submit Time token is loading and added retryable connection error messages.
+* Fixed automatic verification rejecting forms with nested or array input names.
+* Fixed Simple Download Monitor downloads with WordPress script debugging (`SCRIPT_DEBUG`) enabled by loading its source script as a module.
+
= 5.4.1 =
* Fixed WordPress login authentication when login integrations have different protection settings.
* Improved Auto-Verification compatibility with forms on query-based page URLs and Brevo forms, while simplifying form registration storage.
diff --git a/codeception.yml b/codeception.yml
index 0a71e7788..1b1d679d6 100644
--- a/codeception.yml
+++ b/codeception.yml
@@ -20,6 +20,3 @@ coverage:
low_limit: 35
high_limit: 90
show_only_summary: true
- include:
- - ./src/php/*
- - ./hcaptcha.php
diff --git a/composer.json b/composer.json
index d5c515497..0bfb95097 100644
--- a/composer.json
+++ b/composer.json
@@ -72,8 +72,17 @@
"scripts": {
"pre-autoload-dump": "HCaptcha\\Scoper\\Scoper::pre_autoload_dump",
"post-cmd": "HCaptcha\\Scoper\\Scoper::post_cmd",
- "post-install-cmd": "@post-cmd",
- "post-update-cmd": "@post-cmd",
+ "post-install-cmd": [
+ "@post-cmd",
+ "@hooks:install"
+ ],
+ "post-update-cmd": [
+ "@post-cmd",
+ "@hooks:install"
+ ],
+ "hooks:install": "@php .githooks/setup.php",
+ "changelog": "@php .github/scripts/update-changelog.php",
+ "changelog:check": "@php .github/scripts/update-changelog.php --check",
"phpcs": "vendor/bin/phpcs --colors --standard=phpcs.xml",
"integration": "codecept run integration -c codeception.yml",
"integration:multisite": "codecept run multisite -c codeception.yml",
diff --git a/hcaptcha.php b/hcaptcha.php
index 7801713c4..fd281f471 100644
--- a/hcaptcha.php
+++ b/hcaptcha.php
@@ -10,7 +10,7 @@
* Plugin Name: hCaptcha for WP
* Plugin URI: https://www.hcaptcha.com/
* Description: hCaptcha keeps out bots and spam while putting privacy first. It is a drop-in replacement for reCAPTCHA.
- * Version: 5.4.1
+ * Version: 5.5.0
* Requires at least: 6.0
* Requires PHP: 7.4
* Author: hCaptcha
@@ -39,7 +39,7 @@
/**
* Plugin version.
*/
-const HCAPTCHA_VERSION = '5.4.1';
+const HCAPTCHA_VERSION = '5.5.0';
/**
* Path to the plugin dir.
diff --git a/readme.txt b/readme.txt
index 15f6955dd..a7bb4ce1a 100644
--- a/readme.txt
+++ b/readme.txt
@@ -4,7 +4,7 @@ Tags: captcha, hcaptcha, recaptcha, antispam, spam
Requires at least: 6.0
Tested up to: 7.1
Requires PHP: 7.4
-Stable tag: 5.4.1
+Stable tag: 5.5.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
@@ -15,6 +15,8 @@ Works with 60+ integrations: Contact Form 7, Elementor, WooCommerce, Divi, etc.
The strongest CAPTCHA. Switch from reCAPTCHA and Turnstile for free.
+**Unique REST API protection:** In our October 2026 review of the 10 most-installed WordPress.org plugins tagged `captcha`, none offered this combination: hCaptcha protects selected content in WordPress REST post, page, collection, and search responses; requires hCaptcha for native REST comments; and blocks REST post-password attempts. Each safeguard applies when its corresponding protection is enabled.
+
A built-in Migration Wizard helps you move from Google reCAPTCHA or Cloudflare Turnstile to hCaptcha in just a few clicks.
[hCaptcha](https://www.hcaptcha.com/) is a drop-in replacement for reCAPTCHA that puts user privacy first.
@@ -41,6 +43,7 @@ hCaptcha for WP [makes security easy](https://www.hcaptcha.com/integration-hcapt
* **Pro and Enterprise:** Supports Pro and Enterprise versions of hCaptcha.
* **No Challenge Modes:** 99.9% passive and passive modes in Pro and Enterprise versions reduce user friction.
* **Protect Site Content:** Protects selected site URLs from bots with hCaptcha. Works best with Pro 99.9% passive mode.
+* **REST API Protection:** Keeps protected posts and pages out of WordPress REST responses and search, verifies native REST comments, and blocks REST post-password attempts when the corresponding protections are enabled.
* **Logged-in Users:** Optionally turn off hCaptcha for logged-in users.
* **Delayed API Loading:** Load the hCaptcha API instantly or on user interaction for zero page loading impact.
* **IP Access Control:** Allowlist trusted IPs to skip hCaptcha and denylist abusive IPs to block form submissions.
@@ -351,6 +354,12 @@ if ( null !== $result ) {
}
`
+= How to honor per-form protection exemptions in custom handlers =
+
+Custom verification helpers always require a valid CAPTCHA response unless the server supplies the expected form identity. To honor a per-form `hcap_protect_form` exemption, pass the same server-selected `source` and `form_id` used to render the widget: `API::verify_post( $nonce_name, $nonce_action, $expected_id )`, `API::verify_post_html( $nonce_name, $nonce_action, $expected_id )`, or `API::verify_post_data( $nonce_name, $nonce_action, $post_data, $expected_id )`. For `API::verify_request()` and `API::verify()`, use the entry's `expected_id` key. Derive that identity from the native form being processed, independently of the submitted `hcaptcha-widget-id`.
+
+When a handler cannot identify the submitted form independently, set `mandatory` to `true` in the arguments passed to `HCaptcha::form()` or `HCaptcha::form_display()`. This keeps the required challenge and nonce visible even when a per-form exemption is configured. Asgaros, Passster, and PayPal order creation use this mode; PayPal also requires the checkout widget it shares. Icegram's generic form without a native form ID requires the challenge too. Other forms with a matching server-selected identity retain their per-form exemptions.
+
= How to automatically verify an arbitrary form =
Arbitrary user forms can be verified easily. Just add `auto="true"` or `auto="1"` to the shortcode:
@@ -515,8 +524,8 @@ Events Manager
`$source: 'events-manager/events-manager.php'`
`$form_id: event_id`
-Icegram Express
-`$source: 'email-subscribers/email-subscribers.php'`
+Icegram Express (including Max)
+`$source: [ 'email-subscribers-premium/email-subscribers-premium.php', 'email-subscribers/email-subscribers.php' ]`
`$form_id: form_id`
Customer Reviews for WooCommerce
@@ -940,6 +949,8 @@ With the default configuration, this plugin does not:
* send any data to external servers;
* use cookies.
+If you enable CAPTCHA protection for native WordPress password-protected posts, the plugin sets a first-party `hcaptcha_postpass_` cookie after successful verification. It contains signed proof of the password scope without the password itself and follows the native post-password cookie lifetime, including session cookies. Existing post-password cookies without this proof require another password-form submission with CAPTCHA. REST password attempts are rejected while this protection is enabled; editor authorization remains available.
+
Once you activate this plugin, the hCaptcha-answering user's IP address and browser data may be sent to the hCaptcha service on pages where you have activated hCaptcha protection. However, hCaptcha is designed to minimize data used, process it very close to the user, and rapidly discard it after analysis.
For more details, please see the hCaptcha privacy policy at:
@@ -1053,6 +1064,42 @@ Instructions for popular native integrations are below:
== Changelog ==
+= 5.5.0 =
+* Added compatibility with Contact Form 7 6.2.0.
+* Added support for Icegram Express Max.
+* Added safe entry data processing across supported integrations, including native form payloads and email addresses.
+* Protected configured content in WordPress REST post, page, collection, and search responses.
+* Required hCaptcha for native WordPress REST comment creation.
+* Blocked REST password attempts that bypassed the protected post and page password form.
+* Extended signed hCaptcha widget ID verification to integrations and form paths that previously skipped it.
+* Preserved WPForms spam checks and submission-time validation when hCaptcha replaces its native CAPTCHA.
+* Preserved the visible hCaptcha widget in Essential Addons registration after its form markup is sanitized.
+* Kept wpDiscuz comment reCAPTCHA active when hCaptcha protects subscriptions only.
+* Avoided duplicate CAPTCHA challenges on Wordfence-protected WordPress registration forms.
+* Simplified the settings screen with keys and setup guidance first, an optional setup wizard, and an Advanced tab for less common options.
+* Recovered form submissions on long-open pages by refreshing expired timing tokens and retrying token requests with a fresh nonce.
+* Removed the Show Anti-Spam Indicators setting and indicators from the Integrations page, because all integrations now use the Anti-Spam protection.
+* Fixed error responses for rejected hCaptcha checks in WooCommerce Store API checkout.
+* Fixed Easy Digital Downloads checkout to show hCaptcha errors in its standard notices.
+* Fixed content protection on sites using plain permalinks.
+* Fixed adaptive hCaptcha after failed login attempts in Fluent Forms, Simple Membership, Ultimate Member, Beaver Builder, and Ultimate Addons.
+* Fixed rendering and validation of existing Ninja Forms hCaptcha fields alongside the plugin's own field.
+* Fixed hCaptcha rendering in Brevo signup widgets.
+* Fixed hCaptcha rendering in Formidable Forms when the CAPTCHA field label is set to "None".
+* Fixed Kadence form CAPTCHA settings changing when saving content.
+* Fixed adaptive hCaptcha on Theme My Login AJAX login forms.
+* Fixed multisite settings being saved to the wrong scope during background updates.
+* Fixed missing Events entries for requests with long User-Agent values.
+* Fixed content protection URL patterns and preserved regular expressions in settings.
+* Fixed Automatic Verification on forms with nonstandard action URLs.
+* Fixed hCaptcha disappearing from ACF Extended forms after page load.
+* Fixed "Token replayed or expired" errors during ACF Extended form submissions.
+* Fixed "Signature mismatch" errors when guests submit custom Auto-Verification forms with Form Submit Time enabled.
+* Fixed a fatal error when rendering the "Theme My Login" login form.
+* Fixed form submission while a Form Submit Time token is loading and added retryable connection error messages.
+* Fixed automatic verification rejecting forms with nested or array input names.
+* Fixed Simple Download Monitor downloads with WordPress script debugging (`SCRIPT_DEBUG`) enabled by loading its source script as a module.
+
= 5.4.1 =
* Fixed WordPress login authentication when login integrations have different protection settings.
* Improved Auto-Verification compatibility with forms on query-based page URLs and Brevo forms, while simplifying form registration storage.
diff --git a/src/js/hcaptcha/hcaptcha.js b/src/js/hcaptcha/hcaptcha.js
index 7796beefc..b95f111ee 100644
--- a/src/js/hcaptcha/hcaptcha.js
+++ b/src/js/hcaptcha/hcaptcha.js
@@ -734,7 +734,27 @@ class HCaptcha {
return;
}
- const { formElement, submitButtonElement } = this.currentForm;
+ const currentForm = this.currentForm;
+ const { formElement, submitButtonElement } = currentForm;
+
+ if ( window.hCaptchaFST && formElement.querySelector( '[name="hcap_fst_token"]' ) ) {
+ return window.hCaptchaFST.runWhenReady(
+ formElement,
+ () => this.submitForm( currentForm ),
+ submitButtonElement,
+ );
+ }
+
+ this.submitForm( currentForm );
+ }
+
+ /**
+ * Resume submission with the form selected before waiting for its timing token.
+ *
+ * @param {Object} currentForm Form being submitted.
+ */
+ submitForm( currentForm ) {
+ const { formElement, submitButtonElement } = currentForm;
if (
'form' !== formElement.tagName.toLowerCase() ||
diff --git a/src/php/ACFE/Form.php b/src/php/ACFE/Form.php
index 60378a753..7903377eb 100644
--- a/src/php/ACFE/Form.php
+++ b/src/php/ACFE/Form.php
@@ -52,6 +52,13 @@ class Form {
*/
private bool $captcha_added = false;
+ /**
+ * Verification result shared by callbacks in one validation stage.
+ *
+ * @var array|null
+ */
+ private ?array $form_validation = null;
+
/**
* Form constructor.
*/
@@ -66,6 +73,7 @@ public function __construct() {
*/
public function init_hooks(): void {
add_action( 'acfe/form/render/before_fields', [ $this, 'before_fields' ] );
+ add_action( 'acfe/form/validate_form', [ $this, 'validate_form' ] );
add_action( self::RENDER_HOOK, [ $this, 'remove_recaptcha_render' ], 8 );
add_action( self::RENDER_HOOK, [ $this, 'add_hcaptcha' ], 11 );
add_filter( self::VALIDATION_HOOK, [ $this, 'remove_recaptcha_verify' ], 9, 4 );
@@ -153,6 +161,33 @@ public function remove_recaptcha_verify( $valid, string $value, array $field, st
return $valid;
}
+ /**
+ * Verify forms with a required CAPTCHA even when its field is omitted from POST.
+ *
+ * @param array $form Registered ACFE form.
+ *
+ * @return void
+ * @noinspection PhpUndefinedFunctionInspection
+ */
+ public function validate_form( array $form ): void {
+ if ( ! $this->has_required_recaptcha( $form ) ) {
+ return;
+ }
+
+ $this->form_validation = null;
+ $result = $this->verify( true, '', [ 'required' => true ], '' );
+ $this->form_validation = [
+ 'form_id' => (int) ( $form['ID'] ?? 0 ),
+ 'submission' => $this->get_transient_name( wp_unslash( $_POST ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- ACFE verifies its form nonce before this hook.
+ 'result' => $result,
+ 'ajax' => wp_doing_ajax(),
+ ];
+
+ if ( true !== $result ) {
+ acf_add_validation_error( '', $result );
+ }
+ }
+
/**
* Verify request.
*
@@ -169,14 +204,53 @@ public function verify( $valid, string $value, array $field, string $input ) {
return $valid;
}
- if ( is_admin() ) {
+ $form = $this->get_form();
+
+ if ( is_admin() && ( ! wp_doing_ajax() || ! $form ) ) {
// In admin, the recaptcha field is required and $valid set to false in the acf_validate_value().
// So, we fix it.
return true;
}
- $form = $this->get_form();
- $this->form_id = $form['ID'] ?? 0;
+ $this->form_id = (int) ( $form['ID'] ?? 0 );
+ // phpcs:ignore WordPress.Security.NonceVerification.Missing
+ $post_data = wp_unslash( $_POST );
+
+ if (
+ null !== $this->form_validation &&
+ $this->form_id === $this->form_validation['form_id'] &&
+ $this->get_transient_name( $post_data ) === $this->form_validation['submission'] &&
+ wp_doing_ajax() === $this->form_validation['ajax']
+ ) {
+ return $this->form_validation['result'];
+ }
+
+ $result = $this->verify_submission( $post_data );
+
+ if ( wp_doing_ajax() ) {
+ // API::verify() clears the consumed proof from POST; bind the in-request result to that state.
+ // phpcs:ignore WordPress.Security.NonceVerification.Missing
+ $validated_data = wp_unslash( $_POST );
+ $this->form_validation = [
+ 'form_id' => $this->form_id,
+ 'submission' => $this->get_transient_name( $validated_data ),
+ 'result' => $result,
+ 'ajax' => true,
+ ];
+ }
+
+ return $result;
+ }
+
+ /**
+ * Verify the current ACFE submission across its AJAX and final POST stages.
+ *
+ * @param array $post_data Unslashed POST data.
+ *
+ * @return bool|string
+ */
+ private function verify_submission( array $post_data ) {
+ $transient_name = $this->get_transient_name( $post_data );
// ACFE uses a two-step submission flow: AJAX field validation first, then a direct POST submission.
// The token/honeypot can only be verified once,
@@ -184,18 +258,16 @@ public function verify( $valid, string $value, array $field, string $input ) {
// On the subsequent direct POST, we retrieve the cached result instead of verifying again
// (which would fail on a consumed token).
if ( wp_doing_ajax() ) {
- // phpcs:ignore WordPress.Security.NonceVerification.Missing
- $post_data = wp_unslash( $_POST );
- $result = API::verify( $this->get_entry( $post_data ) ) ?: true;
+ $result = API::verify( $this->get_entry( $post_data ) ) ?: true;
- set_transient( self::TRANSIENT, [ $this->form_id, $result ], 30 );
+ set_transient( $transient_name, [ $this->form_id, $result ], 30 );
return $result;
}
- $transient = get_transient( self::TRANSIENT );
+ $transient = get_transient( $transient_name );
- delete_transient( self::TRANSIENT );
+ delete_transient( $transient_name );
$form_id = $transient[0] ?? false;
$result = $transient[1] ?? false;
@@ -206,12 +278,27 @@ public function verify( $valid, string $value, array $field, string $input ) {
// Some ACFE forms submit directly without the AJAX validation step.
// In that case, verify the current POST once instead of requiring a transient.
- // phpcs:ignore WordPress.Security.NonceVerification.Missing
- $post_data = wp_unslash( $_POST );
-
return API::verify( $this->get_entry( $post_data ) ) ?: true;
}
+ /**
+ * Bind the cached validation result to the same tokens and submitted answers.
+ *
+ * @param array $post_data Post data.
+ *
+ * @return string
+ */
+ private function get_transient_name( array $post_data ): string {
+ $submission = [
+ $this->form_id,
+ $post_data['h-captcha-response'] ?? '',
+ $post_data['hcap_fst_token'] ?? '',
+ $post_data['acf'] ?? [],
+ ];
+
+ return self::TRANSIENT . '_' . hash( 'sha256', wp_json_encode( $submission ) );
+ }
+
/**
* Get entry.
*
@@ -374,6 +461,40 @@ private function get_form() {
return $form ?: false;
}
+ /**
+ * Find required CAPTCHA fields from the form's registered field groups.
+ *
+ * @param array $form Registered ACFE form.
+ *
+ * @return bool
+ * @noinspection PhpUndefinedFunctionInspection
+ */
+ private function has_required_recaptcha( array $form ): bool {
+ $field_groups = acfe_as_array( $form['field_groups'] ?? [] );
+
+ if ( ! empty( $form['post_field_groups'] ) ) {
+ $field_groups = wp_list_pluck( acf_get_field_groups( [ 'post_id' => $form['post_field_groups'] ] ), 'key' );
+ }
+
+ foreach ( $field_groups as $group_key ) {
+ $fields = acf_get_fields( $group_key );
+
+ if ( ! $fields ) {
+ continue;
+ }
+
+ foreach ( acfe_get_fields_details_recursive( $fields ) as $details ) {
+ $field = $details['field'];
+
+ if ( $this->is_recaptcha( $field ) && ! empty( $field['required'] ) ) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
/**
* Enqueue scripts.
*
diff --git a/src/php/Abilities/Abilities.php b/src/php/Abilities/Abilities.php
index 1790e225a..87861de90 100644
--- a/src/php/Abilities/Abilities.php
+++ b/src/php/Abilities/Abilities.php
@@ -60,6 +60,11 @@ class Abilities {
*/
private const ABILITY_IMPORT_SETTINGS = 'hcaptcha/import-settings';
+ /**
+ * Maximum number of bytes read from an imported settings file.
+ */
+ private const MAX_IMPORT_FILE_BYTES = 1024 * 1024;
+
/**
* Maximum number of top offenders to return in a threat snapshot.
*/
@@ -636,25 +641,11 @@ public function import_settings( $input ) {
unset( $payload['allow_keys'], $payload['dry_run'], $payload['input_file'] );
if ( '' !== $input_file ) {
- if ( ! file_exists( $input_file ) || ! is_readable( $input_file ) ) {
- return new WP_Error(
- 'hcaptcha_invalid_payload',
- __( 'Input file not found or unreadable.', 'hcaptcha-for-forms-and-more' )
- );
- }
-
- // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
- $json = file_get_contents( $input_file );
- $data = Utils::json_decode_arr( $json );
+ $payload = $this->read_import_file( $input_file );
- if ( ! $data || JSON_ERROR_NONE !== json_last_error() ) {
- return new WP_Error(
- 'hcaptcha_invalid_payload',
- __( 'Invalid JSON in input file.', 'hcaptcha-for-forms-and-more' )
- );
+ if ( is_wp_error( $payload ) ) {
+ return $payload;
}
-
- $payload = $data;
}
if ( ! is_array( $payload ) || empty( $payload ) ) {
@@ -705,6 +696,52 @@ public function import_settings( $input ) {
];
}
+ /**
+ * Read a regular settings file within the import size limit.
+ *
+ * @param string|false $input_file Canonical file path or failed resolution.
+ *
+ * @return array|WP_Error
+ */
+ private function read_import_file( $input_file ) {
+ if ( ! is_string( $input_file ) || ! is_file( $input_file ) || ! is_readable( $input_file ) ) {
+ return new WP_Error(
+ 'hcaptcha_invalid_payload',
+ __( 'Input file not found or unreadable.', 'hcaptcha-for-forms-and-more' )
+ );
+ }
+
+ $file_size = filesize( $input_file );
+
+ if ( false === $file_size || self::MAX_IMPORT_FILE_BYTES < $file_size ) {
+ return new WP_Error(
+ 'hcaptcha_invalid_payload',
+ __( 'Input file is too large.', 'hcaptcha-for-forms-and-more' )
+ );
+ }
+
+ // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
+ $json = file_get_contents( $input_file, false, null, 0, self::MAX_IMPORT_FILE_BYTES + 1 );
+
+ if ( false === $json || self::MAX_IMPORT_FILE_BYTES < strlen( $json ) ) {
+ return new WP_Error(
+ 'hcaptcha_invalid_payload',
+ __( 'Input file is too large or cannot be read.', 'hcaptcha-for-forms-and-more' )
+ );
+ }
+
+ $data = Utils::json_decode_arr( $json );
+
+ if ( ! $data || JSON_ERROR_NONE !== json_last_error() ) {
+ return new WP_Error(
+ 'hcaptcha_invalid_payload',
+ __( 'Invalid JSON in input file.', 'hcaptcha-for-forms-and-more' )
+ );
+ }
+
+ return $data;
+ }
+
/**
* Convert a window string (e.g., 5m) to seconds.
*
@@ -1299,13 +1336,8 @@ private function get_offender_blocks(): array {
$raw = get_option( self::OPTION_OFFENDER_BLOCKS, [] );
$raw = is_array( $raw ) ? $raw : [];
- $blocks = $this->prune_offender_blocks( $raw, time() );
-
- if ( $blocks !== $raw ) {
- $this->set_offender_blocks( $blocks );
- }
-
- return $blocks;
+ // Public lookups must not overwrite bans added after this snapshot was read.
+ return $this->prune_offender_blocks( $raw, time() );
}
/**
diff --git a/src/php/Abstracts/CommentBase.php b/src/php/Abstracts/CommentBase.php
index 4ce3d161d..21261a330 100644
--- a/src/php/Abstracts/CommentBase.php
+++ b/src/php/Abstracts/CommentBase.php
@@ -12,6 +12,7 @@
use HCaptcha\Helpers\HCaptcha;
use HCaptcha\Helpers\Request;
use WP_Error;
+use WP_REST_Request;
/**
* Class CommentBase
@@ -56,6 +57,61 @@ protected function init_hooks(): void {
add_filter( 'pre_comment_approved', [ $this, 'pre_comment_approved' ], 20, 2 );
}
+ /**
+ * Verify a native REST comment before WordPress processes approval.
+ *
+ * @param array|WP_Error $prepared_comment Prepared comment or an earlier error.
+ * @param WP_REST_Request $request REST request.
+ *
+ * @return array|WP_Error
+ */
+ public function verify_rest_comment( $prepared_comment, WP_REST_Request $request ) {
+ if (
+ ! $request->is_method( 'POST' ) ||
+ '/wp/v2/comments' !== strtolower( $request->get_route() ) ||
+ 'note' === $request['type'] ||
+ is_wp_error( $prepared_comment )
+ ) {
+ return $prepared_comment;
+ }
+
+ $comment_data = wp_parse_args(
+ (array) $prepared_comment,
+ [
+ 'comment_author' => '',
+ 'comment_author_email' => '',
+ 'comment_author_url' => '',
+ 'comment_content' => '',
+ 'comment_author_IP' => '',
+ 'comment_agent' => '',
+ ]
+ );
+ $this->form_id = (int) ( $comment_data['comment_post_ID'] ?? 0 );
+ $comment_data['comment_author_IP'] = hcap_get_user_ip();
+ $entry = $this->get_entry( $comment_data );
+ $entry['post_data'] = $request->get_params();
+ $entry['nonce_name'] = static::NONCE;
+ $entry['nonce_action'] = static::ACTION;
+
+ // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Restore unrelated POST data after checking this REST request.
+ $original_post = $_POST;
+
+ // REST proof must come from this request, not from an outer form or batch request.
+ $_POST = [];
+
+ try {
+ $this->result = API::verify( $entry );
+ } finally {
+ $_POST = $original_post;
+ }
+
+ if ( null !== $this->result ) {
+ return new WP_Error( 'invalid_hcaptcha', (string) $this->result, [ 'status' => 400 ] );
+ }
+
+ return $prepared_comment;
+ }
+
/**
* Get signature.
*
@@ -84,8 +140,10 @@ public function display_signature(): void {
public function verify( $comment_data ): array {
$comment_data = (array) $comment_data;
- if ( ! Request::is_frontend() ) {
- // Do not work in ajax mode. It is served by WPDiscuz.
+ if ( ! Request::is_frontend() && ! $this->is_native_comment_submission() ) {
+ // Skip other transports; WPDiscuz handles its own AJAX comment submissions.
+ $this->result = null;
+
return $comment_data;
}
@@ -117,6 +175,28 @@ public function verify( $comment_data ): array {
return $comment_data;
}
+ /**
+ * Whether WordPress itself is handling the submitted comment.
+ *
+ * WooCommerce may define DOING_AJAX from a query argument even when the
+ * request is still handled by the core comment submission script.
+ *
+ * @return bool
+ */
+ private function is_native_comment_submission(): bool {
+ // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Server-provided filesystem path must retain its separators.
+ $script = $_SERVER['SCRIPT_FILENAME'] ?? '';
+
+ if ( ! is_string( $script ) || '' === $script ) {
+ return false;
+ }
+
+ $core_script = realpath( ABSPATH . 'wp-comments-post.php' );
+ $request_script = realpath( $script );
+
+ return false !== $core_script && $core_script === $request_script;
+ }
+
/**
* Pre-approve comment.
*
diff --git a/src/php/Abstracts/FormOwnerBase.php b/src/php/Abstracts/FormOwnerBase.php
index 126ddaf23..12648812b 100644
--- a/src/php/Abstracts/FormOwnerBase.php
+++ b/src/php/Abstracts/FormOwnerBase.php
@@ -51,7 +51,7 @@ public function claim_request_owner( $owner, array $id ) {
return $owner;
}
- return $this->get_expected_id() === $id ? static::class : $owner;
+ return $this->get_expected_id() === $id && $this->can_handle_request() ? static::class : $owner;
}
/**
@@ -105,6 +105,15 @@ protected function get_request_ownership(): ?bool {
return static::class === $owner;
}
+ /**
+ * Whether this verifier can handle the submitted form.
+ *
+ * @return bool
+ */
+ protected function can_handle_request(): bool {
+ return true;
+ }
+
/**
* Whether the current request has the expected WordPress login action.
*
diff --git a/src/php/Abstracts/LoginBase.php b/src/php/Abstracts/LoginBase.php
index 8441f9449..86f1bc410 100644
--- a/src/php/Abstracts/LoginBase.php
+++ b/src/php/Abstracts/LoginBase.php
@@ -113,19 +113,28 @@ public function __construct() {
*/
protected function init_hooks(): void {
add_action( 'hcap_signature', [ $this, 'display_signature' ] );
- add_action( 'login_form', [ $this, 'display_signature' ], PHP_INT_MAX );
+ add_action( 'login_form', [ $this, 'display_signature' ], PHP_INT_MAX, 0 );
add_filter( 'login_form_middle', [ $this, 'add_signature' ], PHP_INT_MAX, 2 );
add_filter( 'wp_authenticate_user', [ $this, 'check_signature' ], PHP_INT_MAX, 2 );
add_filter( 'authenticate', [ $this, 'hide_login_error' ], 100, 3 );
add_filter( 'hcap_auto_verify_unmatched_form', [ $this, 'defer_auto_verification' ], 10, 3 );
add_filter( 'hcap_wp_login_can_skip_verification', [ $this, 'allow_wp_login_skip_verification' ] );
- add_action( 'wp_login', [ $this, 'login' ], 10, 2 );
- add_action( 'wp_login_failed', [ $this, 'login_failed' ] );
+ $this->init_login_attempt_hooks();
add_action( 'hcap_delay_api', [ $this, 'delay_api' ], 0 );
}
+ /**
+ * Register adaptive login counters for integrations with custom hooks.
+ *
+ * @return void
+ */
+ protected function init_login_attempt_hooks(): void {
+ add_action( 'wp_login', [ $this, 'login' ], 10, 2 );
+ add_action( 'wp_login_failed', [ $this, 'login_failed' ] );
+ }
+
/**
* Display signature.
*
@@ -391,6 +400,11 @@ public function login( string $user_login, WP_User $user ): void {
* @noinspection PhpMissingParamTypeInspection
*/
public function login_failed( string $username, $error = null ): void {
+ // Simple Membership may call wp_signon after its own successful login.
+ if ( doing_action( 'wp_login_failed' ) && doing_action( 'swpm_after_login_authentication' ) ) {
+ return;
+ }
+
if ( doing_action( 'wp_login_failed' ) ) {
$action_count = did_action( 'wp_login_failed' );
diff --git a/src/php/Abstracts/LostPasswordBase.php b/src/php/Abstracts/LostPasswordBase.php
index af36646ab..f06931a91 100644
--- a/src/php/Abstracts/LostPasswordBase.php
+++ b/src/php/Abstracts/LostPasswordBase.php
@@ -11,6 +11,7 @@
use HCaptcha\Helpers\EntryData;
use HCaptcha\Helpers\HCaptcha;
use WP_Error;
+use WP_User;
/**
* Class LostPasswordBase
@@ -39,7 +40,7 @@ protected function init_hooks(): void {
$this->init_auto_verify_hooks();
add_action( static::ADD_CAPTCHA_ACTION, [ $this, 'add_captcha' ] );
- add_action( 'lostpassword_post', [ $this, 'verify' ] );
+ add_action( 'lostpassword_post', [ $this, 'verify' ], 10, 2 );
}
/**
@@ -60,11 +61,12 @@ public function add_captcha(): void {
/**
* Verify a lost password form.
*
- * @param WP_Error|mixed $errors Error.
+ * @param WP_Error|mixed $errors Error.
+ * @param WP_User|false|null $user Native resolved recovery recipient.
*
* @return void
*/
- public function verify( $errors ): void {
+ public function verify( $errors, $user = null ): void {
if ( ! $this->can_handle_request() ) {
// This class cannot handle a submitted lost password form.
return;
@@ -82,18 +84,17 @@ public function verify( $errors ): void {
return;
}
- $error_message = API::verify(
- [
- 'nonce_name' => static::NONCE,
- 'nonce_action' => static::ACTION,
- 'data' => EntryData::from_post(
- [
- 'username' => [ 'user_login', 'user_email' ],
- ]
- ),
- 'expected_id' => $this->get_expected_id(),
- ]
- );
+ $entry = [
+ 'nonce_name' => static::NONCE,
+ 'nonce_action' => static::ACTION,
+ 'data' => EntryData::from_post(
+ [
+ 'username' => [ 'user_login', 'user_email' ],
+ ]
+ ),
+ 'expected_id' => $this->get_expected_id(),
+ ];
+ $error_message = API::verify( EntryData::with_emails( $entry, $user instanceof WP_User ? [ $user->user_email ] : [] ) );
HCaptcha::add_error_message( $errors, $error_message );
}
@@ -116,7 +117,16 @@ protected function get_expected_id(): array {
* @return bool
*/
protected function is_owner_action(): bool {
- return $this->is_wp_login_action( 'lostpassword' ) && $this->can_handle_request();
+ return $this->is_lost_password_action() && $this->can_handle_request();
+ }
+
+ /**
+ * Whether the current request uses a native WordPress recovery action.
+ *
+ * @return bool
+ */
+ protected function is_lost_password_action(): bool {
+ return $this->is_wp_login_action( 'lostpassword' ) || $this->is_wp_login_action( 'retrievepassword' );
}
/**
@@ -124,7 +134,7 @@ protected function is_owner_action(): bool {
*
* @return bool
*/
- private function can_handle_request(): bool {
+ protected function can_handle_request(): bool {
// Nonce is verified later by the owning form integration.
// phpcs:disable WordPress.Security.NonceVerification.Missing
$post_value = isset( $_POST[ static::POST_KEY ] ) ?
diff --git a/src/php/Abstracts/RegisterBase.php b/src/php/Abstracts/RegisterBase.php
index d14815e63..89044a2e6 100644
--- a/src/php/Abstracts/RegisterBase.php
+++ b/src/php/Abstracts/RegisterBase.php
@@ -33,6 +33,6 @@ protected function init_hooks(): void {
* @return bool
*/
protected function is_owner_action(): bool {
- return $this->is_wp_login_action( 'register' );
+ return $this->is_wp_login_action( 'register' ) && $this->can_handle_request();
}
}
diff --git a/src/php/Admin/Events/Events.php b/src/php/Admin/Events/Events.php
index 4a35ba34f..4d197f875 100644
--- a/src/php/Admin/Events/Events.php
+++ b/src/php/Admin/Events/Events.php
@@ -12,7 +12,7 @@
use HCaptcha\Helpers\HCaptcha;
use HCaptcha\Migrations\Migrations;
use HCaptcha\Settings\General;
-use HCaptcha\Settings\PluginSettingsBase;
+use HCaptcha\Settings\SettingsStorage;
use Throwable;
/**
@@ -95,11 +95,11 @@ class Events {
];
/**
- * Saved flag.
+ * Whether this request has already attempted event collection.
*
* @var bool
*/
- private bool $saved = false;
+ private bool $save_attempted = false;
/**
* Class constructor.
@@ -140,11 +140,11 @@ private function init_hooks(): void {
public function save_event( $result, array $deprecated, object $error_info ) {
global $wpdb;
- if ( $this->saved ) {
+ if ( $this->save_attempted ) {
return $result;
}
- $this->saved = true;
+ $this->save_attempted = true;
if ( ! ( is_string( $result ) || is_null( $result ) ) ) {
return $result;
@@ -162,9 +162,9 @@ public function save_event( $result, array $deprecated, object $error_info ) {
return $result;
}
- $event = self::prepare_event( $event_id, $error_info, $settings );
-
try {
+ $event = self::prepare_event( $event_id, $error_info, $settings );
+
if ( ! self::acquire_write_lock() ) {
return $result;
}
@@ -177,7 +177,9 @@ public function save_event( $result, array $deprecated, object $error_info ) {
}
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
- $wpdb->insert( $wpdb->prefix . self::TABLE_NAME, $event );
+ if ( false === $wpdb->insert( $wpdb->prefix . self::TABLE_NAME, $event ) ) {
+ return $result;
+ }
} finally {
self::release_write_lock();
}
@@ -199,6 +201,8 @@ public function save_event( $result, array $deprecated, object $error_info ) {
* @return array
*/
private static function prepare_event( array $event_id, object $error_info, object $settings ): array {
+ global $wpdb;
+
$ip = '';
$user_agent = '';
@@ -209,6 +213,10 @@ private static function prepare_event( array $event_id, object $error_info, obje
if ( $settings->is_on( 'anonymous' ) ) {
$user_agent = wp_hash( $user_agent );
}
+
+ // Normalize after hashing, using the actual column's charset and character limit.
+ $user_agent = $wpdb->strip_invalid_text_for_column( $wpdb->prefix . self::TABLE_NAME, 'user_agent', $user_agent );
+ $user_agent = is_wp_error( $user_agent ) ? '' : $user_agent;
}
if ( $settings->is_on( 'collect_ip' ) ) {
@@ -529,9 +537,8 @@ public static function create_table( bool $force = false ): void {
* @return bool
*/
public static function table_exists(): bool {
- $settings = hcaptcha()->settings();
- $raw = $settings ? $settings->get_raw_settings() : get_option( PluginSettingsBase::OPTION_NAME, [] );
- $raw = is_array( $raw ) ? $raw : [];
+ // The table marker belongs to the current blog's database prefix.
+ $raw = SettingsStorage::get( false );
return 'on' === ( $raw[ self::TABLE_CREATED_OPTION_NAME ] ?? '' );
}
@@ -562,12 +569,7 @@ private static function database_table_exists(): bool {
* @return void
*/
private static function mark_table_created(): void {
- $option = get_option( PluginSettingsBase::OPTION_NAME, [] );
- $option = is_array( $option ) ? $option : [];
-
- $option[ self::TABLE_CREATED_OPTION_NAME ] = 'on';
-
- update_option( PluginSettingsBase::OPTION_NAME, $option );
+ SettingsStorage::update( [ self::TABLE_CREATED_OPTION_NAME => 'on' ], [], false );
}
/**
@@ -576,15 +578,13 @@ private static function mark_table_created(): void {
* @return void
*/
private static function unmark_table_created(): void {
- $option = get_option( PluginSettingsBase::OPTION_NAME, [] );
+ $option = SettingsStorage::get( false );
- if ( ! is_array( $option ) || ! array_key_exists( self::TABLE_CREATED_OPTION_NAME, $option ) ) {
+ if ( ! array_key_exists( self::TABLE_CREATED_OPTION_NAME, $option ) ) {
return;
}
- unset( $option[ self::TABLE_CREATED_OPTION_NAME ] );
-
- update_option( PluginSettingsBase::OPTION_NAME, $option );
+ SettingsStorage::update( [], [ self::TABLE_CREATED_OPTION_NAME ], false );
}
/**
@@ -651,6 +651,7 @@ public static function cleanup_trash(): void {
* Whether the Events table has the retention schema.
*
* @return bool
+ * @noinspection PhpCastIsUnnecessaryInspection
*/
public static function is_retention_schema_ready(): bool {
global $wpdb;
@@ -708,6 +709,7 @@ private static function cleanup_expired_rows(): void {
* @param int $days Retention in days.
*
* @return void
+ * @noinspection PhpCastIsUnnecessaryInspection
*/
private static function delete_expired_rows( string $status, string $date_column, string $index, int $days ): void {
global $wpdb;
@@ -791,7 +793,7 @@ private static function has_capacity(): bool {
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
$result = $wpdb->query(
$wpdb->prepare(
- "SELECT id FROM $table_name FORCE INDEX (PRIMARY) ORDER BY id LIMIT %d, 1",
+ "SELECT id FROM $table_name FORCE INDEX (`PRIMARY`) ORDER BY id LIMIT %d, 1",
$max_rows - 1
)
);
diff --git a/src/php/Admin/Notifications.php b/src/php/Admin/Notifications.php
index 50fc5e858..b67dc0245 100644
--- a/src/php/Admin/Notifications.php
+++ b/src/php/Admin/Notifications.php
@@ -85,25 +85,23 @@ protected function get_notifications(): array {
$notifications = [
'register' => [
- 'title' => __( 'Get your hCaptcha site keys', 'hcaptcha-for-forms-and-more' ),
- 'message' => sprintf(
- /* translators: 1: hCaptcha link, 2: register link. */
- __( 'To use %1$s, please register %2$s to get your site and secret keys.', 'hcaptcha-for-forms-and-more' ),
- sprintf(
- '%2$s',
- $urls['hcaptcha'],
- __( 'hCaptcha', 'hcaptcha-for-forms-and-more' )
- ),
+ 'title' => __( 'Set up hCaptcha', 'hcaptcha-for-forms-and-more' ),
+ 'message' => sprintf(
+ /* translators: %s: Link to create an hCaptcha account. */
+ __( 'To use the plugin, %s and get your keys. Then select Live mode below and enter your keys.', 'hcaptcha-for-forms-and-more' ),
sprintf(
- '%2$s',
- $urls['register'],
- __( 'here', 'hcaptcha-for-forms-and-more' )
+ '%2$s',
+ esc_url( $urls['register'] ),
+ esc_html__( 'create an hCaptcha account', 'hcaptcha-for-forms-and-more' )
)
),
- 'button' => [
- 'url' => $urls['register'],
- 'text' => __( 'Get site keys', 'hcaptcha-for-forms-and-more' ),
+ 'button' => [
+ 'url' => $urls['onboarding'],
+ 'text' => __( 'Show Setup Wizard', 'hcaptcha-for-forms-and-more' ),
+ 'target' => '_self',
],
+ 'notice_type' => 'warning',
+ 'dismissible' => false,
],
'pro-free-trial' => [
'title' => __( 'Try Pro for free', 'hcaptcha-for-forms-and-more' ),
@@ -373,6 +371,15 @@ protected function get_notifications(): array {
'text' => __( 'Review headers', 'hcaptcha-for-forms-and-more' ),
],
],
+ // Added in 5.5.0.
+ 'rest-api-protection' => [
+ 'title' => __( 'Unique REST API Protection', 'hcaptcha-for-forms-and-more' ),
+ 'message' => __( 'hCaptcha now protects selected content in WordPress REST responses and search, verifies native REST comments, and blocks REST post-password attempts when the corresponding protections are enabled. No other plugin in our October 2026 review of the 10 most-installed WordPress.org plugins tagged captcha offered all three.', 'hcaptcha-for-forms-and-more' ),
+ 'button' => [
+ 'url' => $urls['protect_content'],
+ 'text' => __( 'Configure Content Protection', 'hcaptcha-for-forms-and-more' ),
+ ],
+ ],
];
$notifications = $this->select_active_notifications( $notifications );
@@ -422,24 +429,19 @@ private function cf7_admin_notification(): array {
/**
* Show notifications.
*
+ * @param bool $setup_only Whether to show only the setup notification.
+ *
* @return void
*/
- public function show(): void {
- $notifications = $this->get_notifications();
-
- $user = wp_get_current_user();
- $user_id = $user->ID ?? 0;
-
- // phpcs:ignore Generic.Commenting.DocComment.MissingShort
- $dismissed = get_user_meta( $user_id, self::HCAPTCHA_DISMISSED_META_KEY, true ) ?: [];
- $notifications = array_diff_key( $notifications, array_flip( $dismissed ) );
+ public function show( bool $setup_only = false ): void {
+ $notifications = $this->get_visible_notifications( $setup_only );
if ( ! $notifications ) {
return;
}
?>
-
+
@@ -466,6 +468,9 @@ public function show(): void {
$button_url = $notification['button']['url'];
$button_text = $notification['button']['text'];
$button_lightbox = $notification['button']['lightbox'];
+ $button_target = $notification['button']['target'];
+ $notice_type = $notification['notice_type'];
+ $dismissible = $notification['dismissible'];
$lightbox_class = $button_lightbox ? ' hcaptcha-lightbox' : '';
ob_start();
@@ -479,7 +484,7 @@ public function show(): void {
+ target="">
"
// We need the 'inline' class below to prevent moving the 'notice' div after h2 by common.js script in WP Core.
?>
@@ -523,6 +528,53 @@ class="hcaptcha-notification notice notice-info is-dismissible inline"
get_notifications();
+
+ if ( $setup_only ) {
+ return array_intersect_key( $notifications, [ 'register' => true ] );
+ }
+
+ $user = wp_get_current_user();
+ $user_id = $user->ID ?? 0;
+
+ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
+ $dismissed = get_user_meta( $user_id, self::HCAPTCHA_DISMISSED_META_KEY, true ) ?: [];
+
+ return array_diff_key( $notifications, array_flip( $dismissed ) );
+ }
+
+ /**
+ * Whether the current user has dismissed an active notification.
+ *
+ * @return bool
+ */
+ public function has_dismissed_notifications(): bool {
+ $user = wp_get_current_user();
+ $dismissed = get_user_meta( $user->ID ?? 0, self::HCAPTCHA_DISMISSED_META_KEY, true );
+
+ if ( ! is_array( $dismissed ) || ! $dismissed ) {
+ return false;
+ }
+
+ $notifications = $this->get_notifications();
+
+ foreach ( $dismissed as $id ) {
+ if ( is_string( $id ) && isset( $notifications[ $id ] ) && ( $notifications[ $id ]['dismissible'] ?? true ) ) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
/**
* Enqueue class scripts.
*
@@ -702,6 +754,9 @@ private function validate_notification( array $notification ): array {
$notification['button']['url'] = $notification['button']['url'] ?? '';
$notification['button']['text'] = $notification['button']['text'] ?? '';
$notification['button']['lightbox'] = $notification['button']['lightbox'] ?? '';
+ $notification['button']['target'] = $notification['button']['target'] ?? '_blank';
+ $notification['notice_type'] = $notification['notice_type'] ?? 'info';
+ $notification['dismissible'] = $notification['dismissible'] ?? true;
return $notification;
}
@@ -732,7 +787,7 @@ private function select_active_notifications( array $notifications ): array {
}
}
- if ( ! empty( $settings->get_site_key() ) && ! empty( $settings->get_secret_key() ) ) {
+ if ( ! empty( $settings->get( 'site_key' ) ) && ! empty( $settings->get( 'secret_key' ) ) ) {
unset( $notifications['register'] );
}
diff --git a/src/php/Admin/NotificationsBase.php b/src/php/Admin/NotificationsBase.php
index 288d35533..0c08c3a44 100644
--- a/src/php/Admin/NotificationsBase.php
+++ b/src/php/Admin/NotificationsBase.php
@@ -7,6 +7,7 @@
namespace HCaptcha\Admin;
+use HCaptcha\Settings\Advanced;
use HCaptcha\Settings\AntiSpamPage;
use HCaptcha\Settings\EventsPage;
use HCaptcha\Settings\FormsPage;
@@ -42,60 +43,62 @@ protected function prepare_urls(): array {
$utm_sk = $utm . 'sk';
$utm_not = $utm . 'not';
- $urls['general'] = $settings->tab_url( General::class );
- $urls['anti_spam_page'] = $settings->tab_url( AntiSpamPage::class );
- $urls['integrations'] = $settings->tab_url( Integrations::class );
- $urls['forms'] = $settings->tab_url( FormsPage::class );
- $urls['events'] = $settings->tab_url( EventsPage::class );
- $urls['tools'] = $settings->tab_url( Tools::class );
- $urls['hcaptcha'] = 'https://www.hcaptcha.com' . $utm_sk;
- $urls['register'] = 'https://www.hcaptcha.com/signup-interstitial' . $utm_sk;
- $urls['pro'] = 'https://www.hcaptcha.com/pro' . $utm_not;
- $urls['dashboard'] = 'https://dashboard.hcaptcha.com' . $utm_not;
- $urls['post_leadership'] = 'https://www.hcaptcha.com/post/hcaptcha-named-a-technology-leader-in-bot-management' . $utm_not;
- $urls['rate'] = 'https://wordpress.org/support/plugin/hcaptcha-for-forms-and-more/reviews/#new-post';
- $urls['search_integrations'] = $urls['integrations'] . '#hcaptcha-integrations-search';
- $urls['enterprise_features'] = 'https://www.hcaptcha.com/#enterprise-features' . $utm_not;
- $urls['statistics'] = $urls['general'] . '#statistics_1';
- $urls['force'] = $urls['general'] . '#force_1';
- $urls['elementor_edit_form'] = HCAPTCHA_URL . '/assets/images/elementor-edit-form.png';
- $urls['size'] = $urls['general'] . '#size';
- $urls['passive_mode_demo'] = HCAPTCHA_URL . '/assets/images/demo/passive-mode.gif';
- $urls['protect_content'] = $urls['general'] . '#protect_content_1';
- $urls['protect_content_demo'] = HCAPTCHA_URL . '/assets/images/demo/protect-content.gif';
- $urls['antispam'] = $urls['general'] . '#antispam_1';
- $urls['antispam_demo'] = HCAPTCHA_URL . '/assets/images/demo/antispam.gif';
- $urls['token'] = $urls['general'] . '#set_min_submit_time_1';
- $urls['honeypot'] = $urls['general'] . '#honeypot_1';
- $urls['honeypot_demo'] = HCAPTCHA_URL . '/assets/images/demo/honeypot.png';
- $urls['onboarding'] = add_query_arg(
+ $urls['general'] = $settings->tab_url( General::class );
+ $urls['advanced'] = $settings->tab_url( Advanced::class );
+ $urls['anti_spam_page'] = $settings->tab_url( AntiSpamPage::class );
+ $urls['integrations'] = $settings->tab_url( Integrations::class );
+ $urls['forms'] = $settings->tab_url( FormsPage::class );
+ $urls['events'] = $settings->tab_url( EventsPage::class );
+ $urls['tools'] = $settings->tab_url( Tools::class );
+ $urls['hcaptcha'] = 'https://www.hcaptcha.com' . $utm_sk;
+ $urls['register'] = 'https://www.hcaptcha.com/signup-interstitial' . $utm_sk;
+ $urls['pro'] = 'https://www.hcaptcha.com/pro' . $utm_not;
+ $urls['dashboard'] = 'https://dashboard.hcaptcha.com' . $utm_not;
+ $urls['post_leadership'] = 'https://www.hcaptcha.com/post/hcaptcha-named-a-technology-leader-in-bot-management' . $utm_not;
+ $urls['rate'] = 'https://wordpress.org/support/plugin/hcaptcha-for-forms-and-more/reviews/#new-post';
+ $urls['search_integrations'] = $urls['integrations'] . '#hcaptcha-integrations-search';
+ $urls['enterprise_features'] = 'https://www.hcaptcha.com/#enterprise-features' . $utm_not;
+ $urls['statistics'] = $urls['advanced'] . '#statistics_1';
+ $urls['force'] = $urls['general'] . '#force_1';
+ $urls['elementor_edit_form'] = HCAPTCHA_URL . '/assets/images/elementor-edit-form.png';
+ $urls['size'] = $urls['general'] . '#size';
+ $urls['passive_mode_demo'] = HCAPTCHA_URL . '/assets/images/demo/passive-mode.gif';
+ $urls['protect_content'] = $urls['advanced'] . '#protect_content_1';
+ $urls['protect_content_demo'] = HCAPTCHA_URL . '/assets/images/demo/protect-content.gif';
+ $urls['antispam'] = $urls['general'] . '#antispam_1';
+ $urls['antispam_demo'] = HCAPTCHA_URL . '/assets/images/demo/antispam.gif';
+ $urls['token'] = $urls['general'] . '#set_min_submit_time_1';
+ $urls['honeypot'] = $urls['general'] . '#honeypot_1';
+ $urls['honeypot_demo'] = HCAPTCHA_URL . '/assets/images/demo/honeypot.png';
+ $urls['onboarding'] = add_query_arg(
[
OnboardingWizard::STEP_PARAM => 1,
OnboardingWizard::NONCE_PARAM => wp_create_nonce( OnboardingWizard::STEP_ACTION ),
],
$urls['general']
);
- $urls['onboarding_demo'] = HCAPTCHA_URL . '/assets/images/demo/onboarding.gif';
- $urls['ai_abilities'] = 'https://wordpress.org/plugins/hcaptcha-for-forms-and-more/#how%20do%20i%20use%20the%20new%20ai%20/%20abilities%20features%3F';
- $urls['ai_abilities_img'] = HCAPTCHA_URL . '/assets/images/ai-abilities.png';
- $urls['export_import_img'] = HCAPTCHA_URL . '/assets/images/export-import.png';
- $urls['country_access'] = $urls['general'] . '#blacklisted_countries';
- $urls['country_access_img'] = HCAPTCHA_URL . '/assets/images/country-access.png';
- $urls['migration_wizard'] = $urls['tools'] . '#hcaptcha-migration-wizard';
- $urls['migration_wizard_img'] = HCAPTCHA_URL . '/assets/images/migration-wizard.png';
- $urls['trusted_ip_headers'] = $urls['anti_spam_page'] . '#trusted_address_headers';
- $urls['trusted_ip_headers_img'] = HCAPTCHA_URL . '/assets/images/trusted-ip-headers.png';
- $urls['forms_events_trash'] = $urls['forms'];
- $urls['forms_events_trash_img'] = HCAPTCHA_URL . '/assets/images/forms-events-trash.png';
- $urls['events_dashboard_img'] = HCAPTCHA_URL . '/assets/images/events-dashboard.png';
- $urls['paypal_payments'] = $urls['integrations'] . '#paypal_payments_status_1';
- $urls['paypal_payments_img'] = HCAPTCHA_URL . '/assets/images/woocommerce-paypal-payments.png';
- $urls['command_palette'] = $urls['general'];
- $urls['command_palette_img'] = HCAPTCHA_URL . '/assets/images/magnifying-glass.svg';
- $urls['theme_editor'] = $urls['general'] . '#config_params';
- $urls['theme_editor_img'] = HCAPTCHA_URL . '/assets/images/advanced-theme-editor.jpg';
- $urls['anti_spam_checks'] = $urls['anti_spam_page'] . '#antispam_1';
- $urls['anti_spam_checks_img'] = HCAPTCHA_URL . '/assets/images/smarter-anti-spam-checks.png';
+ $urls['onboarding_demo'] = HCAPTCHA_URL . '/assets/images/demo/onboarding.gif';
+ $urls['ai_abilities'] = 'https://wordpress.org/plugins/hcaptcha-for-forms-and-more/#how%20do%20i%20use%20the%20new%20ai%20/%20abilities%20features%3F';
+ $urls['ai_abilities_img'] = HCAPTCHA_URL . '/assets/images/ai-abilities.png';
+ $urls['export_import_img'] = HCAPTCHA_URL . '/assets/images/export-import.png';
+ $urls['country_access'] = $urls['general'] . '#blacklisted_countries';
+ $urls['country_access_img'] = HCAPTCHA_URL . '/assets/images/country-access.png';
+ $urls['migration_wizard'] = $urls['tools'] . '#hcaptcha-migration-wizard';
+ $urls['migration_wizard_img'] = HCAPTCHA_URL . '/assets/images/migration-wizard.png';
+ $urls['trusted_ip_headers'] = $urls['anti_spam_page'] . '#trusted_address_headers';
+ $urls['trusted_ip_headers_img'] = HCAPTCHA_URL . '/assets/images/trusted-ip-headers.png';
+ $urls['forms_events_trash'] = $urls['forms'];
+ $urls['forms_events_trash_img'] = HCAPTCHA_URL . '/assets/images/forms-events-trash.png';
+ $urls['events_dashboard_img'] = HCAPTCHA_URL . '/assets/images/events-dashboard.png';
+ $urls['paypal_payments'] = $urls['integrations'] . '#paypal_payments_status_1';
+ $urls['paypal_payments_img'] = HCAPTCHA_URL . '/assets/images/woocommerce-paypal-payments.png';
+ $urls['command_palette'] = $urls['general'];
+ $urls['command_palette_img'] = HCAPTCHA_URL . '/assets/images/magnifying-glass.svg';
+ $urls['theme_editor'] = $urls['general'] . '#config_params';
+ $urls['theme_editor_img'] = HCAPTCHA_URL . '/assets/images/advanced-theme-editor.jpg';
+ $urls['anti_spam_checks'] = $urls['anti_spam_page'] . '#antispam_1';
+ $urls['anti_spam_checks_img'] = HCAPTCHA_URL . '/assets/images/smarter-anti-spam-checks.png';
+ $urls['rest_api_protection_img'] = HCAPTCHA_URL . '/assets/images/rest-api-protection.png';
}
return $urls;
diff --git a/src/php/Admin/OnboardingWizard.php b/src/php/Admin/OnboardingWizard.php
index 02f3f0a99..96ffd3cee 100644
--- a/src/php/Admin/OnboardingWizard.php
+++ b/src/php/Admin/OnboardingWizard.php
@@ -8,6 +8,7 @@
namespace HCaptcha\Admin;
use HCaptcha\Helpers\Request;
+use HCaptcha\Settings\AntiSpamPage;
use HCaptcha\Settings\General;
use HCaptcha\Settings\Integrations;
use HCaptcha\Settings\PluginSettingsBase;
@@ -79,6 +80,13 @@ class OnboardingWizard {
*/
private PluginSettingsBase $general_tab;
+ /**
+ * Anti-Spam tab instance.
+ *
+ * @var PluginSettingsBase
+ */
+ private PluginSettingsBase $antispam_tab;
+
/**
* Integration tab instance.
*
@@ -112,6 +120,7 @@ public function __construct( PluginSettingsBase $tab ) {
public function init(): void {
$this->settings = hcaptcha()->settings();
$this->general_tab = $this->settings->get_tab( General::class );
+ $this->antispam_tab = $this->settings->get_tab( AntiSpamPage::class );
$this->integrations_tab = $this->settings->get_tab( Integrations::class );
$this->init_wizard_state();
@@ -152,10 +161,10 @@ public function maybe_handle_direct_step(): void {
return;
}
- // Accept a numeric step only: onb=1..8.
+ // Accept a numeric step only: onb=1..9.
$num = (int) $step;
- if ( $num < 1 || $num > 8 ) {
+ if ( $num < 1 || $num > 9 ) {
$num = 1;
}
@@ -163,9 +172,15 @@ public function maybe_handle_direct_step(): void {
$this->set_wizard_state( 'step ' . $num );
// Determine the target page by step.
- $url = ( $num <= 6 )
- ? $this->tab->tab_url( $this->general_tab )
- : $this->tab->tab_url( $this->integrations_tab );
+ if ( $num <= 5 ) {
+ $target_tab = $this->general_tab;
+ } elseif ( $num <= 7 ) {
+ $target_tab = $this->antispam_tab;
+ } else {
+ $target_tab = $this->integrations_tab;
+ }
+
+ $url = $this->tab->tab_url( $target_tab );
$this->redirect_after_direct_step( $url );
}
@@ -218,8 +233,8 @@ public function admin_enqueue_scripts(): void {
$wizard = $this->get_wizard_state();
- // Start the wizard if the key is absent or its value is not 'completed'.
- if ( 'completed' === $wizard ) {
+ // Show the wizard only after the user explicitly starts it.
+ if ( ! preg_match( '/^step [1-9]$/', $wizard ) ) {
return;
}
@@ -231,13 +246,19 @@ public function admin_enqueue_scripts(): void {
// @codeCoverageIgnoreEnd
}
- $min = hcap_min_suffix();
+ $min = hcap_min_suffix();
+ $script_version = constant( 'HCAPTCHA_VERSION' );
+
+ if ( '' === $min ) {
+ $script_mtime = filemtime( constant( 'HCAPTCHA_PATH' ) . '/assets/js/onboarding-wizard.js' );
+ $script_version .= false === $script_mtime ? '' : '-' . $script_mtime;
+ }
wp_enqueue_script(
self::HANDLE,
constant( 'HCAPTCHA_URL' ) . "/assets/js/onboarding-wizard$min.js",
[ 'jquery', $this->tab::HANDLE ],
- constant( 'HCAPTCHA_VERSION' ),
+ $script_version,
true
);
@@ -262,9 +283,12 @@ public function admin_enqueue_scripts(): void {
'set_min_submit_time' => '#set_min_submit_time_1',
'antispam_check' => '#antispam_1',
'antispam_provider' => 'select[name="hcaptcha_settings[antispam_provider]"]',
- 'antispam' => '.hcaptcha-section-antispam+table',
'save' => '#hcaptcha-options #submit',
],
+ 'antispam' => [
+ 'bot_detection' => '.hcaptcha-section-bot-detection+table',
+ 'save' => '#hcaptcha-options #submit',
+ ],
'integrations' => [
'integrations_list' => '.hcaptcha-enabled-section+h3+table tr:first-child',
'save' => '#hcaptcha-options #submit',
@@ -277,14 +301,21 @@ public function admin_enqueue_scripts(): void {
2 => __( 'Switch Mode to Live', 'hcaptcha-for-forms-and-more' ),
3 => __( 'Enter keys, solve hCaptcha and Check Config', 'hcaptcha-for-forms-and-more' ),
4 => __( 'Enable Force (recommended)', 'hcaptcha-for-forms-and-more' ),
- 5 => __( 'Enable Anti-spam options (recommended)', 'hcaptcha-for-forms-and-more' ),
- 6 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ),
- 7 => __( 'Enable hCaptcha for installed plugins', 'hcaptcha-for-forms-and-more' ),
- 8 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ),
+ 5 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ),
+ 6 => __( 'Review bot detection options', 'hcaptcha-for-forms-and-more' ),
+ 7 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ),
+ 8 => __( 'Enable hCaptcha for installed plugins', 'hcaptcha-for-forms-and-more' ),
+ 9 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ),
];
// Detect which settings page we are on by looking at the body class via the section title echoing into form class.
- $page = $this->tab === $this->integrations_tab ? 'integrations' : 'general';
+ if ( $this->tab === $this->integrations_tab ) {
+ $page = 'integrations';
+ } elseif ( $this->tab === $this->antispam_tab ) {
+ $page = 'antispam';
+ } else {
+ $page = 'general';
+ }
wp_localize_script(
self::HANDLE,
@@ -300,7 +331,9 @@ public function admin_enqueue_scripts(): void {
'currentStep' => $current_step,
'selectors' => $selectors,
'steps' => $steps,
+ 'signupUrl' => 'https://www.hcaptcha.com/signup-interstitial/?r=wp&utm_source=wordpress&utm_medium=wpplugin&utm_campaign=sk',
'generalUrl' => $settings->tab_url( General::class ),
+ 'antispamUrl' => $settings->tab_url( AntiSpamPage::class ),
'integrationsUrl' => $settings->tab_url( Integrations::class ),
'stepParam' => self::STEP_PARAM,
'stepNonce' => wp_create_nonce( self::STEP_ACTION ),
@@ -311,7 +344,7 @@ public function admin_enqueue_scripts(): void {
'done' => __( 'Done', 'hcaptcha-for-forms-and-more' ),
'choiceTitle' => __( 'How would you like to continue?', 'hcaptcha-for-forms-and-more' ),
'choiceBody' => __( 'Your keys are configured and verified. We can now apply the recommended setup automatically, or you can continue step by step.', 'hcaptcha-for-forms-and-more' ),
- 'choiceAutoBody' => __( 'Automatic setup will enable Force, apply the recommended anti-spam options, enable hCaptcha for installed plugins and themes, and save your settings.', 'hcaptcha-for-forms-and-more' ),
+ 'choiceAutoBody' => __( 'Automatic setup will enable Force, Honeypot, and minimum submit time, apply available reCAPTCHA migrations, and save your settings.', 'hcaptcha-for-forms-and-more' ),
'choiceAutoCta' => __( 'Apply recommended setup automatically', 'hcaptcha-for-forms-and-more' ),
'choiceManualCta' => __( 'Continue step by step', 'hcaptcha-for-forms-and-more' ),
'close' => __( 'Close', 'hcaptcha-for-forms-and-more' ),
diff --git a/src/php/Admin/WhatsNew.php b/src/php/Admin/WhatsNew.php
index a95953f3a..72658b062 100644
--- a/src/php/Admin/WhatsNew.php
+++ b/src/php/Admin/WhatsNew.php
@@ -809,6 +809,39 @@ protected function whats_new_5_4_0(): void {
$this->show_block( $block_anti_spam );
}
+ /**
+ * What's New 5.5.0 content.
+ *
+ * @return void
+ * @noinspection HtmlUnknownTarget
+ * @noinspection PhpUnused
+ */
+ protected function whats_new_5_5_0(): void {
+ $urls = $this->prepare_urls();
+
+ $block_rest_api_protection = [
+ 'type' => 'left',
+ 'badge' => __( 'New Feature', 'hcaptcha-for-forms-and-more' ),
+ 'title' => __( 'Unique REST API Protection', 'hcaptcha-for-forms-and-more' ),
+ 'message' => sprintf(
+ '
%1$s
%2$s
%3$s
',
+ __( 'Protect Content now keeps selected posts and pages out of WordPress REST responses, collections, and search until the visitor passes hCaptcha.', 'hcaptcha-for-forms-and-more' ),
+ __( 'When the corresponding integrations are enabled, native REST comments require hCaptcha and REST post-password attempts are blocked.', 'hcaptcha-for-forms-and-more' ),
+ __( 'In our October 2026 review of the 10 most-installed WordPress.org plugins tagged captcha, none offered all three protections.', 'hcaptcha-for-forms-and-more' )
+ ),
+ 'button' => [
+ 'url' => $urls['protect_content'],
+ 'text' => __( 'Configure Content Protection', 'hcaptcha-for-forms-and-more' ),
+ ],
+ 'image' => [
+ 'url' => $urls['rest_api_protection_img'],
+ 'lightbox' => true,
+ ],
+ ];
+
+ $this->show_block( $block_rest_api_protection );
+ }
+
/**
* Show block.
*
diff --git a/src/php/Affiliates/Register.php b/src/php/Affiliates/Register.php
index c7d23e692..8051780ef 100644
--- a/src/php/Affiliates/Register.php
+++ b/src/php/Affiliates/Register.php
@@ -8,6 +8,7 @@
namespace HCaptcha\Affiliates;
use HCaptcha\Helpers\API;
+use HCaptcha\Helpers\EntryData;
use HCaptcha\Helpers\HCaptcha;
/**
@@ -88,10 +89,7 @@ public function after_section( string $current_section_key ): void {
$args = [
'action' => self::ACTION,
'name' => self::NONCE,
- 'id' => [
- 'source' => HCaptcha::get_class_source( __CLASS__ ),
- 'form_id' => 'register',
- ],
+ 'id' => $this->get_expected_id(),
];
$search = '
error_message = API::verify_post( self::NONCE, self::ACTION );
+ // A logged-in affiliate registers with the stored address, not the readonly POST field.
+ $email = '';
+
+ // phpcs:disable WordPress.Security.NonceVerification.Missing -- The API verifies the nonce below.
+ if ( is_user_logged_in() ) {
+ $email = wp_get_current_user()->user_email;
+ } elseif ( isset( $_POST['user_email'] ) && is_scalar( $_POST['user_email'] ) ) {
+ $email = sanitize_email( wp_unslash( (string) $_POST['user_email'] ) );
+ }
+ // phpcs:enable WordPress.Security.NonceVerification.Missing
+
+ $this->error_message = API::verify_post(
+ self::NONCE,
+ self::ACTION,
+ $this->get_expected_id(),
+ EntryData::with_emails( [], [ $email ] )
+ );
return null !== $this->error_message;
}
@@ -139,4 +153,16 @@ private function show_error(): void {
HCaptcha::get_class_source( __CLASS__ ),
+ 'form_id' => 'register',
+ ];
+ }
}
diff --git a/src/php/AntiSpam/DisposableEmail.php b/src/php/AntiSpam/DisposableEmail.php
index 237b13a12..e9c2edce7 100644
--- a/src/php/AntiSpam/DisposableEmail.php
+++ b/src/php/AntiSpam/DisposableEmail.php
@@ -7,6 +7,8 @@
namespace HCaptcha\AntiSpam;
+use HCaptcha\Helpers\EntryData;
+
/**
* Class DisposableEmail.
*/
@@ -81,21 +83,21 @@ private function init_hooks(): void {
* @return string|null
*/
public function verify( array $entry ): ?string {
- $email = $entry['data']['email'] ?? '';
-
- if ( ! is_email( $email ) ) {
- return true;
+ foreach ( EntryData::get_emails( $entry ) as $email ) {
+ /**
+ * Filters the disposable email status.
+ *
+ * @param bool $is_disposable Whether the email is disposable.
+ * @param string $email Email address.
+ */
+ $disposable = (bool) apply_filters( 'hcap_is_disposable_email', $this->is_disposable_email( $email ), $email );
+
+ if ( $disposable ) {
+ return false;
+ }
}
- /**
- * Filters the disposable email status.
- *
- * @param bool $is_disposable Whether the email is disposable.
- * @param string $email Email address.
- */
- $disposable = (bool) apply_filters( 'hcap_is_disposable_email', $this->is_disposable_email( $email ), $email );
-
- return ! $disposable;
+ return true;
}
/**
@@ -162,18 +164,15 @@ protected function read_file( string $file ) {
* @return bool
*/
public function is_disposable_email( string $email ): bool {
- if ( false === strpos( $email, '@' ) ) {
- return false;
- }
-
- $parts = explode( '@', trim( $email ) );
+ $email = trim( $email );
+ $separator = strrpos( $email, '@' );
- if ( count( $parts ) < 2 || '' === $parts[1] ) {
+ if ( false === $separator || strlen( $email ) - 1 === $separator ) {
return false;
}
$to_lower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
- $domain = $to_lower( $parts[1] );
+ $domain = $to_lower( substr( $email, $separator + 1 ) );
$domain_parts = explode( '.', $domain );
$blocklist = $this->get_blocklist();
$count = count( $domain_parts );
@@ -262,6 +261,7 @@ public function update_blocklist(): void {
* Schedule the recurring blocklist update via Action Scheduler.
*
* @return void
+ * @noinspection PhpUndefinedFunctionInspection
*/
protected function schedule_update(): void {
if ( ! function_exists( 'as_schedule_recurring_action' ) ) {
@@ -282,6 +282,7 @@ protected function schedule_update(): void {
* Unschedule the recurring blocklist update.
*
* @return void
+ * @noinspection PhpUndefinedFunctionInspection
*/
protected function unschedule_update(): void {
if ( ! function_exists( 'as_unschedule_all_actions' ) ) {
diff --git a/src/php/Asgaros/Base.php b/src/php/Asgaros/Base.php
index 7f883fb71..7d1636490 100644
--- a/src/php/Asgaros/Base.php
+++ b/src/php/Asgaros/Base.php
@@ -50,15 +50,13 @@ public function add_captcha( $output, string $tag, $attr, array $m ) {
return $output;
}
- $form_id = isset( $attr['id'] ) ? (int) $attr['id'] : 0;
+ $form_id = $this->get_form_id();
$search = '
';
$args = [
- 'action' => static::ACTION,
- 'name' => static::NAME,
- 'id' => [
- 'source' => HCaptcha::get_class_source( static::class ),
- 'form_id' => $form_id,
- ],
+ 'mandatory' => true,
+ 'action' => static::ACTION,
+ 'name' => static::NAME,
+ 'id' => $this->get_id( $form_id ),
];
return str_replace(
@@ -83,7 +81,7 @@ public function add_captcha( $output, string $tag, $attr, array $m ) {
public function verify( $verified ) {
global $asgarosforum;
- $error_message = API::verify_post( static::NAME, static::ACTION );
+ $error_message = API::verify_post( static::NAME, static::ACTION, $this->get_id( $this->get_form_id() ) );
if ( null !== $error_message ) {
$asgarosforum->add_notice( $error_message );
@@ -94,6 +92,33 @@ public function verify( $verified ) {
return $verified;
}
+ /**
+ * Get the forum selected by the native request.
+ *
+ * @return int
+ */
+ private function get_form_id(): int {
+ global $asgarosforum;
+
+ $forum_id = $asgarosforum->current_forum ?? 0;
+
+ return is_scalar( $forum_id ) ? absint( $forum_id ) : 0;
+ }
+
+ /**
+ * Get the widget identity for an Asgaros forum.
+ *
+ * @param int $forum_id Forum ID.
+ *
+ * @return array
+ */
+ private function get_id( int $forum_id ): array {
+ return [
+ 'source' => HCaptcha::get_class_source( static::class ),
+ 'form_id' => $forum_id,
+ ];
+ }
+
/**
* Print inline styles.
*
diff --git a/src/php/AutoVerify/AutoVerify.php b/src/php/AutoVerify/AutoVerify.php
index a350afe25..74cd16f40 100644
--- a/src/php/AutoVerify/AutoVerify.php
+++ b/src/php/AutoVerify/AutoVerify.php
@@ -10,6 +10,7 @@
use HCaptcha\Helpers\API;
use HCaptcha\Helpers\HCaptcha;
use HCaptcha\Helpers\Request;
+use WP_Query;
use WP_Widget_Block;
/**
@@ -27,6 +28,11 @@ class AutoVerify {
*/
private const OPTION_PREFIX = 'hcaptcha_auto_verify_form_';
+ /**
+ * Public WordPress query variables selecting a single post.
+ */
+ private const QUERY_SELECTORS = [ 'page_id', 'p', 'pagename', 'name', 'attachment_id', 'subpost_id', 'attachment', 'subpost' ];
+
/**
* Legacy transient size limit, retained for compatibility.
*
@@ -286,13 +292,19 @@ private function get_registered_form_for_request(): ?array {
return $registered_form;
}
- $canonical_path = $this->get_canonical_request_path();
+ foreach ( $this->get_canonical_request_keys() as $canonical_key ) {
+ if ( ! $canonical_key || $canonical_key === $path || $canonical_key === $target_key ) {
+ continue;
+ }
- if ( ! $canonical_path || $canonical_path === $path ) {
- return null;
+ $registered_form = $this->get_registered_form( $canonical_key );
+
+ if ( null !== $registered_form ) {
+ return $registered_form;
+ }
}
- return $this->get_registered_form( $canonical_path );
+ return null;
}
/**
@@ -326,13 +338,20 @@ private function verify_submission( array $registered_form ): ?string {
* @return array
*/
private function get_entry( string $name, string $action, array $expected_id ): array {
- return [
+ $entry = [
'nonce_name' => $name,
'nonce_action' => $action,
'h-captcha-response' => Request::filter_input( INPUT_POST, 'h-captcha-response' ),
'data' => $this->get_data(),
'expected_id' => $expected_id,
];
+
+ /**
+ * Filter entry data for the server-registered automatic form.
+ *
+ * @param array $entry Verification entry with the registered form identity.
+ */
+ return (array) apply_filters( 'hcap_auto_verify_entry', $entry );
}
/**
@@ -417,17 +436,214 @@ protected function register_forms( array $forms ): void {
* @return string
*/
private function get_form_action( string $form ): string {
- $form_action = '';
+ $form_action = $this->get_form_action_attribute( $form );
+ $form_action = trim( str_replace( [ "\t", "\r", "\n" ], '', $form_action ), "\x00..\x20" );
- if ( preg_match( '#
])(?:[^>"\']|"[^"]*"|\'[^\']*\')*>#i', $form, $tag ) ) {
+ preg_match_all(
+ '#([^\x09\x0a\x0c\x0d\x20=/>]+)(?:[\x09\x0a\x0c\x0d\x20]*=[\x09\x0a\x0c\x0d\x20]*(?:"([^"]*)"|\'([^\']*)\'|([^\x09\x0a\x0c\x0d\x20>]*)))?#',
+ substr( $tag[0], 5, -1 ),
+ $attributes,
+ PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL
+ );
+
+ foreach ( $attributes as $attribute ) {
+ if ( 'action' !== strtolower( $attribute[1] ) ) {
+ continue;
+ }
+
+ // Browsers use the first duplicate attribute and decode its entities once.
+ return $this->decode_action_attribute( $attribute[2] ?? $attribute[3] ?? $attribute[4] ?? '' );
+ }
+ }
+
+ return '';
+ }
+
+ /**
+ * Decode HTML attribute references once, including browser forms without semicolons.
+ *
+ * @param string $value Attribute value.
+ *
+ * @return string
+ */
+ private function decode_action_attribute( string $value ): string {
+ $legacy = [ 'AMP', 'COPY', 'GT', 'LT', 'QUOT', 'REG', 'amp', 'gt', 'lt', 'quot' ];
+
+ foreach ( get_html_translation_table( HTML_ENTITIES, ENT_QUOTES | ENT_HTML401 ) as $character => $entity ) {
+ if ( preg_match( '/^(?:\xc2[\xa0-\xbf]|\xc3[\x80-\xbf])$/', $character ) ) {
+ $legacy[] = substr( $entity, 1, -1 );
+ }
+ }
+
+ return preg_replace_callback(
+ '/(?:[xX][0-9a-fA-F]+|[0-9]+);?|&([a-zA-Z][a-zA-Z0-9]*)(;|(?![a-zA-Z0-9=]))/',
+ function ( array $matches ) use ( $legacy ): string {
+ if ( 0 === strpos( $matches[0], '' ) ) {
+ return $this->decode_numeric_reference( $matches[0] );
+ }
+
+ if ( ';' !== $matches[2] && ! in_array( $matches[1], $legacy, true ) ) {
+ return $matches[0];
+ }
+
+ return html_entity_decode( '&' . $matches[1] . ';', ENT_QUOTES | ENT_HTML5, 'UTF-8' );
+ },
+ $value
+ );
+ }
+
+ /**
+ * Decode a numeric reference with HTML's replacement and legacy control mapping.
+ *
+ * @param string $reference Numeric character reference.
+ *
+ * @return string
+ */
+ private function decode_numeric_reference( string $reference ): string {
+ $number = substr( rtrim( $reference, ';' ), 2 );
+ $code = 'x' === strtolower( $number[0] ) ? hexdec( substr( $number, 1 ) ) : (float) $number;
+
+ if ( 0 === (int) $code || $code > 0x10ffff || ( $code >= 0xd800 && $code <= 0xdfff ) ) {
+ return "\xef\xbf\xbd";
+ }
+
+ $controls = [
+ 0x80 => 0x20ac,
+ 0x82 => 0x201a,
+ 0x83 => 0x0192,
+ 0x84 => 0x201e,
+ 0x85 => 0x2026,
+ 0x86 => 0x2020,
+ 0x87 => 0x2021,
+ 0x88 => 0x02c6,
+ 0x89 => 0x2030,
+ 0x8a => 0x0160,
+ 0x8b => 0x2039,
+ 0x8c => 0x0152,
+ 0x8e => 0x017d,
+ 0x91 => 0x2018,
+ 0x92 => 0x2019,
+ 0x93 => 0x201c,
+ 0x94 => 0x201d,
+ 0x95 => 0x2022,
+ 0x96 => 0x2013,
+ 0x97 => 0x2014,
+ 0x98 => 0x02dc,
+ 0x99 => 0x2122,
+ 0x9a => 0x0161,
+ 0x9b => 0x203a,
+ 0x9c => 0x0153,
+ 0x9e => 0x017e,
+ 0x9f => 0x0178,
+ ];
+ $code = $controls[ (int) $code ] ?? (int) $code;
+
+ if ( $code < 0x80 ) {
+ return chr( $code );
+ }
+
+ if ( $code < 0x800 ) {
+ return chr( 0xc0 | ( $code >> 6 ) ) . chr( 0x80 | ( $code & 0x3f ) );
+ }
+
+ if ( $code < 0x10000 ) {
+ return chr( 0xe0 | ( $code >> 12 ) ) . chr( 0x80 | ( ( $code >> 6 ) & 0x3f ) ) . chr( 0x80 | ( $code & 0x3f ) );
+ }
+
+ return chr( 0xf0 | ( $code >> 18 ) ) . chr( 0x80 | ( ( $code >> 12 ) & 0x3f ) ) . chr( 0x80 | ( ( $code >> 6 ) & 0x3f ) ) . chr( 0x80 | ( $code & 0x3f ) );
+ }
+
+ /**
+ * Resolve an action against the current document before decoding URL path octets.
+ *
+ * @param string $action Form action.
+ *
+ * @return string
+ */
+ private function resolve_form_action( string $action ): string {
+ // Backslashes are path separators in browser HTTP URLs, but not in their queries.
+ $action = preg_replace_callback(
+ '/^[^?#]*/',
+ static function ( array $matches ): string {
+ return str_replace( '\\', '/', $matches[0] );
+ },
+ $action
+ );
+ $parts = (array) wp_parse_url( $action );
+ $base = (array) wp_parse_url( $this->get_request_uri() );
+ $origin = isset( $parts['host'] ) || isset( $parts['scheme'] );
+ $path = $parts['path'] ?? '';
+
+ if ( $origin ) {
+ $path = '' === $path ? '/' : $path;
+ } elseif ( '' === $path ) {
+ $path = $base['path'] ?? '/';
+ } elseif ( '/' !== $path[0] ) {
+ $base_path = $base['path'] ?? '/';
+ $path = substr( $base_path, 0, (int) strrpos( $base_path, '/' ) + 1 ) . $path;
+ }
+
+ $query = $this->get_action_query( $parts, $base, $origin );
+
+ return $this->normalize_action_path( $path ) . ( '' !== $query ? '?' . $query : '' );
+ }
+
+ /**
+ * A pathless relative action inherits the document query unless it supplies one.
+ *
+ * @param array $parts Action URL parts.
+ * @param array $base Document URL parts.
+ * @param bool $origin Whether the action specifies an origin.
+ *
+ * @return string
+ */
+ private function get_action_query( array $parts, array $base, bool $origin ): string {
+ return $parts['query'] ?? ( ! $origin && ! isset( $parts['path'] ) ? ( $base['query'] ?? '' ) : '' );
+ }
+
+ /**
+ * Remove browser dot segments while retaining empty segments and encoded separators.
+ *
+ * @param string $path Action path.
+ *
+ * @return string
+ */
+ private function normalize_action_path( string $path ): string {
+ $segments = [];
+
+ foreach ( explode( '/', ltrim( $path, '/' ) ) as $segment ) {
+ $dot_segment = str_ireplace( '%2e', '.', $segment );
+
+ if ( '..' === $dot_segment ) {
+ array_pop( $segments );
+ } elseif ( '.' !== $dot_segment ) {
+ $segments[] = $segment;
+ }
+ }
+
+ return '/' . implode( '/', $segments );
+ }
+
/**
* Distinguish WordPress query routes sharing the same URL path.
*
@@ -449,16 +665,21 @@ private function get_target_key( string $url ): string {
}
parse_str( $query, $query_vars );
- $post_id = $this->get_query_post_id( $query_vars );
- if ( ! $post_id ) {
+ if ( ! array_filter( array_intersect_key( $query_vars, array_flip( self::QUERY_SELECTORS ) ) ) ) {
return $path;
}
$home_path = $this->get_path( home_url( '/' ) );
$index_path = ( '/' === $home_path ? '' : $home_path ) . '/index.php';
- return $path === $home_path || $path === $index_path ? 'post:' . $post_id . ':' . $path : $path;
+ if ( $path !== $home_path && $path !== $index_path ) {
+ return $path;
+ }
+
+ $post_id = $this->get_query_post_id( $query_vars );
+
+ return $post_id ? 'post:' . $post_id . ':' . $path : $path;
}
/**
@@ -469,21 +690,22 @@ private function get_target_key( string $url ): string {
* @return int
*/
private function get_query_post_id( array $query_vars ): int {
- foreach ( [ 'page_id', 'p' ] as $key ) {
- $value = $query_vars[ $key ] ?? null;
+ $query_vars = array_intersect_key( $query_vars, array_flip( array_merge( self::QUERY_SELECTORS, [ 'post_type' ] ) ) );
- if ( is_scalar( $value ) && ctype_digit( (string) $value ) ) {
- return (int) $value;
- }
+ if ( ! array_filter( array_intersect_key( $query_vars, array_flip( self::QUERY_SELECTORS ) ) ) ) {
+ return 0;
}
- if ( ! empty( $query_vars['pagename'] ) && is_string( $query_vars['pagename'] ) ) {
- $page = get_page_by_path( $query_vars['pagename'] );
-
- return $page->ID ?? 0;
- }
+ // Use the installed core's selector normalization, aliases and precedence.
+ $query = new WP_Query(
+ $query_vars + [
+ 'posts_per_page' => 1,
+ 'no_found_rows' => true,
+ ]
+ );
- return 0;
+ // Retain page-qualified action keys even when a numeric target does not exist yet.
+ return $query->get_queried_object_id() ?: (int) ( $query->query_vars['page_id'] ?: $query->query_vars['p'] );
}
/**
@@ -504,36 +726,50 @@ private function get_widget_id_value( string $form ): string {
}
/**
- * Get the canonical path of the current WordPress request.
+ * Get equivalent registration keys for the current WordPress page.
*
- * @return string
+ * @return array
*/
- private function get_canonical_request_path(): string {
- $post_id = url_to_postid( Request::current_url() );
-
- if ( ! $post_id ) {
- $pagename = Request::filter_input( INPUT_GET, 'pagename' );
+ private function get_canonical_request_keys(): array {
+ // The native login script does not route page selectors through WordPress's main query.
+ if ( 'wp-login.php' === basename( Request::filter_input( INPUT_SERVER, 'SCRIPT_NAME' ) ) ) {
+ return [];
+ }
- if ( is_string( $pagename ) && '' !== $pagename ) {
- $page = get_page_by_path( $pagename );
+ $query_vars = [];
- if ( $page ) {
- $post_id = $page->ID;
- }
- }
+ foreach ( array_merge( self::QUERY_SELECTORS, [ 'post_type' ] ) as $key ) {
+ // Preserve WordPress's input and POST-before-GET precedence. WP_Query validates these selectors.
+ // Nonce is verified later, in API::verify().
+ // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
+ $query_vars[ $key ] = $_POST[ $key ] ?? $_GET[ $key ] ?? '';
}
+ $post_id = $this->get_query_post_id( $query_vars );
+ $post_id = $post_id ?: url_to_postid( Request::current_url() );
+
if ( ! $post_id ) {
- return '';
+ return [];
}
$permalink = get_permalink( $post_id );
if ( ! is_string( $permalink ) ) {
- return '';
+ return [];
}
- return $this->get_path( $permalink );
+ $home_path = $this->get_path( home_url( '/' ) );
+ $index_path = ( '/' === $home_path ? '' : $home_path ) . '/index.php';
+
+ // Existing registrations can use either plain permalink entry point.
+ return array_unique(
+ [
+ $this->get_target_key( $permalink ),
+ 'post:' . $post_id . ':' . $home_path,
+ 'post:' . $post_id . ':' . $index_path,
+ $this->get_path( $permalink ),
+ ]
+ );
}
/**
@@ -543,7 +779,7 @@ private function get_canonical_request_path(): string {
*/
private function get_request_uri(): string {
return isset( $_SERVER['REQUEST_URI'] ) ?
- (string) filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ), FILTER_SANITIZE_FULL_SPECIAL_CHARS ) :
+ (string) filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ), FILTER_SANITIZE_URL ) :
'';
}
@@ -796,16 +1032,80 @@ private function is_same_registered_form_identity( array $registered_form, array
* Whether a request matches the registered form structure.
*
* @param array $registered_form Registered form.
- * @param array $post_keys Submitted input names.
+ * @param array $post Submitted form data.
* @param string $widget_id Submitted widget ID.
*
* @return bool
*/
- private function is_same_registered_form( array $registered_form, array $post_keys, string $widget_id ): bool {
+ private function is_same_registered_form( array $registered_form, array $post, string $widget_id ): bool {
$inputs = (array) ( $registered_form['inputs'] ?? [] );
$registered_widget_id = (string) ( $registered_form['widget_id'] ?? '' );
- return $widget_id && $registered_widget_id === $widget_id && ! array_diff( $inputs, $post_keys );
+ if ( ! $widget_id || $registered_widget_id !== $widget_id ) {
+ return false;
+ }
+
+ foreach ( $inputs as $input ) {
+ if ( ! $this->has_input( $input, $post ) ) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Check a registered HTML input name against PHP's parsed submission.
+ *
+ * @param string $name Input name.
+ * @param array $post Submitted form data.
+ *
+ * @return bool
+ */
+ private function has_input( string $name, array $post ): bool {
+ // Let PHP normalize the root key without interpreting name characters as query separators.
+ parse_str( rawurlencode( $name ) . '=1', $parsed );
+
+ if ( ! $parsed ) {
+ return false;
+ }
+
+ preg_match_all( '/\[([^\]]*)\]/', $name, $matches );
+ $keys = array_merge( [ array_key_first( $parsed ) ], $matches[1] );
+
+ return $this->has_input_path( $post, $keys );
+ }
+
+ /**
+ * Resolve named array keys, treating empty brackets as any submitted array element.
+ *
+ * @param mixed $value Submitted value.
+ * @param array $keys Remaining input name keys.
+ *
+ * @return bool
+ */
+ private function has_input_path( $value, array $keys ): bool {
+ if ( ! $keys ) {
+ return true;
+ }
+
+ if ( ! is_array( $value ) ) {
+ return false;
+ }
+
+ $key = array_shift( $keys );
+
+ if ( '' !== $key ) {
+ return array_key_exists( $key, $value ) && $this->has_input_path( $value[ $key ], $keys );
+ }
+
+ foreach ( $value as $item ) {
+ if ( $this->has_input_path( $item, $keys ) ) {
+ return true;
+ }
+ }
+
+ return false;
}
/**
@@ -874,12 +1174,12 @@ protected function get_registered_form( string $path ): ?array {
// Nonce is verified later, in \HCaptcha\Helpers\API::verify().
// phpcs:ignore WordPress.Security.NonceVerification.Missing
- $post_keys = array_keys( $_POST );
+ $post = $_POST;
$widget_id = Request::filter_input( INPUT_POST, HCaptcha::HCAPTCHA_WIDGET_ID );
$widget_id = is_string( $widget_id ) ? $widget_id : '';
foreach ( $action_forms as $registered_form ) {
- if ( $this->is_same_registered_form( (array) $registered_form, $post_keys, $widget_id ) ) {
+ if ( $this->is_same_registered_form( (array) $registered_form, $post, $widget_id ) ) {
return $registered_form;
}
}
@@ -937,19 +1237,47 @@ private function process_content( $content ): string {
return $content;
}
- if (
- preg_match_all(
- '#