This commit is contained in:
2026-05-01 23:40:14 +08:00
commit b8f599a617
3867 changed files with 478663 additions and 0 deletions
@@ -0,0 +1,41 @@
<?php
namespace Illuminate\Http\Middleware;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Vite;
class AddLinkHeadersForPreloadedAssets
{
/**
* Configure the middleware.
*
* @param int $limit
* @return string
*/
public static function using($limit)
{
return static::class.':'.$limit;
}
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int|null $limit
* @return \Illuminate\Http\Response
*/
public function handle($request, $next, $limit = null)
{
return tap($next($request), function ($response) use ($limit) {
if ($response instanceof Response && Vite::preloadedAssets() !== []) {
$response->header('Link', (new Collection(Vite::preloadedAssets()))
->when($limit, fn ($assets, $limit) => $assets->take($limit))
->map(fn ($attributes, $url) => "<{$url}>; ".implode('; ', $attributes))
->join(', '), false);
}
});
}
}
@@ -0,0 +1,27 @@
<?php
namespace Illuminate\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\Response;
class CheckResponseForModifications
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
if ($response instanceof Response) {
$response->isNotModified($request);
}
return $response;
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace Illuminate\Http\Middleware;
use Closure;
class FrameGuard
{
/**
* Handle the given request and get the response.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Symfony\Component\HttpFoundation\Response
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('X-Frame-Options', 'SAMEORIGIN', false);
return $response;
}
}
+141
View File
@@ -0,0 +1,141 @@
<?php
namespace Illuminate\Http\Middleware;
use Closure;
use Fruitcake\Cors\CorsService;
use Illuminate\Contracts\Container\Container;
use Illuminate\Http\Request;
class HandleCors
{
/**
* The container instance.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* The CORS service instance.
*
* @var \Fruitcake\Cors\CorsService
*/
protected $cors;
/**
* All of the registered skip callbacks.
*
* @var array<int, \Closure(\Illuminate\Http\Request): bool>
*/
protected static $skipCallbacks = [];
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Container\Container $container
* @param \Fruitcake\Cors\CorsService $cors
*/
public function __construct(Container $container, CorsService $cors)
{
$this->container = $container;
$this->cors = $cors;
}
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response
*/
public function handle($request, Closure $next)
{
foreach (static::$skipCallbacks as $callback) {
if ($callback($request)) {
return $next($request);
}
}
if (! $this->hasMatchingPath($request)) {
return $next($request);
}
$this->cors->setOptions($this->container['config']->get('cors', []));
if ($this->cors->isPreflightRequest($request)) {
$response = $this->cors->handlePreflightRequest($request);
$this->cors->varyHeader($response, 'Access-Control-Request-Method');
return $response;
}
$response = $next($request);
if ($request->getMethod() === 'OPTIONS') {
$this->cors->varyHeader($response, 'Access-Control-Request-Method');
}
return $this->cors->addActualRequestHeaders($response, $request);
}
/**
* Get the path from the configuration to determine if the CORS service should run.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function hasMatchingPath(Request $request): bool
{
$paths = $this->getPathsByHost($request->getHost());
foreach ($paths as $path) {
if ($path !== '/') {
$path = trim($path, '/');
}
if ($request->fullUrlIs($path) || $request->is($path)) {
return true;
}
}
return false;
}
/**
* Get the CORS paths for the given host.
*
* @param string $host
* @return array
*/
protected function getPathsByHost(string $host)
{
$paths = $this->container['config']->get('cors.paths', []);
return $paths[$host] ?? array_filter($paths, function ($path) {
return is_string($path);
});
}
/**
* Register a callback that instructs the middleware to be skipped.
*
* @param \Closure $callback
* @return void
*/
public static function skipWhen(Closure $callback)
{
static::$skipCallbacks[] = $callback;
}
/**
* Flush the middleware's global state.
*
* @return void
*/
public static function flushState()
{
static::$skipCallbacks = [];
}
}
@@ -0,0 +1,65 @@
<?php
namespace Illuminate\Http\Middleware;
use Closure;
class PrefersJsonResponses
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$accept = $request->headers->get('Accept');
if ($this->acceptHeaderIsBroad($accept)) {
if ($accept !== null) {
$request->headers->set('X-Original-Accept', $accept);
}
$request->headers->set('Accept', 'application/json');
}
return $next($request);
}
/**
* Determine if the given "Accept" header value is broad enough to be treated as JSON.
*
* The header is broad when it's missing or every media-type listed is wildcard ("*\/*" or "application/*").
*
* @param string|null $accept
* @return bool
*/
protected function acceptHeaderIsBroad($accept)
{
if ($accept === null || trim($accept) === '') {
return true;
}
foreach (explode(',', $accept) as $value) {
$value = strtolower(trim($value));
if ($value === '') {
continue;
}
$pos = strpos($value, ';');
if ($pos !== false) {
$value = trim(substr($value, 0, $pos));
}
if (! in_array($value, ['*/*', 'application/*'], true)) {
return false;
}
}
return true;
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace Illuminate\Http\Middleware;
use Closure;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
class SetCacheHeaders
{
/**
* Specify the options for the middleware.
*
* @param array|string $options
* @return string
*/
public static function using($options)
{
if (is_string($options)) {
return static::class.':'.$options;
}
return (new Collection($options))
->map(function ($value, $key) {
if (is_bool($value)) {
return $value ? $key : null;
}
return is_int($key) ? $value : "{$key}={$value}";
})
->filter()
->map(fn ($value) => Str::finish($value, ';'))
->pipe(fn ($options) => rtrim(static::class.':'.$options->implode(''), ';'));
}
/**
* Add cache related HTTP headers.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|array $options
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \InvalidArgumentException
*/
public function handle($request, Closure $next, $options = [])
{
$response = $next($request);
if (! $request->isMethodCacheable() || (! $response->getContent() && ! $response instanceof BinaryFileResponse && ! $response instanceof StreamedResponse)) {
return $response;
}
if (is_string($options)) {
$options = $this->parseOptions($options);
}
if (! $response->isSuccessful()) {
return $response;
}
if (isset($options['etag']) && $options['etag'] === true) {
$options['etag'] = $response->getEtag() ?? ($response->getContent() ? hash('xxh128', $response->getContent()) : null);
}
if (isset($options['last_modified'])) {
if (is_numeric($options['last_modified'])) {
$options['last_modified'] = Carbon::createFromTimestamp($options['last_modified'], date_default_timezone_get());
} else {
$options['last_modified'] = Carbon::parse($options['last_modified']);
}
}
$response->setCache($options);
$response->isNotModified($request);
return $response;
}
/**
* Parse the given header options.
*
* @param string $options
* @return array
*/
protected function parseOptions($options)
{
return (new Collection(explode(';', rtrim($options, ';'))))->mapWithKeys(function ($option) {
$data = explode('=', $option, 2);
return [$data[0] => $data[1] ?? true];
})->all();
}
}
+127
View File
@@ -0,0 +1,127 @@
<?php
namespace Illuminate\Http\Middleware;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
class TrustHosts
{
/**
* The application instance.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* The trusted hosts that have been configured to always be trusted.
*
* @var array<int, string>|(callable(): array<int, string>)|null
*/
protected static $alwaysTrust;
/**
* Indicates whether subdomains of the application URL should be trusted.
*
* @var bool|null
*/
protected static $subdomains;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* Get the host patterns that should be trusted.
*
* @return array
*/
public function hosts()
{
if (is_null(static::$alwaysTrust)) {
return [$this->allSubdomainsOfApplicationUrl()];
}
$hosts = match (true) {
is_array(static::$alwaysTrust) => static::$alwaysTrust,
is_callable(static::$alwaysTrust) => call_user_func(static::$alwaysTrust),
default => [],
};
if (static::$subdomains) {
$hosts[] = $this->allSubdomainsOfApplicationUrl();
}
return $hosts;
}
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response
*/
public function handle(Request $request, $next)
{
if ($this->shouldSpecifyTrustedHosts()) {
Request::setTrustedHosts(array_filter($this->hosts()));
}
return $next($request);
}
/**
* Specify the hosts that should always be trusted.
*
* @param array<int, string>|(callable(): array<int, string>) $hosts
* @param bool $subdomains
* @return void
*/
public static function at(array|callable $hosts, bool $subdomains = true)
{
static::$alwaysTrust = $hosts;
static::$subdomains = $subdomains;
}
/**
* Determine if the application should specify trusted hosts.
*
* @return bool
*/
protected function shouldSpecifyTrustedHosts()
{
return ! $this->app->environment('local') &&
! $this->app->runningUnitTests();
}
/**
* Get a regular expression matching the application URL and all of its subdomains.
*
* @return string|null
*/
protected function allSubdomainsOfApplicationUrl()
{
if ($host = parse_url($this->app['config']->get('app.url'), PHP_URL_HOST)) {
return '^(.+\.)?'.preg_quote($host).'$';
}
}
/**
* Flush the state of the middleware.
*
* @return void
*/
public static function flushState()
{
static::$alwaysTrust = null;
static::$subdomains = null;
}
}
+202
View File
@@ -0,0 +1,202 @@
<?php
namespace Illuminate\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class TrustProxies
{
/**
* The trusted proxies for the application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The trusted proxies headers for the application.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_PREFIX |
Request::HEADER_X_FORWARDED_AWS_ELB;
/**
* The proxies that have been configured to always be trusted.
*
* @var array<int, string>|string|null
*/
protected static $alwaysTrustProxies;
/**
* The proxies headers that have been configured to always be trusted.
*
* @var int|null
*/
protected static $alwaysTrustHeaders;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function handle(Request $request, Closure $next)
{
$request::setTrustedProxies([], $this->getTrustedHeaderNames());
$this->setTrustedProxyIpAddresses($request);
return $next($request);
}
/**
* Sets the trusted proxies on the request.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function setTrustedProxyIpAddresses(Request $request)
{
$trustedIps = $this->proxies() ?: config('trustedproxy.proxies');
if (is_null($trustedIps) &&
(laravel_cloud() ||
str_ends_with($request->host(), '.on-forge.com') ||
str_ends_with($request->host(), '.on-vapor.com'))) {
$trustedIps = '*';
}
if (str_ends_with($request->host(), '.on-forge.com') ||
str_ends_with($request->host(), '.on-vapor.com')) {
$request->headers->remove('X-Forwarded-Host');
}
if ($trustedIps === '*' || $trustedIps === '**') {
return $this->setTrustedProxyIpAddressesToTheCallingIp($request);
}
$trustedIps = is_string($trustedIps)
? array_map(trim(...), explode(',', $trustedIps))
: $trustedIps;
if (is_array($trustedIps)) {
return $this->setTrustedProxyIpAddressesToSpecificIps($request, $trustedIps);
}
}
/**
* Specify the IP addresses to trust explicitly.
*
* @param \Illuminate\Http\Request $request
* @param array $trustedIps
* @return void
*/
protected function setTrustedProxyIpAddressesToSpecificIps(Request $request, array $trustedIps)
{
$request->setTrustedProxies(array_reduce($trustedIps, function ($ips, $trustedIp) use ($request) {
$ips[] = $trustedIp === 'REMOTE_ADDR'
? $request->server->get('REMOTE_ADDR')
: $trustedIp;
return $ips;
}, []), $this->getTrustedHeaderNames());
}
/**
* Set the trusted proxy to be the IP address calling this servers.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function setTrustedProxyIpAddressesToTheCallingIp(Request $request)
{
$request->setTrustedProxies([$request->server->get('REMOTE_ADDR')], $this->getTrustedHeaderNames());
}
/**
* Retrieve trusted header name(s), falling back to defaults if config not set.
*
* @return int A bit field of Request::HEADER_*, to set which headers to trust from your proxies.
*/
protected function getTrustedHeaderNames()
{
$headers = $this->headers();
if (is_int($headers)) {
return $headers;
}
return match ($headers) {
'HEADER_X_FORWARDED_AWS_ELB' => Request::HEADER_X_FORWARDED_AWS_ELB,
'HEADER_FORWARDED' => Request::HEADER_FORWARDED,
'HEADER_X_FORWARDED_FOR' => Request::HEADER_X_FORWARDED_FOR,
'HEADER_X_FORWARDED_HOST' => Request::HEADER_X_FORWARDED_HOST,
'HEADER_X_FORWARDED_PORT' => Request::HEADER_X_FORWARDED_PORT,
'HEADER_X_FORWARDED_PROTO' => Request::HEADER_X_FORWARDED_PROTO,
'HEADER_X_FORWARDED_PREFIX' => Request::HEADER_X_FORWARDED_PREFIX,
default => Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_PREFIX | Request::HEADER_X_FORWARDED_AWS_ELB,
};
}
/**
* Get the trusted headers.
*
* @return int
*/
protected function headers()
{
return static::$alwaysTrustHeaders ?: $this->headers;
}
/**
* Get the trusted proxies.
*
* @return array|string|null
*/
protected function proxies()
{
return static::$alwaysTrustProxies ?: $this->proxies;
}
/**
* Specify the IP addresses of proxies that should always be trusted.
*
* @param array|string $proxies
* @return void
*/
public static function at(array|string $proxies)
{
static::$alwaysTrustProxies = $proxies;
}
/**
* Specify the proxy headers that should always be trusted.
*
* @param int $headers
* @return void
*/
public static function withHeaders(int $headers)
{
static::$alwaysTrustHeaders = $headers;
}
/**
* Flush the state of the middleware.
*
* @return void
*/
public static function flushState()
{
static::$alwaysTrustHeaders = null;
static::$alwaysTrustProxies = null;
}
}
@@ -0,0 +1,30 @@
<?php
namespace Illuminate\Http\Middleware;
use Closure;
use Illuminate\Http\Exceptions\MalformedUrlException;
use Illuminate\Http\Request;
class ValidatePathEncoding
{
/**
* Validate that the incoming request has a valid UTF-8 encoded path.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Illuminate\Http\Exceptions\MalformedUrlException
*/
public function handle(Request $request, Closure $next)
{
$decodedPath = rawurldecode($request->path());
if (! mb_check_encoding($decodedPath, 'UTF-8')) {
throw new MalformedUrlException;
}
return $next($request);
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace Illuminate\Http\Middleware;
use Closure;
use Illuminate\Http\Exceptions\PostTooLargeException;
class ValidatePostSize
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Illuminate\Http\Exceptions\PostTooLargeException
*/
public function handle($request, Closure $next)
{
$max = $this->getPostMaxSize();
if ($max > 0 && $request->server('CONTENT_LENGTH') > $max) {
throw new PostTooLargeException('The POST data is too large.');
}
return $next($request);
}
/**
* Determine the server 'post_max_size' as bytes.
*
* @return int
*/
protected function getPostMaxSize()
{
if (is_numeric($postMaxSize = ini_get('post_max_size'))) {
return (int) $postMaxSize;
}
$metric = strtoupper(substr($postMaxSize, -1));
$postMaxSize = (int) $postMaxSize;
return match ($metric) {
'K' => $postMaxSize * 1024,
'M' => $postMaxSize * 1048576,
'G' => $postMaxSize * 1073741824,
default => $postMaxSize,
};
}
}