Кнопка проверки источника входящих вебхуков в панели

This commit is contained in:
rsgrinko committed 2026-09-16 11:04:58 +03:00
1 parent e4a5592802
commit 5d01831ebd
5 files changed
+110

No files matched your search

@@ -214,6 +214,37 @@ final class WebhooksController extends Controller
return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]);
}
/**
* Пробная посылка себе, как от источника: проверяет и токен, и обработчик,
* ничего не дожидаясь в очереди — результат виден сразу, строкой в журнале.
*/
public function testIncoming(Request $request): Response
{
$key = trim($request->text('source'));
if (Incoming::source($key) === null) {
$this->flash('Такого источника нет', 'error');
return $this->redirect('admin.webhooks.incoming');
}
$status = Incoming::test($key);
$labels = [
IncomingHook::DONE => ['Обработчик отработал без ошибок', 'ok'],
IncomingHook::FAILED => ['Токен принят, но обработчик упал — подробности в журнале ниже', 'error'],
IncomingHook::REJECTED => ['Токен не подошёл или источник не настроен — подробности в журнале ниже', 'error'],
];
[$message, $type] = $labels[$status] ?? ['Не разобрать, что случилось', 'error'];
Audit::action('incoming', 0, 'пробная посылка источнику «' . $key . '»: ' . $status);
$this->flash($message, $type);
return $this->redirect('admin.webhooks.incoming');
}
public function delete(int $id): Response
{
$webhook = $this->webhook($id);
+35
View File
@@ -38,6 +38,9 @@ final class Incoming
/** Заголовок с токеном */
public const HEADER = 'x-proton-token';
/** Пробная посылка себе — кнопка «Проверить» у источника в панели */
public const TEST_EVENT = 'incoming.test';
/** @var array<string, array{label: string, token: string, handler: callable}>|null */
private static ?array $sources = null;
@@ -123,6 +126,38 @@ final class Incoming
}
}
/**
* Пробная посылка источнику: тот же путь, что у настоящего запроса, только
* тело и токен собираем сами — токен берём из .env на сервере, в панель
* его значение никогда не уходит.
*/
public static function test(string $key): string
{
$source = self::source($key);
if ($source === null) {
return IncomingHook::UNKNOWN;
}
$payload = [
'event' => self::TEST_EVENT,
'message' => 'Проверка источника «' . $source['label'] . '»',
'sent_at' => date('Y-m-d H:i:s'),
];
$headers = [];
if ($source['token'] !== '') {
$token = Env::string($source['token'], '');
if ($token !== '') {
$headers[self::HEADER] = $token;
}
}
return self::receive($key, Request::create('POST', '/api/v1/hooks/' . $key, $payload, [], $headers));
}
/**
* Почему посылку не приняли. null — приняли, иначе текст для журнала.
*
+15
View File
@@ -113,6 +113,13 @@ $pretty = static function (mixed $payload): string {
<div class="card">
<h2>Источники</h2>
<p class="muted small">
«Проверить» шлёт себе пробную посылку тем же путём, что настоящая система:
с токеном из <span class="mono">.env</span> сервера (в панель он не уходит) и
событием <span class="mono">incoming.test</span>. Результат виден сразу — строкой
в посылках ниже, без очереди и ожидания.
</p>
<?php if ($sources === []) { ?>
<p class="muted small">Ни одного источника не объявлено — см. <span class="mono">config/incoming.php</span>.</p>
<?php } else { ?>
@@ -123,6 +130,7 @@ $pretty = static function (mixed $payload): string {
<th>Название</th>
<th>Адрес приёма</th>
<th>Токен</th>
<th></th>
</tr>
<?php foreach ($sources as $key => $source) { ?>
@@ -139,6 +147,13 @@ $pretty = static function (mixed $payload): string {
<div class="muted small">значение в <span class="mono">.env</span>, переменная <span class="mono"><?= View::e($source['token']) ?></span></div>
<?php } ?>
</td>
<td class="right">
<form method="post" action="<?= View::e(View::route('admin.webhooks.incoming.test')) ?>">
<?= View::csrf() ?>
<input type="hidden" name="source" value="<?= View::e((string) $key) ?>">
<button type="submit">Проверить</button>
</form>
</td>
</tr>
<?php } ?>
</table>
+1
View File
@@ -63,6 +63,7 @@ return static function (Router $router): void {
$router->group(['prefix' => '/webhooks', 'middleware' => 'can:' . Permission::WEBHOOKS_MANAGE], function (Router $router): void {
$router->get('', [WebhooksController::class, 'index'])->name('admin.webhooks');
$router->get('/incoming', [WebhooksController::class, 'incoming'])->name('admin.webhooks.incoming');
$router->post('/incoming/test', [WebhooksController::class, 'testIncoming'])->name('admin.webhooks.incoming.test');
$router->get('/new', [WebhooksController::class, 'create'])->name('admin.webhooks.create');
$router->post('/new', [WebhooksController::class, 'store']);
$router->get('/{id:\d+}', [WebhooksController::class, 'show'])->name('admin.webhooks.show');
+28
View File
@@ -20,9 +20,11 @@ use Rsgrinko\Proton\Models\ApiToken;
use Rsgrinko\Proton\Models\Role;
use Rsgrinko\Proton\Models\User;
use Rsgrinko\Proton\Models\UserNotification;
use Rsgrinko\Proton\Models\IncomingHook;
use Rsgrinko\Proton\Models\Webhook;
use Rsgrinko\Proton\Models\WebhookDelivery;
use Rsgrinko\Proton\Support\Settings;
use Rsgrinko\Proton\Webhooks\Incoming;
/**
* Запрос к ядру от лица пользователя (или гостя, если его нет).
@@ -358,6 +360,32 @@ test('http: подписка на события заводится и пров
assertSame(0, WebhookDelivery::query()->where('webhook_id', $webhook->id())->count(), 'журнал ушёл вместе с подпиской');
});
test('http: кнопка «Проверить» шлёт источнику пробную посылку и пишет в журнал', function (): void {
Incoming::reset();
Incoming::register('http_test', 'Проверка из панели', 'HTTP_TEST_HOOK_TOKEN', static function (): void {});
putenv('HTTP_TEST_HOOK_TOKEN=токен-панели');
$before = IncomingHook::query()->count();
$response = httpRequest('POST', '/admin/webhooks/incoming/test', httpAdmin(), ['source' => 'http_test']);
assertStatus(302, $response);
assertSame($before + 1, IncomingHook::query()->count(), 'посылка легла в журнал сразу, не через очередь');
$hook = assertNotNull(IncomingHook::query()->orderBy('id', 'desc')->first());
assertSame(IncomingHook::DONE, (string) $hook->raw('status'));
assertSame('incoming.test', (string) $hook->raw('event'));
// Неизвестный источник не роняет страницу
assertStatus(302, httpRequest('POST', '/admin/webhooks/incoming/test', httpAdmin(), ['source' => 'нет-такого']));
putenv('HTTP_TEST_HOOK_TOKEN');
Incoming::reset();
});
test('http: список фильтруется и сортируется параметрами адреса', function (): void {
$admin = httpAdmin();
$user = httpUser();