Manage webhooks from the panel
Some checks failed
Tests / lint (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / test-postgres (push) Has been cancelled
Tests / mcp (push) Has been cancelled

Create one and see its secret once, send a test, change the secret, and read
each delivery with what the other end answered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-01 11:44:11 +02:00
parent d80ed1a3e8
commit d4cf4a66b7
14 changed files with 797 additions and 26 deletions

View File

@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\Webhooks\Pages;
use App\Filament\Resources\Webhooks\WebhookResource;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
/**
* The secret is made here and shown once, on the page that opens next.
*/
class CreateWebhook extends CreateRecord
{
protected static string $resource = WebhookResource::class;
protected string $secret = '';
protected function mutateFormDataBeforeCreate(array $data): array
{
$this->secret = Str::random(40);
return [...$data, 'secret' => $this->secret];
}
protected function afterCreate(): void
{
$this->record->forceFill(['created_by' => Auth::id()])->save();
WebhookResource::showSecret($this->secret);
}
protected function getCreatedNotification(): null
{
return null;
}
protected function getRedirectUrl(): string
{
return WebhookResource::getUrl('edit', ['record' => $this->record]);
}
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\Webhooks\Pages;
use App\Filament\Resources\Webhooks\WebhookResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditWebhook extends EditRecord
{
protected static string $resource = WebhookResource::class;
protected function getHeaderActions(): array
{
return [
WebhookResource::pingAction(),
WebhookResource::rotateAction(),
DeleteAction::make(),
];
}
/**
* Switching it back on starts its failure count again, as through the API.
*/
protected function mutateFormDataBeforeSave(array $data): array
{
if (($data['is_active'] ?? false) && ! $this->record->is_active) {
$this->record->consecutive_failures = 0;
}
return $data;
}
}

View File

@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\Webhooks\Pages;
use App\Filament\Resources\Webhooks\WebhookResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListWebhooks extends ListRecords
{
protected static string $resource = WebhookResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\Webhooks\RelationManagers;
use App\Models\WebhookDelivery;
use App\Support\Webhooks\Webhooks;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\HtmlString;
/**
* What was sent, and what the other end answered.
*/
class DeliveriesRelationManager extends RelationManager
{
protected static string $relationship = 'deliveries';
public static function getTitle(Model $ownerRecord, string $pageClass): string
{
return __('panel.webhooks.deliveries.title');
}
public function isReadOnly(): bool
{
return true;
}
public function table(Table $table): Table
{
return $table
->defaultSort('id', 'desc')
->poll('10s')
->columns([
TextColumn::make('event')
->label(__('panel.webhooks.deliveries.event'))
->badge()
->color('gray'),
TextColumn::make('status')
->label(__('panel.webhooks.deliveries.status'))
->badge()
->formatStateUsing(fn (string $state) => __("panel.webhooks.deliveries.statuses.{$state}"))
->color(fn (string $state) => match ($state) {
WebhookDelivery::SUCCEEDED => 'success',
WebhookDelivery::FAILED => 'danger',
default => 'warning',
}),
TextColumn::make('response_status')
->label(__('panel.webhooks.deliveries.response'))
->placeholder('—'),
TextColumn::make('attempts')
->label(__('panel.webhooks.deliveries.attempts')),
TextColumn::make('error')
->label(__('panel.webhooks.deliveries.error'))
->limit(60)
->tooltip(fn (WebhookDelivery $record) => $record->error)
->placeholder('—')
->color('danger'),
TextColumn::make('created_at')
->label(__('panel.webhooks.deliveries.created_at'))
->since()
->dateTimeTooltip(),
])
->filters([
SelectFilter::make('status')
->label(__('panel.webhooks.deliveries.status'))
->options(collect([WebhookDelivery::PENDING, WebhookDelivery::SUCCEEDED, WebhookDelivery::FAILED])
->mapWithKeys(fn (string $s) => [$s => __("panel.webhooks.deliveries.statuses.{$s}")])
->all()),
])
->recordActions([
Action::make('payload')
->label(__('panel.webhooks.deliveries.payload'))
->icon('heroicon-o-code-bracket')
->color('gray')
->modalHeading(fn (WebhookDelivery $record) => $record->event.' · '.$record->uuid)
->modalSubmitAction(false)
->modalContent(fn (WebhookDelivery $record) => new HtmlString(
'<pre style="white-space: pre-wrap; overflow-wrap: anywhere; font-size: .8125rem;">'
.e((string) json_encode($record->payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE))
.'</pre>'
)),
Action::make('redeliver')
->label(__('panel.webhooks.deliveries.redeliver'))
->icon('heroicon-o-arrow-path')
->requiresConfirmation()
->authorize(fn () => $this->getOwnerRecord() && auth()->user()?->can('update', $this->getOwnerRecord()))
->action(function (WebhookDelivery $record): void {
Webhooks::redeliver($record);
Notification::make()->title(__('panel.webhooks.deliveries.redelivered'))->success()->send();
}),
]);
}
}

View File

@@ -0,0 +1,229 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\Webhooks;
use App\Filament\Resources\Webhooks\Pages\CreateWebhook;
use App\Filament\Resources\Webhooks\Pages\EditWebhook;
use App\Filament\Resources\Webhooks\Pages\ListWebhooks;
use App\Filament\Resources\Webhooks\RelationManagers\DeliveriesRelationManager;
use App\Models\Webhook;
use App\Rules\PublicHttpsUrl;
use App\Support\Webhooks\Webhooks;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Str;
use UnitEnum;
/**
* Outgoing webhooks: where to tell when something happens here, and how each
* delivery went.
*/
class WebhookResource extends Resource
{
protected static ?string $model = Webhook::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBolt;
protected static ?int $navigationSort = 85;
protected static ?string $recordTitleAttribute = 'name';
public static function getModelLabel(): string
{
return __('panel.webhooks.label');
}
public static function getPluralModelLabel(): string
{
return __('panel.webhooks.plural');
}
public static function getNavigationGroup(): string|UnitEnum|null
{
return __('panel.groups.administration');
}
/**
* Red while one is switched off by failures: something is not hearing
* what it signed up for.
*/
public static function getNavigationBadge(): ?string
{
$off = static::getModel()::query()
->where('is_active', false)
->where('consecutive_failures', '>=', Webhook::MAX_FAILURES)
->count();
return $off > 0 ? (string) $off : null;
}
public static function getNavigationBadgeColor(): ?string
{
return 'danger';
}
public static function form(Schema $schema): Schema
{
return $schema->components([
Section::make()
->columns(2)
->schema([
TextInput::make('name')
->label(__('panel.webhooks.fields.name'))
->required()
->maxLength(120),
TextInput::make('url')
->label(__('panel.webhooks.fields.url'))
->helperText(__('panel.webhooks.fields.url_hint'))
->required()
->url()
->maxLength(2048)
->rule(new PublicHttpsUrl),
CheckboxList::make('events')
->label(__('panel.webhooks.fields.events'))
->options(fn () => collect(['*', ...Webhook::EVENTS])
->mapWithKeys(fn (string $event) => [$event => self::eventLabel($event)])
->all())
->descriptions(fn () => collect(['*', ...Webhook::EVENTS])
->mapWithKeys(fn (string $event) => [$event => $event])
->all())
->required()
->columns(2)
->columnSpanFull(),
Toggle::make('include_personal_data')
->label(__('panel.webhooks.fields.include_personal_data'))
->helperText(__('panel.webhooks.fields.include_personal_data_hint')),
Toggle::make('is_active')
->label(__('panel.webhooks.fields.is_active'))
->default(true),
]),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')
->label(__('panel.webhooks.fields.name'))
->weight('bold')
->description(fn (Webhook $record) => $record->url)
->searchable(),
TextColumn::make('events')
->label(__('panel.webhooks.fields.events'))
->badge()
->color('gray'),
IconColumn::make('is_active')
->label(__('panel.webhooks.fields.is_active'))
->boolean(),
TextColumn::make('consecutive_failures')
->label(__('panel.webhooks.fields.failures'))
->color(fn (int $state) => $state > 0 ? 'danger' : 'gray'),
TextColumn::make('last_delivered_at')
->label(__('panel.webhooks.fields.last_delivered_at'))
->since()
->dateTimeTooltip()
->placeholder('—'),
])
->recordActions([
self::pingAction(),
EditAction::make(),
DeleteAction::make(),
]);
}
public static function eventLabel(string $event): string
{
$key = str_replace('.', '_', $event);
return __("panel.webhooks.events.{$key}");
}
public static function pingAction(): Action
{
return Action::make('ping')
->label(__('panel.webhooks.actions.ping'))
->icon('heroicon-o-paper-airplane')
->color('gray')
->authorize('update')
->action(function (Webhook $record): void {
Webhooks::ping($record);
Notification::make()
->title(__('panel.webhooks.actions.ping_sent'))
->body(__('panel.webhooks.actions.ping_hint'))
->success()
->send();
});
}
/**
* A new secret, shown once. The old one stops being valid at once, so the
* receiving end has to be updated straight after.
*/
public static function rotateAction(): Action
{
return Action::make('rotate_secret')
->label(__('panel.webhooks.actions.rotate'))
->icon('heroicon-o-key')
->color('warning')
->requiresConfirmation()
->modalDescription(__('panel.webhooks.actions.rotate_hint'))
->authorize('update')
->action(function (Webhook $record): void {
$secret = Str::random(40);
$record->forceFill(['secret' => $secret])->save();
self::showSecret($secret);
});
}
public static function showSecret(string $secret): void
{
Notification::make()
->title(__('panel.webhooks.secret.title'))
->body(__('panel.webhooks.secret.body', ['secret' => $secret]))
->warning()
->persistent()
->send();
}
public static function getRelations(): array
{
return [
DeliveriesRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => ListWebhooks::route('/'),
'create' => CreateWebhook::route('/create'),
'edit' => EditWebhook::route('/{record}/edit'),
];
}
}

View File

@@ -8,9 +8,9 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\WebhookRequest;
use App\Http\Resources\WebhookDeliveryResource;
use App\Http\Resources\WebhookResource;
use App\Jobs\DeliverWebhook;
use App\Models\Webhook;
use App\Models\WebhookDelivery;
use App\Support\Webhooks\Webhooks;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
@@ -115,15 +115,9 @@ class WebhookController extends Controller
{
$this->authorize('update', $webhook);
$delivery = $webhook->deliveries()->create([
'uuid' => (string) Str::uuid(),
'event' => 'ping',
'payload' => ['webhook' => $webhook->id, 'events' => $webhook->events],
]);
$delivery = Webhooks::ping($webhook);
DeliverWebhook::dispatch($delivery);
return WebhookDeliveryResource::make($delivery->refresh())->response()->setStatusCode(202);
return WebhookDeliveryResource::make($delivery)->response()->setStatusCode(202);
}
/**
@@ -133,14 +127,8 @@ class WebhookController extends Controller
{
$this->authorize('update', $delivery->webhook);
$again = $delivery->webhook->deliveries()->create([
'uuid' => (string) Str::uuid(),
'event' => $delivery->event,
'payload' => $delivery->payload,
]);
$again = Webhooks::redeliver($delivery);
DeliverWebhook::dispatch($again);
return WebhookDeliveryResource::make($again->refresh())->response()->setStatusCode(202);
return WebhookDeliveryResource::make($again)->response()->setStatusCode(202);
}
}

View File

@@ -5,8 +5,7 @@ declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use App\Models\Webhook;
use App\Support\Webhooks\PublicEndpoint;
use Closure;
use App\Rules\PublicHttpsUrl;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -34,13 +33,7 @@ class WebhookRequest extends FormRequest
'max:2048',
// Refused now rather than at the first delivery; checked
// again at every delivery all the same.
function (string $attribute, mixed $value, Closure $fail): void {
[, $reason] = app(PublicEndpoint::class)->check((string) $value);
if ($reason !== null) {
$fail(__("rules.media.remote.{$reason}"));
}
},
new PublicHttpsUrl,
],
'events' => [$sometimes, 'array', 'min:1'],
'events.*' => ['string', 'distinct', Rule::in(['*', ...Webhook::EVENTS])],

View File

@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Rules;
use App\Support\Webhooks\PublicEndpoint;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
/**
* An HTTPS address whose host resolves only to public addresses — somewhere
* this server may send a request to without reaching into its own network.
*/
class PublicHttpsUrl implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
[, $reason] = app(PublicEndpoint::class)->check((string) $value);
if ($reason !== null) {
$fail(__("rules.media.remote.{$reason}"));
}
}
}

View File

@@ -9,6 +9,7 @@ use App\Models\Application;
use App\Models\ReviewComment;
use App\Models\Revision;
use App\Models\Webhook;
use App\Models\WebhookDelivery;
use App\Support\AdminContent;
use App\Support\ContentTypes;
use App\Support\SiteUrls;
@@ -43,6 +44,38 @@ final class Webhooks
}
}
/**
* A `ping`, to check the receiving end before anything real happens.
*/
public static function ping(Webhook $webhook): WebhookDelivery
{
$delivery = $webhook->deliveries()->create([
'uuid' => (string) Str::uuid(),
'event' => 'ping',
'payload' => ['webhook' => $webhook->id, 'events' => $webhook->events],
]);
DeliverWebhook::dispatch($delivery);
return $delivery->refresh();
}
/**
* One sent again, as a new delivery of the same event and payload.
*/
public static function redeliver(WebhookDelivery $delivery): WebhookDelivery
{
$again = $delivery->webhook->deliveries()->create([
'uuid' => (string) Str::uuid(),
'event' => $delivery->event,
'payload' => $delivery->payload,
]);
DeliverWebhook::dispatch($again);
return $again->refresh();
}
public static function applicationReceived(Application $application): void
{
self::dispatch('application.received', [