Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Recaptcha Enterprise Bundle Laravel Package

artack/recaptcha-enterprise-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require artack/recaptcha-enterprise-bundle:0.1.*
    

    (Pin to 0.1.* to avoid breaking changes.)

  2. Configure Environment Variables Add these to .env:

    ARTACK_GOOGLE_RECAPTCHA_ENABLED=true
    ARTACK_GOOGLE_RECAPTCHA_SITE_KEY=your_site_key
    ARTACK_GOOGLE_RECAPTCHA_PROJECT_ID=your_project_id
    ARTACK_GOOGLE_RECAPTCHA_API_KEY=your_api_key
    
  3. Create Config File Generate config/packages/artack_recaptcha_enterprise.yaml (see README for template).

  4. First Use Case: Add to a Form

    use Artack\RecaptchaEnterpriseBundle\Form\RecaptchaEnterpriseType;
    
    $builder->add('recaptchaToken', RecaptchaEnterpriseType::class, [
        'action_name' => 'submit_form', // Required for validation
    ]);
    
  5. Render the Form The bundle auto-loads Twig templates. No manual CSP nonce is needed unless using strict policies.


Implementation Patterns

Common Workflows

  1. Form Integration

    • Basic Usage: Add RecaptchaEnterpriseType to any form. The hidden token field is auto-generated.
    • Dynamic Actions: Use action_name to tie tokens to specific form submissions (e.g., 'contact', 'signup').
      $builder->add('recaptchaToken', RecaptchaEnterpriseType::class, [
          'action_name' => 'user_registration',
      ]);
      
  2. Validation

    • Constraint-Based: Attach RecaptchaEnterprise validator to fields or classes.
      use Artack\RecaptchaEnterpriseBundle\Validator\RecaptchaEnterprise;
      
      #[RecaptchaEnterprise(minScore: 0.9, actionName: 'admin_panel')]
      class AdminFormType extends AbstractType { ... }
      
    • Global Defaults: Configure min_score in artack_recaptcha_enterprise.yaml (fallback for unconfigured constraints).
  3. Conditional Enforcement

    • Disable in dev/staging:
      when@dev:
          artack_recaptcha_enterprise:
              enabled: false
      
    • Skip for trusted users (e.g., logged-in admins):
      if (!$this->getUser()->isAdmin()) {
          $builder->add('recaptchaToken', RecaptchaEnterpriseType::class);
      }
      
  4. CSP Integration

    • Nonce Handling: Pass script_csp_nonce if using Content Security Policy:
      $builder->add('recaptchaToken', RecaptchaEnterpriseType::class, [
          'script_csp_nonce' => $this->getCspNonceGenerator()->generate(),
      ]);
      
    • Alternative: Use unsafe-inline in CSP (not recommended for production).
  5. API-Only Forms

    • For non-Twig forms (e.g., API submissions), manually inject the token via JavaScript:
      grecaptcha.enterprise.execute('SITE_KEY', {action: 'api_submit'})
          .then(token => document.getElementById('recaptcha_token').value = token);
      

Integration Tips

  • Symfony UX: Works seamlessly with Symfony UX Turbo/Stimulus. The form re-submission is handled client-side.
  • Error Handling: Customize validation error messages:
    # config/validator/constraints.yaml
    Artack\RecaptchaEnterpriseBundle\Validator\RecaptchaEnterprise:
        message: 'reCAPTCHA score too low ({{ score }}). Please try again.'
    
  • Testing: Mock the validator in PHPUnit:
    $validator = $this->createMock(RecaptchaEnterpriseValidator::class);
    $validator->method('validate')->willReturn(null); // Simulate success
    $this->container->set(RecaptchaEnterpriseValidator::class, $validator);
    

Gotchas and Tips

Pitfalls

  1. Token Mismatch Errors

    • Cause: action_name in the form type must match the validator’s actionName.
    • Fix: Ensure consistency:
      // Form type
      'action_name' => 'login_form'
      
      // Validator
      new RecaptchaEnterprise(actionName: 'login_form')
      
  2. Score Thresholds

    • Issue: Default min_score (0.5) may be too low for high-risk forms.
    • Solution: Override per constraint or globally:
      artack_recaptcha_enterprise:
          min_score: 0.9  # Strict for all forms
      
  3. Dev Environment Leaks

    • Risk: Disabling enabled: false in dev may still expose site keys in templates.
    • Fix: Use environment-specific Twig extensions to hide the script entirely:
      {% if app.environment == 'dev' %}
          {# No reCAPTCHA script #}
      {% else %}
          {{ form_widget(form.recaptchaToken) }}
      {% endif %}
      
  4. Rate Limits

    • Warning: Google’s Assessments API has quotas. Monitor usage in Google Cloud Console.
    • Mitigation: Cache tokens briefly (e.g., 5 minutes) for repeated submissions.
  5. CSP Nonce Generation

    • Problem: Hardcoding nonces breaks security.
    • Fix: Use Symfony’s CspNonceGenerator or a custom service:
      $nonce = $this->cspNonceGenerator->generate();
      

Debugging

  • Validation Failures: Check Symfony’s profiler under "Validator" > "Errors" for recaptcha-specific messages.
  • API Errors: Enable debug logging for Artack\RecaptchaEnterpriseBundle:
    monolog:
        handlers:
            main:
                level: debug
    
  • Token Debugging: Log the raw token (temporarily) to verify submission:
    $event->getData()->get('recaptchaToken'); // In a form event listener
    

Extension Points

  1. Custom Validators Extend RecaptchaEnterpriseValidator to add logic (e.g., IP-based score adjustments):

    class CustomRecaptchaValidator extends RecaptchaEnterpriseValidator {
        public function validate($value, Constraint $constraint): void {
            if ($this->isHighRiskIp($value)) {
                $constraint->minScore = 0.95;
            }
            parent::validate($value, $constraint);
        }
    }
    
  2. Event Listeners Hook into RecaptchaEnterpriseEvent to modify requests/responses:

    use Artack\RecaptchaEnterpriseBundle\Event\RecaptchaEnterpriseEvent;
    
    $dispatcher->addListener(RecaptchaEnterpriseEvent::PRE_VALIDATE, function (RecaptchaEnterpriseEvent $event) {
        $event->setCustomData(['user_id' => $this->getUser()->getId()]);
    });
    
  3. Twig Overrides Customize the token field template:

    {# templates/artack_recaptcha_enterprise/recaptcha_enterprise.html.twig #}
    <div class="custom-recaptcha">
        {{ parent() }}
    </div>
    

Pro Tips

  • Score Calibration: Test thresholds with real traffic. Start at 0.5, then adjust based on false positives/negatives.
  • Action Naming: Use semantic names (e.g., user_registration, password_reset) for analytics.
  • Performance: Lazy-load the Google script with defer:
    <script src="https://www.gstatic.com/recaptcha/api.js?render=SITE_KEY" defer></script>
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky