<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Guards the internal terminal-resolve endpoint: only the terminal sidecar (which holds the shared
 * secret, injected from the same .env) may call it. The endpoint hands out decrypted SSH credentials,
 * so it must never be reachable without the secret — and it is only routed on the private network.
 */
class VerifyTerminalSidecarSecret
{
    public function handle(Request $request, Closure $next): Response
    {
        $expected = (string) config('clusev.terminal_secret');
        $given = (string) $request->header('X-Sidecar-Secret', '');

        abort_if($expected === '' || ! hash_equals($expected, $given), 403);

        return $next($request);
    }
}
