ldc-cocotte/app/Http/Middleware/HtmlSanitizer.php

142 lines
3.9 KiB
PHP
Raw Permalink Normal View History

2026-06-14 21:32:07 +02:00
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TransformsRequest;
use Illuminate\Support\Str;
2026-06-14 21:32:07 +02:00
use Mews\Purifier\Purifier;
/**
* Portable request sanitization middleware built on Laravel's `TransformsRequest`.
*
* Cleans query, form, and JSON bags while leaving uploaded files untouched:
* strips HTML tags by default, applies HTMLPurifier to listed rich-HTML fields,
* and skips fields matching `$except`.
*/
class HtmlSanitizer extends TransformsRequest
2026-06-14 21:32:07 +02:00
{
/**
* The attributes that should not be sanitized.
*
* @var list<string>
*/
protected array $except = [
'current_password',
'password',
'password_confirmation',
'password_old',
];
/** @var list<string> */
private array $richFields = [];
2026-06-14 21:32:07 +02:00
public function __construct(
private readonly Purifier $purifierService
) {
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request):(\Symfony\Component\HttpFoundation\Response) $next
2026-06-14 21:32:07 +02:00
* @param string ...$params List of input names that should be sanitized with rich sanitization (allowing some HTML)
*/
#[\Override]
public function handle($request, \Closure $next, string ...$params): mixed
2026-06-14 21:32:07 +02:00
{
$this->richFields = array_values($params);
2026-06-14 21:32:07 +02:00
try {
return parent::handle($request, $next);
} finally {
$this->richFields = [];
}
2026-06-14 21:32:07 +02:00
}
#[\Override]
protected function cleanValue($key, $value): mixed
{
if ($this->matchesPattern((string) $key, $this->except)) {
return $value;
2026-06-14 21:32:07 +02:00
}
return parent::cleanValue($key, $value);
}
2026-06-14 21:32:07 +02:00
#[\Override]
protected function transform($key, $value): mixed
{
if (! is_string($value)) {
return $value;
}
2026-06-14 21:32:07 +02:00
if ($this->matchesPattern((string) $key, $this->richFields)) {
return $this->sanitizeRichInput($value);
2026-06-14 21:32:07 +02:00
}
return strip_tags($value);
2026-06-14 21:32:07 +02:00
}
/**
* @param list<string> $patterns
2026-06-14 21:32:07 +02:00
*/
private function matchesPattern(string $key, array $patterns): bool
2026-06-14 21:32:07 +02:00
{
if ($patterns === []) {
return false;
}
$root = Str::before($key, '.');
$leaf = Str::afterLast($key, '.');
return Str::is($patterns, $key)
|| Str::is($patterns, $root)
|| Str::is($patterns, $leaf);
2026-06-14 21:32:07 +02:00
}
private function sanitizeRichInput(string $input): string
2026-06-14 21:32:07 +02:00
{
$decoded = \json_decode($input, true);
if ($decoded && is_array($decoded)) {
\array_walk_recursive($decoded, function (mixed &$item): void {
2026-06-14 21:32:07 +02:00
if (\is_string($item)) {
$item = $this->purifyString($item);
}
});
return json_encode($decoded, \JSON_THROW_ON_ERROR)
?: throw new \UnexpectedValueException('Failed to encode JSON after sanitization.');
2026-06-14 21:32:07 +02:00
}
return $this->purifyString($input);
2026-06-14 21:32:07 +02:00
}
private function purifyString(string $input): string
{
$cleaned = $this->purifierService->clean($input);
if (! is_string($cleaned)) {
throw new \UnexpectedValueException('Purifier should return a string when input is a string.');
}
return $this->stripCkEditorSchemesOnMediaInputs($cleaned);
}
/**
* Strip scheme (http) on oembed urls
* Only embed allowed are for MP4 self hosted videos right now
*
* https is force by ckeditor MediaElements which natively supports
* only cloud hosted medias (youtube, spotify etc..)
*/
private function stripCkEditorSchemesOnMediaInputs(string $input): string
{
return Str::of($input)
->replaceMatches('/(?<=<oembed url=")(http:\/\/)(?=.*?">)/m', '')
->toString();
2026-06-14 21:32:07 +02:00
}
}