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

Jsonp Callback Validator Laravel Package

willdurand/jsonp-callback-validator

Validate JSONP callback names to prevent XSS. JsonpCallbackValidator checks whether a callback like JSONP.callback is safe and rejects malicious function payloads. Use via instance or static validate(), installable via Composer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require willdurand/jsonp-callback-validator
    

    Add to composer.json if using Laravel's autoloader (though not required for standalone usage).

  2. First Use Case: Validate JSONP callbacks in API endpoints or middleware to prevent XSS attacks.

    use JsonpCallbackValidator;
    
    // In a controller or service
    $callback = request()->input('callback'); // e.g., "JSONP.callback"
    $isValid = JsonpCallbackValidator::validate($callback);
    
  3. Where to Look First:


Implementation Patterns

Usage Patterns

  1. Middleware Integration: Validate callbacks in middleware to sanitize incoming JSONP requests globally.

    namespace App\Http\Middleware;
    
    use Closure;
    use JsonpCallbackValidator;
    
    class ValidateJsonpCallback
    {
        public function handle($request, Closure $next)
        {
            $callback = $request->input('callback');
            if ($callback && !JsonpCallbackValidator::validate($callback)) {
                abort(400, 'Invalid JSONP callback');
            }
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\ValidateJsonpCallback::class,
    ];
    
  2. API Response Wrapper: Dynamically wrap responses in JSONP format if a valid callback is provided.

    namespace App\Services;
    
    use JsonpCallbackValidator;
    
    class JsonpResponseService
    {
        public function wrap($data, $callback = null)
        {
            if ($callback && JsonpCallbackValidator::validate($callback)) {
                return "$callback($data)";
            }
            return $data;
        }
    }
    
  3. Form Request Validation: Extend Laravel's FormRequest to validate JSONP callbacks.

    namespace App\Http\Requests;
    
    use JsonpCallbackValidator;
    use Illuminate\Foundation\Http\FormRequest;
    
    class JsonpRequest extends FormRequest
    {
        public function rules()
        {
            return [
                'callback' => 'nullable|string',
            ];
        }
    
        public function passedValidation()
        {
            if ($this->callback && !JsonpCallbackValidator::validate($this->callback)) {
                $this->fail('Invalid JSONP callback');
            }
            return parent::passedValidation();
        }
    }
    

Workflows

  1. JSONP Endpoint Handling:

    • Accept callback parameter in API routes.
    • Validate before processing the request.
    • Wrap responses dynamically if the callback is valid.
  2. Legacy System Integration:

    • Use the validator in legacy PHP applications where JSONP is still supported.
    • Example: Validate callbacks in a custom JsonpController.
  3. Testing:

    • Mock the validator in unit tests to simulate valid/invalid callbacks.
    $validator = $this->createMock(JsonpCallbackValidator::class);
    $validator->method('validate')->willReturn(true);
    

Integration Tips

  • Laravel Service Providers: Bind the validator to the container for dependency injection:

    $this->app->singleton(JsonpCallbackValidator::class);
    

    Then inject it into controllers/services:

    use JsonpCallbackValidator;
    
    public function __construct(private JsonpCallbackValidator $validator) {}
    
  • Custom Validation Rules: Create a reusable validation rule:

    namespace App\Rules;
    
    use JsonpCallbackValidator;
    use Illuminate\Contracts\Validation\Rule;
    
    class ValidJsonpCallback implements Rule
    {
        public function passes($attribute, $value)
        {
            return JsonpCallbackValidator::validate($value);
        }
    
        public function message()
        {
            return 'The :attribute must be a valid JSONP callback.';
        }
    }
    

    Use in FormRequest or manually:

    $request->validate(['callback' => ['nullable', new ValidJsonpCallback]]);
    

Gotchas and Tips

Pitfalls

  1. False Positives/Negatives:

    • The validator may reject legitimate callbacks with complex names (e.g., my.callback.with.dots).
    • Workaround: Extend the validator or use a whitelist for known-safe callbacks.
    $whitelist = ['JSONP.callback', 'myApp.callback'];
    $isValid = in_array($callback, $whitelist, true);
    
  2. Performance:

    • The validator uses regex, which is lightweight but may impact performance in high-throughput APIs.
    • Tip: Cache validation results if the same callback is reused (e.g., in a loop).
  3. PHP 8.x Compatibility:

    • The package is updated for PHP 8.x, but test thoroughly if using newer features (e.g., named arguments).
  4. Edge Cases:

    • Empty strings or null values may not be handled explicitly. Add checks:
    if (empty($callback)) {
        return true; // or false, depending on requirements
    }
    

Debugging

  1. Invalid Callback Rejections:

    • Use the unit tests as a reference for valid/invalid patterns.
    • Example of a rejected callback: (function xss(x){evil()}).
  2. Regex Debugging:

    • The validator's regex is simple but may need adjustment for custom use cases.
    • Inspect the source: Validator.php.
  3. Logging:

    • Log rejected callbacks for security audits:
    if (!$validator->validate($callback)) {
        \Log::warning("Invalid JSONP callback: $callback");
    }
    

Config Quirks

  • No Configuration: The package is stateless and requires no configuration. All logic is self-contained.

Extension Points

  1. Custom Validation Logic: Extend the validator class to add rules:

    namespace App\Services;
    
    use JsonpCallbackValidator as BaseValidator;
    
    class CustomJsonpValidator extends BaseValidator
    {
        protected function getRegex()
        {
            return '/^([a-zA-Z_$][a-zA-Z0-9_$]*)(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/';
        }
    }
    
  2. Whitelist Integration: Combine with a whitelist for stricter control:

    class WhitelistedJsonpValidator
    {
        private $whitelist;
    
        public function __construct(array $whitelist)
        {
            $this->whitelist = $whitelist;
        }
    
        public function validate($callback)
        {
            return in_array($callback, $this->whitelist, true) ||
                   JsonpCallbackValidator::validate($callback);
        }
    }
    
  3. Event-Based Validation: Trigger events when callbacks are validated/rejected:

    event(new JsonpCallbackValidated($callback));
    event(new JsonpCallbackRejected($callback));
    
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.
yandex/translate-api
voku/simple_html_dom
league/flysystem-vfs
bkwld/upchuck
filament/spatie-laravel-tags-plugin
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php