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.
eval(), making this validator a critical security layer for any Laravel app processing user-provided callbacks.validate() method) with no Laravel-specific abstractions. Integration requires zero framework modifications beyond dependency injection./api/jsonp)?callback=foo) or static ones?400 Bad Request?Validator facade (for custom rules)?Installation:
composer require willdurand/jsonp-callback-validator
Option 1: Middleware Integration (Recommended for API endpoints):
// app/Http/Middleware/ValidateJsonpCallback.php
namespace App\Http\Middleware;
use Closure;
use JsonpCallbackValidator;
class ValidateJsonpCallback
{
public function handle($request, Closure $next)
{
$callback = $request->query('callback');
if ($callback && !JsonpCallbackValidator::validate($callback)) {
return response()->json(['error' => 'Invalid callback'], 400);
}
return $next($request);
}
}
Register in app/Http/Kernel.php:
protected $routeMiddleware = [
'validate.jsonp' => \App\Http\Middleware\ValidateJsonpCallback::class,
];
Usage in routes:
Route::get('/jsonp', function () { ... })->middleware('validate.jsonp');
Option 2: Service Layer (For reusable validation):
// app/Services/JsonpValidator.php
namespace App\Services;
use JsonpCallbackValidator;
class JsonpValidator
{
public function validateCallback(string $callback): bool
{
return JsonpCallbackValidator::validate($callback);
}
}
Inject into controllers/services:
public function __construct(private JsonpValidator $validator) {}
Option 3: Form Request Validation (For web routes):
Extend Laravel’s FormRequest and use the validator in rules():
public function rules()
{
return [
'callback' => ['required', 'string', function ($attribute, $value, $fail) {
if (!JsonpCallbackValidator::validate($value)) {
$fail('The callback must be a valid JSONP function name.');
}
}],
];
}
callback()).(function xss(){...}), eval(...), window.location.JSONP.callback, app.handleResponse.| Failure Scenario | Impact | Mitigation |
|---|---|---|
| False positive (valid callback rejected) | Breaks legitimate JSONP consumers | Test with real-world payloads; adjust rules if needed. |
| False negative (malicious callback allowed) | XSS vulnerability | Combine with CSP headers, input sanitization, and logging. |
| Middleware/service misconfiguration | No validation applied | Unit tests for validation logic; integration tests for endpoints. |
| PHP version incompatibility | Fails silently or throws errors | Pin to ^2.0 in composer.json; test on CI. |
How can I help you explore Laravel packages today?