*/ protected array $except = [ 'current_password', 'password', 'password_confirmation', 'password_old', ]; /** @var list */ private array $richFields = []; 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 * @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 { $this->richFields = array_values($params); try { return parent::handle($request, $next); } finally { $this->richFields = []; } } #[\Override] protected function cleanValue($key, $value): mixed { if ($this->matchesPattern((string) $key, $this->except)) { return $value; } return parent::cleanValue($key, $value); } #[\Override] protected function transform($key, $value): mixed { if (! is_string($value)) { return $value; } if ($this->matchesPattern((string) $key, $this->richFields)) { return $this->sanitizeRichInput($value); } return strip_tags($value); } /** * @param list $patterns */ private function matchesPattern(string $key, array $patterns): bool { 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); } private function sanitizeRichInput(string $input): string { $decoded = \json_decode($input, true); if ($decoded && is_array($decoded)) { \array_walk_recursive($decoded, function (mixed &$item): void { 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.'); } return $this->purifyString($input); } 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('/(?<=)/m', '') ->toString(); } }