feat: agent token, auth.agent middleware, /mcp route with HadoServer skeleton
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BCrwHHnGCB5XH968Nxokqw
This commit is contained in:
36
core/app/Console/Commands/AgentTokenCommand.php
Normal file
36
core/app/Console/Commands/AgentTokenCommand.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Ingest\EventUpserter;
|
||||
use App\Models\AgentToken;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class AgentTokenCommand extends Command
|
||||
{
|
||||
protected $signature = 'hado:agent:token {login : Логин пользователя, как в X-Remote-User} {--revoke : Отозвать токен, ничего не печатать}';
|
||||
|
||||
protected $description = 'Выпускает токен агента (MCP) для пользователя и печатает его один раз; повторный вызов перевыпускает';
|
||||
|
||||
public function handle(EventUpserter $users): int
|
||||
{
|
||||
$user = $users->ensureUser((string) $this->argument('login'));
|
||||
$had = AgentToken::where('user_id', $user->id)->exists();
|
||||
|
||||
if ($this->option('revoke')) {
|
||||
AgentToken::where('user_id', $user->id)->delete();
|
||||
$this->info($had ? "Токен агента для «{$user->login}» отозван." : "У «{$user->login}» не было токена агента.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$token = AgentToken::issue($user);
|
||||
$this->info($had
|
||||
? "Токен агента для «{$user->login}» перевыпущен, старый больше не работает."
|
||||
: "Токен агента для «{$user->login}» создан.");
|
||||
$this->line('Показывается один раз, в базе только хэш.');
|
||||
$this->line("Token: {$token}");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
32
core/app/Http/Middleware/AuthenticateAgent.php
Normal file
32
core/app/Http/Middleware/AuthenticateAgent.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\AgentToken;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Вход агента (MCP): Bearer-токен агента → пользователь.
|
||||
* Кладёт user в тот же атрибут, что RemoteUser, — дальше код не различает, кто пришёл.
|
||||
*/
|
||||
class AuthenticateAgent
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$token = $request->bearerToken();
|
||||
if ($token === null || $token === '') {
|
||||
return response()->json(['message' => 'Нужен Bearer-токен агента'], 401);
|
||||
}
|
||||
|
||||
$agent = AgentToken::findByToken($token);
|
||||
if ($agent === null) {
|
||||
return response()->json(['message' => 'Неизвестный токен агента'], 401);
|
||||
}
|
||||
|
||||
$request->attributes->set('user', $agent->user);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
32
core/app/Mcp/HadoServer.php
Normal file
32
core/app/Mcp/HadoServer.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mcp;
|
||||
|
||||
use Laravel\Mcp\Server;
|
||||
|
||||
class HadoServer extends Server
|
||||
{
|
||||
protected string $name = 'Hado';
|
||||
|
||||
protected string $version = '1.0.0';
|
||||
|
||||
protected string $instructions = <<<'MD'
|
||||
Hado — ядро напоминаний пользователя. Ты действуешь от его лица: видишь все его события, ставишь свои, закрываешь любые.
|
||||
|
||||
Событие — это срок (`due_at`) и день старта подготовки (`fire_at`). Состояния: `scheduled` (старт не пришёл, молчит),
|
||||
`preparing` (напоминает раз в день), `today` (день срока, каждый час), `overdue` (срок прошёл, `after_due = keep`),
|
||||
`done` (пользователь закрыл), `expired` (срок прошёл, `after_due = expire`), `withdrawn` (снято).
|
||||
|
||||
«Сделано» (`mark_done`) закрывает событие. «Помню» (`mark_ack`) — только глушит текущее напоминание, событие живёт.
|
||||
|
||||
Свои события ты создаёшь от источника `manual` — того же, что кнопка в инбоксе. Их можно править и снимать.
|
||||
События других источников (`editable: false`) ты видишь и можешь закрыть, но не правишь и не снимаешь — их источник
|
||||
перезапишет правку при следующей синхронизации.
|
||||
|
||||
`due_at`: `YYYY-MM-DD` (весь день), `YYYY-MM-DDTHH:MM` (едет за поясом пользователя) или со смещением
|
||||
`YYYY-MM-DDTHH:MM+02:00` — только если событие привязано к месту (вылет, встреча по чужому времени).
|
||||
Повторяющееся — отдельные события на каждое вхождение, не одно с переносом даты.
|
||||
MD;
|
||||
|
||||
protected array $tools = [];
|
||||
}
|
||||
30
core/app/Models/AgentToken.php
Normal file
30
core/app/Models/AgentToken.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class AgentToken extends Model
|
||||
{
|
||||
protected $guarded = [];
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/** Выпускает (или перевыпускает) токен пользователя; возвращает открытый токен — показать один раз. */
|
||||
public static function issue(User $user): string
|
||||
{
|
||||
$token = 'hado_agent_'.bin2hex(random_bytes(32));
|
||||
static::updateOrCreate(['user_id' => $user->id], ['token_hash' => hash('sha256', $token)]);
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
public static function findByToken(string $token): ?self
|
||||
{
|
||||
return static::where('token_hash', hash('sha256', $token))->first();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Middleware\AuthenticateAgent;
|
||||
use App\Http\Middleware\AuthenticateSource;
|
||||
use App\Http\Middleware\RemoteUser;
|
||||
use Illuminate\Foundation\Application;
|
||||
@@ -18,12 +19,13 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
$middleware->trustProxies(at: '*');
|
||||
$middleware->alias([
|
||||
'auth.source' => AuthenticateSource::class,
|
||||
'auth.agent' => AuthenticateAgent::class,
|
||||
'remote.user' => RemoteUser::class,
|
||||
]);
|
||||
$middleware->validateCsrfTokens(except: ['a/*', 'hooks/*', 'me/heartbeat']);
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions): void {
|
||||
$exceptions->shouldRenderJsonWhen(
|
||||
fn (Request $request) => $request->expectsJson() || $request->is('api/*') || $request->is('a/*') || $request->is('hooks/*'),
|
||||
fn (Request $request) => $request->expectsJson() || $request->is('api/*') || $request->is('a/*') || $request->is('hooks/*') || $request->is('mcp'),
|
||||
);
|
||||
})->create();
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
// Токен агента (MCP): один на пользователя, строка есть — токен есть.
|
||||
Schema::create('agent_tokens', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->unique()->constrained()->cascadeOnDelete();
|
||||
$table->string('token_hash', 64)->unique();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('agent_tokens');
|
||||
}
|
||||
};
|
||||
7
core/routes/ai.php
Normal file
7
core/routes/ai.php
Normal file
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Mcp\HadoServer;
|
||||
use Laravel\Mcp\Facades\Mcp;
|
||||
|
||||
// Вход агента (§11): без сессии и CSRF (маршрут вне группы web), мимо forward_auth хаба.
|
||||
Mcp::web('/mcp', HadoServer::class)->middleware(['auth.agent', 'throttle:60,1']);
|
||||
45
core/tests/Feature/AgentTokenCommandTest.php
Normal file
45
core/tests/Feature/AgentTokenCommandTest.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\AgentToken;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AgentTokenCommandTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_issues_token_creating_user_if_needed(): void
|
||||
{
|
||||
$this->artisan('hado:agent:token', ['login' => 'nikita'])
|
||||
->expectsOutputToContain('Token: hado_agent_')
|
||||
->assertSuccessful();
|
||||
|
||||
$user = User::where('login', 'nikita')->sole();
|
||||
$this->assertSame(64, strlen(AgentToken::where('user_id', $user->id)->sole()->token_hash));
|
||||
}
|
||||
|
||||
public function test_reissue_replaces_the_old_token(): void
|
||||
{
|
||||
$this->artisan('hado:agent:token', ['login' => 'nikita'])->assertSuccessful();
|
||||
$old = AgentToken::sole()->token_hash;
|
||||
|
||||
$this->artisan('hado:agent:token', ['login' => 'nikita'])
|
||||
->expectsOutputToContain('перевыпущен')
|
||||
->assertSuccessful();
|
||||
|
||||
$this->assertSame(1, AgentToken::count());
|
||||
$this->assertNotSame($old, AgentToken::sole()->token_hash);
|
||||
}
|
||||
|
||||
public function test_revoke_deletes_the_token(): void
|
||||
{
|
||||
$this->artisan('hado:agent:token', ['login' => 'nikita'])->assertSuccessful();
|
||||
|
||||
$this->artisan('hado:agent:token', ['login' => 'nikita', '--revoke' => true])->assertSuccessful();
|
||||
|
||||
$this->assertSame(0, AgentToken::count());
|
||||
}
|
||||
}
|
||||
39
core/tests/Feature/McpAuthTest.php
Normal file
39
core/tests/Feature/McpAuthTest.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\AgentToken;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class McpAuthTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private const INITIALIZE = [
|
||||
'jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize',
|
||||
'params' => ['protocolVersion' => '2025-06-18', 'capabilities' => [], 'clientInfo' => ['name' => 'test', 'version' => '0']],
|
||||
];
|
||||
|
||||
public function test_requires_agent_token(): void
|
||||
{
|
||||
$this->postJson('/mcp', self::INITIALIZE)->assertStatus(401)->assertJsonPath('message', 'Нужен Bearer-токен агента');
|
||||
$this->postJson('/mcp', self::INITIALIZE, ['Authorization' => 'Bearer nope'])->assertStatus(401)->assertJsonPath('message', 'Неизвестный токен агента');
|
||||
}
|
||||
|
||||
public function test_remote_user_header_is_not_enough(): void
|
||||
{
|
||||
$this->postJson('/mcp', self::INITIALIZE, ['X-Remote-User' => 'nikita'])->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_valid_token_reaches_the_server(): void
|
||||
{
|
||||
$user = User::create(['login' => 'nikita', 'tz' => 'UTC']);
|
||||
AgentToken::create(['user_id' => $user->id, 'token_hash' => hash('sha256', 'secret')]);
|
||||
|
||||
$this->postJson('/mcp', self::INITIALIZE, ['Authorization' => 'Bearer secret'])
|
||||
->assertOk()
|
||||
->assertJsonPath('result.serverInfo.name', 'Hado');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user