headers->set('X-Content-Type-Options', 'nosniff'); // 防点击劫持(现代浏览器看 frame-ancestors,旧浏览器看 X-Frame-Options) $response->headers->set('X-Frame-Options', 'DENY'); // Referrer 泄露控制 $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin'); // 关闭不必要的浏览器敏感能力 $response->headers->set( 'Permissions-Policy', "geolocation=(), camera=(), microphone=(), payment=(), usb=(), interest-cohort=()" ); // 内容安全策略:限制脚本/样式/连接/表单来源,缩小 XSS 影响面 $csp = implode('; ', [ "default-src 'self'", "script-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com", "style-src 'self' 'unsafe-inline' https://cdn.tailwindcss.com", "img-src 'self' data: https:", "font-src 'self' data:", "connect-src 'self'", "frame-ancestors 'none'", "base-uri 'self'", "form-action 'self'", ]); $response->headers->set('Content-Security-Policy', $csp); // HSTS:仅生产 + HTTPS 时下发 if ($request->isSecure() && app()->environment('production')) { $response->headers->set( 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload' ); } // 禁止代理/浏览器缓存动态页面(含 CSRF token 的表单页)。 // 否则 nginx/浏览器缓存的旧 HTML 会携带过期 _token,提交即触发 419 Page Expired。 // 静态资源由 web 服务器直接服务、不经过本中间件,不受影响。 $response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate, private'); $response->headers->set('Pragma', 'no-cache'); $response->headers->set('Expires', '0'); return $response; } }