app.php 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. use App\Exceptions\Problem;
  3. use App\Http\Middleware\HandleInertiaRequests;
  4. use App\Http\Middleware\OpsToken;
  5. use App\Http\Middleware\SetLocale;
  6. use App\Http\Middleware\UserOperation;
  7. use App\Http\Middleware\V3\Authenticate as V3Authenticate;
  8. use App\Http\Middleware\V3\AuthenticateAdmin;
  9. use App\Http\Middleware\V3\AuthenticateAgentService;
  10. use Illuminate\Auth\AuthenticationException;
  11. use Illuminate\Foundation\Application;
  12. use Illuminate\Foundation\Configuration\Exceptions;
  13. use Illuminate\Foundation\Configuration\Middleware;
  14. use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets;
  15. use Illuminate\Http\Request;
  16. use Illuminate\Validation\ValidationException;
  17. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  18. return Application::configure(basePath: dirname(__DIR__))
  19. ->withRouting(
  20. web: __DIR__.'/../routes/web.php',
  21. api: __DIR__.'/../routes/api.php',
  22. commands: __DIR__.'/../routes/console.php',
  23. health: '/up',
  24. )
  25. ->withMiddleware(function (Middleware $middleware): void {
  26. $middleware->web(append: [
  27. HandleInertiaRequests::class,
  28. AddLinkHeadersForPreloadedAssets::class,
  29. ]);
  30. // API 组中间件(来自原 Laravel 8 Kernel)
  31. $middleware->api(append: [
  32. UserOperation::class,
  33. ]);
  34. // web 组中间件
  35. $middleware->web(append: [
  36. SetLocale::class,
  37. ]);
  38. $middleware->alias([
  39. 'ops.token' => OpsToken::class,
  40. // v3 的登录闸。只认 bearer,未登录在进控制器前就 401——
  41. // 所以「未登录 + 参数非法」得到的是 401 而不是 422
  42. 'auth.v3' => V3Authenticate::class,
  43. // 服务间鉴权:只放行 AI 对话服务(X-Agent-Service-Key)
  44. 'auth.agent-service' => AuthenticateAgentService::class,
  45. // 管理员闸:排在 auth.v3 之后,非 root / administrator 一律 403
  46. 'auth.v3.admin' => AuthenticateAdmin::class,
  47. ]);
  48. })
  49. ->withExceptions(function (Exceptions $exceptions): void {
  50. // api/* 一律回 JSON。默认只在客户端声明 Accept: application/json 时才回 JSON,
  51. // 否则校验失败会 302 跳首页——客户端跟随重定向就拿到一张 HTML,
  52. // 比拿到错误码更难排查。
  53. $exceptions->shouldRenderJsonWhen(
  54. fn ($request, Throwable $e): bool => $request->is('api/*') || $request->expectsJson()
  55. );
  56. /*
  57. |----------------------------------------------------------------------
  58. | v3 的错误一律 RFC 9457 Problem Details
  59. |----------------------------------------------------------------------
  60. |
  61. | 控制器只管抛异常,格式化在这里统一做。**只接管 api/v3/**:v2 的错误
  62. | 形状(Laravel 默认的 {message, errors}、以及自写的 {ok:false,…})在
  63. | dashboard-v4 下线前一个字节都不能变。
  64. |
  65. | 不需要为 ModelNotFoundException / AuthorizationException 单独注册:
  66. | Handler::prepareException() 在 render 回调之前就把它们分别转成了
  67. | NotFoundHttpException(404) 与 AccessDeniedHttpException(403),
  68. | 会被下面的兜底按状态码正确处理;给它们写处理器反而是死代码。
  69. |
  70. | AuthenticationException 则不在那张转换表里,且默认行为会尝试重定向到
  71. | login 路由,所以必须显式处理。
  72. |
  73. */
  74. $isV3 = fn (Request $request): bool => $request->is('api/v3/*');
  75. $exceptions->render(function (ValidationException $e, Request $request) use ($isV3) {
  76. if ($isV3($request)) {
  77. return Problem::response(
  78. $request, 422, 'validation-error', null,
  79. $e->getMessage(), ['errors' => $e->errors()],
  80. );
  81. }
  82. });
  83. $exceptions->render(function (AuthenticationException $e, Request $request) use ($isV3) {
  84. if ($isV3($request)) {
  85. return Problem::response($request, 401, 'unauthenticated');
  86. }
  87. });
  88. $exceptions->render(function (Throwable $e, Request $request) use ($isV3) {
  89. if (! $isV3($request)) {
  90. return null;
  91. }
  92. $status = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;
  93. $slug = match (true) {
  94. $status === 404 => 'not-found',
  95. $status === 403 => 'forbidden',
  96. $status >= 500 => 'server-error',
  97. default => 'request-error',
  98. };
  99. // 生产环境不泄露 5xx 的内部信息
  100. $detail = ($status < 500 || config('app.debug')) ? $e->getMessage() : null;
  101. return Problem::response($request, $status, $slug, null, $detail);
  102. });
  103. })->create();