diff --git a/README.md b/README.md index 26f34161..cdf4d20c 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,47 @@ GET /projects/{project}/items/{item}/ai /projects/1-bugs/items/2-bug-in-sites-overview/ai?format=yml&include[comments]=1 ``` +## Read API and webhooks + +### Read API + +Create an API token in the admin panel under **Manage > API tokens** (not tied to a user, shown only once) and send it as `Authorization: Bearer `. Private projects, items and comments are included. + +``` +GET /api/v1/projects +GET /api/v1/items?project_id=1 +GET /api/v1/comments?item_id=1 +``` + +| Parameter | Description | +|---|---| +| `updated_since` | Only records updated at or after this date, e.g. `2026-01-01T00:00:00Z` | +| `per_page` | 1-100, defaults to 50 | +| `page` | Page number; responses include `data`, `links` and `meta` | + +Deleted records are not listed, use the `*.deleted` webhooks for those. `updated_since` accepts a time zone offset. Responses are always JSON. + +### Webhooks + +Admins manage webhooks in the admin panel under **Manage > Webhooks**: a URL, a secret and the events to receive. The URL must use `https` and resolve to a public address, redirects are not followed. + +| Event | Sent when | +|---|---| +| `item.created` | an item is created | +| `item.updated` | an item is changed | +| `item.status_changed` | an item moves to another board (adds `previous_board_id`) | +| `item.deleted` | an item is deleted | +| `comment.created` | a comment is placed | +| `comment.updated` | the content or visibility of a comment is changed | +| `comment.deleted` | a comment is deleted | +| `project.created` | a project is created | +| `project.updated` | a project is changed | +| `project.deleted` | a project is deleted | + +Requests are `POST` with a JSON body `{"event", "delivery_id", "created_at", "data"}`, where `data` has the same shape as the API resources. `created_at` is the time the event happened. Changes to the vote count alone do not send `item.updated`. Comments that are removed together with their item or user do not send `comment.deleted`, use `item.deleted` for that. Requests are sent through the queue (make sure a worker is running, with `QUEUE_CONNECTION=sync` they are sent after the response and failures are only logged) and retried up to 5 times with increasing delays when the endpoint does not answer with a 2xx status. + +Verify a request by computing `sha256=` + `HMAC_SHA256(secret, X-Roadmap-Timestamp + "." + raw body)` and comparing it with the `X-Roadmap-Signature` header. Reject requests with an old timestamp to prevent replays. + ## Docker Support ### Getting up and running... diff --git a/app/Enums/WebhookEvent.php b/app/Enums/WebhookEvent.php new file mode 100644 index 00000000..d32cc2ca --- /dev/null +++ b/app/Enums/WebhookEvent.php @@ -0,0 +1,25 @@ + + */ + public static function options(): array + { + return collect(self::cases())->mapWithKeys(fn (self $event) => [$event->value => $event->value])->all(); + } +} diff --git a/app/Filament/Resources/ApiTokens/ApiTokenResource.php b/app/Filament/Resources/ApiTokens/ApiTokenResource.php new file mode 100644 index 00000000..7ec1d99a --- /dev/null +++ b/app/Filament/Resources/ApiTokens/ApiTokenResource.php @@ -0,0 +1,89 @@ +components([ + TextInput::make('name') + ->label(trans('resources.api-token.name')) + ->maxLength(255) + ->required(), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->columns([ + TextColumn::make('name') + ->label(trans('resources.api-token.name')) + ->searchable(), + TextColumn::make('last_used_at') + ->label(trans('resources.api-token.last-used-at')) + ->since() + ->placeholder('-'), + TextColumn::make('created_at') + ->label(trans('resources.created-at')) + ->dateTime(), + ]) + ->recordActions([ + DeleteAction::make(), + ]) + ->toolbarActions([ + DeleteBulkAction::make(), + ]); + } + + public static function getPages(): array + { + return [ + 'index' => ListApiTokens::route('/'), + 'create' => CreateApiToken::route('/create'), + ]; + } +} diff --git a/app/Filament/Resources/ApiTokens/Pages/CreateApiToken.php b/app/Filament/Resources/ApiTokens/Pages/CreateApiToken.php new file mode 100644 index 00000000..12675195 --- /dev/null +++ b/app/Filament/Resources/ApiTokens/Pages/CreateApiToken.php @@ -0,0 +1,38 @@ +title(trans('resources.api-token.created-title')) + ->body(trans('resources.api-token.created-body', ['token' => $plainTextToken])) + ->success() + ->persistent() + ->send(); + + return $token; + } + + protected function getCreatedNotification(): ?Notification + { + return null; + } + + protected function getRedirectUrl(): string + { + return static::getResource()::getUrl('index'); + } +} diff --git a/app/Filament/Resources/ApiTokens/Pages/ListApiTokens.php b/app/Filament/Resources/ApiTokens/Pages/ListApiTokens.php new file mode 100644 index 00000000..a27cdca0 --- /dev/null +++ b/app/Filament/Resources/ApiTokens/Pages/ListApiTokens.php @@ -0,0 +1,19 @@ +record->secret; + + return $data; + } + + protected function getHeaderActions(): array + { + return [ + DeleteAction::make(), + ]; + } +} diff --git a/app/Filament/Resources/Webhooks/Pages/ListWebhooks.php b/app/Filament/Resources/Webhooks/Pages/ListWebhooks.php new file mode 100644 index 00000000..479e24ab --- /dev/null +++ b/app/Filament/Resources/Webhooks/Pages/ListWebhooks.php @@ -0,0 +1,19 @@ +components([ + Section::make() + ->columnSpanFull() + ->schema([ + TextInput::make('url') + ->label(trans('resources.webhook.url')) + ->url() + ->rule(new SafeWebhookUrl()) + ->maxLength(2048) + ->required(), + + TextInput::make('secret') + ->label(trans('resources.webhook.secret')) + ->helperText(trans('resources.webhook.secret-helper-text')) + ->password() + ->revealable() + ->default(fn () => Str::random(40)) + ->required(), + + CheckboxList::make('events') + ->label(trans('resources.webhook.events')) + ->options(WebhookEvent::options()) + ->required(), + + Toggle::make('active') + ->label(trans('resources.webhook.active')) + ->default(true), + ]), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->columns([ + TextColumn::make('url') + ->label(trans('resources.webhook.url')) + ->searchable(), + TextColumn::make('events') + ->label(trans('resources.webhook.events')) + ->badge(), + IconColumn::make('active') + ->label(trans('resources.webhook.active')) + ->boolean(), + ]) + ->recordActions([ + EditAction::make(), + DeleteAction::make(), + ]) + ->toolbarActions([ + DeleteBulkAction::make(), + ]); + } + + public static function getPages(): array + { + return [ + 'index' => ListWebhooks::route('/'), + 'create' => CreateWebhook::route('/create'), + 'edit' => EditWebhook::route('/{record}/edit'), + ]; + } +} diff --git a/app/Http/Controllers/Api/V1/CommentController.php b/app/Http/Controllers/Api/V1/CommentController.php new file mode 100644 index 00000000..8c87c48e --- /dev/null +++ b/app/Http/Controllers/Api/V1/CommentController.php @@ -0,0 +1,30 @@ +validate([ + 'updated_since' => ['nullable', 'date'], + 'item_id' => ['nullable', 'integer'], + 'per_page' => ['nullable', 'integer', 'min:1', 'max:100'], + ]); + + return CommentResource::collection( + Comment::query() + ->when($request->date('updated_since')?->setTimezone(config('app.timezone')), fn ($query, $since) => $query->where('updated_at', '>=', $since)) + ->when($request->integer('item_id'), fn ($query, $itemId) => $query->where('item_id', $itemId)) + ->orderBy('id') + ->paginate($request->integer('per_page') ?: 50) + ->withQueryString() + ); + } +} diff --git a/app/Http/Controllers/Api/V1/ItemController.php b/app/Http/Controllers/Api/V1/ItemController.php new file mode 100644 index 00000000..b2521e92 --- /dev/null +++ b/app/Http/Controllers/Api/V1/ItemController.php @@ -0,0 +1,31 @@ +validate([ + 'updated_since' => ['nullable', 'date'], + 'project_id' => ['nullable', 'integer'], + 'per_page' => ['nullable', 'integer', 'min:1', 'max:100'], + ]); + + return ItemResource::collection( + Item::query() + ->with(['board', 'project']) + ->when($request->date('updated_since')?->setTimezone(config('app.timezone')), fn ($query, $since) => $query->where('updated_at', '>=', $since)) + ->when($request->integer('project_id'), fn ($query, $projectId) => $query->where('project_id', $projectId)) + ->orderBy('id') + ->paginate($request->integer('per_page') ?: 50) + ->withQueryString() + ); + } +} diff --git a/app/Http/Controllers/Api/V1/ProjectController.php b/app/Http/Controllers/Api/V1/ProjectController.php new file mode 100644 index 00000000..e3f07fdb --- /dev/null +++ b/app/Http/Controllers/Api/V1/ProjectController.php @@ -0,0 +1,28 @@ +validate([ + 'updated_since' => ['nullable', 'date'], + 'per_page' => ['nullable', 'integer', 'min:1', 'max:100'], + ]); + + return ProjectResource::collection( + Project::query() + ->when($request->date('updated_since')?->setTimezone(config('app.timezone')), fn ($query, $since) => $query->where('updated_at', '>=', $since)) + ->orderBy('id') + ->paginate($request->integer('per_page') ?: 50) + ->withQueryString() + ); + } +} diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 4dc60a2d..df4d25e5 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -3,6 +3,8 @@ namespace App\Http; use App\Http\Middleware\Localize; +use App\Http\Middleware\ForceJsonResponse; +use App\Http\Middleware\AuthenticateApiToken; use App\Http\Middleware\TrimStrings; use App\Http\Middleware\Authenticate; use App\Http\Middleware\TrustProxies; @@ -85,6 +87,8 @@ class Kernel extends HttpKernel * @var array */ protected $middlewareAliases = [ + 'api.json' => ForceJsonResponse::class, + 'api.token' => AuthenticateApiToken::class, 'auth' => Authenticate::class, 'auth.basic' => AuthenticateWithBasicAuth::class, 'auth.session' => AuthenticateSession::class, diff --git a/app/Http/Middleware/AuthenticateApiToken.php b/app/Http/Middleware/AuthenticateApiToken.php new file mode 100644 index 00000000..b09935aa --- /dev/null +++ b/app/Http/Middleware/AuthenticateApiToken.php @@ -0,0 +1,31 @@ +bearerToken(); + $token = $plainTextToken ? ApiToken::findByPlainTextToken($plainTextToken) : null; + + abort_unless($token, 401, 'Unauthenticated.'); + + // Avoid a write on every request. + if (! $token->last_used_at || $token->last_used_at->lt(now()->subMinute())) { + $token->forceFill(['last_used_at' => now()])->saveQuietly(); + } + + return $next($request); + } +} diff --git a/app/Http/Middleware/ForceJsonResponse.php b/app/Http/Middleware/ForceJsonResponse.php new file mode 100644 index 00000000..2b357330 --- /dev/null +++ b/app/Http/Middleware/ForceJsonResponse.php @@ -0,0 +1,22 @@ +headers->set('Accept', 'application/json'); + + return $next($request); + } +} diff --git a/app/Http/Resources/Api/V1/CommentResource.php b/app/Http/Resources/Api/V1/CommentResource.php new file mode 100644 index 00000000..143c6d62 --- /dev/null +++ b/app/Http/Resources/Api/V1/CommentResource.php @@ -0,0 +1,28 @@ + + */ + public function toArray(Request $request): array + { + return [ + 'id' => $this->id, + 'item_id' => $this->item_id, + 'parent_id' => $this->parent_id, + 'user_id' => $this->user_id, + 'content' => $this->content, + 'private' => (bool) $this->private, + 'total_votes' => (int) $this->total_votes, + 'created_at' => $this->created_at?->toIso8601String(), + 'updated_at' => $this->updated_at?->toIso8601String(), + ]; + } +} diff --git a/app/Http/Resources/Api/V1/ItemResource.php b/app/Http/Resources/Api/V1/ItemResource.php new file mode 100644 index 00000000..e502e26d --- /dev/null +++ b/app/Http/Resources/Api/V1/ItemResource.php @@ -0,0 +1,36 @@ + + */ + public function toArray(Request $request): array + { + return [ + 'id' => $this->id, + 'slug' => $this->slug, + 'title' => $this->title, + 'content' => $this->content, + 'project_id' => $this->project_id, + 'board_id' => $this->board_id, + 'status' => $this->board?->title, + 'user_id' => $this->user_id, + 'private' => (bool) $this->private, + 'pinned' => (bool) $this->pinned, + 'total_votes' => (int) $this->total_votes, + 'issue_number' => $this->issue_number, + 'url' => $this->view_url, + 'created_at' => $this->created_at?->toIso8601String(), + 'updated_at' => $this->updated_at?->toIso8601String(), + ]; + } +} diff --git a/app/Http/Resources/Api/V1/ProjectResource.php b/app/Http/Resources/Api/V1/ProjectResource.php new file mode 100644 index 00000000..de5ca513 --- /dev/null +++ b/app/Http/Resources/Api/V1/ProjectResource.php @@ -0,0 +1,30 @@ + + */ + public function toArray(Request $request): array + { + return [ + 'id' => $this->id, + 'slug' => $this->slug, + 'title' => $this->title, + 'group' => $this->group, + 'description' => $this->description, + 'url' => $this->url, + 'repo' => $this->repo, + 'private' => (bool) $this->private, + 'sort_order' => $this->sort_order, + 'created_at' => $this->created_at?->toIso8601String(), + 'updated_at' => $this->updated_at?->toIso8601String(), + ]; + } +} diff --git a/app/Jobs/SendWebhookJob.php b/app/Jobs/SendWebhookJob.php new file mode 100644 index 00000000..826a5412 --- /dev/null +++ b/app/Jobs/SendWebhookJob.php @@ -0,0 +1,92 @@ + $data + */ + public function __construct( + public readonly WebhookEndpoint $endpoint, + public readonly string $event, + public readonly array $data, + public readonly string $deliveryId, + public readonly string $occurredAt, + ) { + } + + /** + * @return array + */ + public function backoff(): array + { + return [10, 60, 300, 900]; + } + + public function handle(): void + { + try { + $this->deliver(); + } catch (Throwable $exception) { + // Without a real queue there is no retry, and a failing endpoint must not break the request. + if (config('queue.default') !== 'sync') { + throw $exception; + } + + report($exception); + } + } + + private function deliver(): void + { + // Checked again on every attempt, DNS may have changed since the endpoint was saved. + $address = SafeWebhookUrl::resolveAddress($this->endpoint->url) + ?? throw new RuntimeException('The webhook URL is not allowed.'); + + $timestamp = time(); + $body = json_encode([ + 'event' => $this->event, + 'delivery_id' => $this->deliveryId, + 'created_at' => $this->occurredAt, + 'data' => $this->data, + ], JSON_THROW_ON_ERROR); + + // The signature covers the timestamp too, so receivers can reject replayed requests. + $signature = hash_hmac('sha256', $timestamp . '.' . $body, $this->endpoint->secret); + + $host = parse_url($this->endpoint->url, PHP_URL_HOST); + $port = parse_url($this->endpoint->url, PHP_URL_PORT) ?: 443; + + Http::withHeaders([ + 'X-Roadmap-Event' => $this->event, + 'X-Roadmap-Delivery' => $this->deliveryId, + 'X-Roadmap-Timestamp' => (string) $timestamp, + 'X-Roadmap-Signature' => 'sha256=' . $signature, + ]) + ->withBody($body, 'application/json') + ->withoutRedirecting() + // Connect to the address we just checked, so DNS rebinding cannot swap it afterwards. + ->withOptions(['curl' => [CURLOPT_RESOLVE => ["{$host}:{$port}:{$address}"]]]) + ->timeout(10) + ->post($this->endpoint->url) + ->throw(); + } +} diff --git a/app/Livewire/Header.php b/app/Livewire/Header.php index a5577314..9fe7f1aa 100644 --- a/app/Livewire/Header.php +++ b/app/Livewire/Header.php @@ -22,6 +22,7 @@ use App\Filament\Resources\Users\UserResource; use Filament\Forms\Concerns\InteractsWithForms; use Filament\Actions\Concerns\InteractsWithActions; +use Illuminate\Support\Facades\DB; class Header extends Component implements HasForms, HasActions { @@ -167,15 +168,19 @@ public function submitItemAction(): Action return redirect()->route('verification.notice'); } - $item = Item::create([ - 'title' => $data['title'], - 'content' => $data['content'], - 'project_id' => $data['project_id'] ?? null, - 'board_id' => $data['board_id'] ?? null - ]); + $item = DB::transaction(function () use ($data) { + $item = Item::create([ + 'title' => $data['title'], + 'content' => $data['content'], + 'project_id' => $data['project_id'] ?? null, + 'board_id' => $data['board_id'] ?? null + ]); - $item->user()->associate(auth()->user())->save(); - $item->toggleUpvote(); + $item->user()->associate(auth()->user())->save(); + $item->toggleUpvote(); + + return $item; + }); Notification::make('item_created') ->title('Item') diff --git a/app/Livewire/Item/Create.php b/app/Livewire/Item/Create.php index ccba6290..f8785525 100644 --- a/app/Livewire/Item/Create.php +++ b/app/Livewire/Item/Create.php @@ -14,6 +14,7 @@ use Filament\Notifications\Notification; use Filament\Forms\Components\MarkdownEditor; use Filament\Forms\Concerns\InteractsWithForms; +use Illuminate\Support\Facades\DB; class Create extends Component implements HasForms { @@ -60,15 +61,19 @@ public function submit() $formState = $this->form->getState(); - $item = Item::create([ - ...$formState, - ]); + $item = DB::transaction(function () use ($formState) { + $item = Item::create([ + ...$formState, + ]); - $item->user()->associate(auth()->user())->save(); - $item->project()->associate($this->project)->save(); - $item->board()->associate($this->board)->save(); + $item->user()->associate(auth()->user())->save(); + $item->project()->associate($this->project)->save(); + $item->board()->associate($this->board)->save(); - $item->toggleUpvote(); + $item->toggleUpvote(); + + return $item; + }); Notification::make('items') ->title('Items') diff --git a/app/Mcp/Tools/CreateItemTool.php b/app/Mcp/Tools/CreateItemTool.php index d5c12d5e..be39c37d 100644 --- a/app/Mcp/Tools/CreateItemTool.php +++ b/app/Mcp/Tools/CreateItemTool.php @@ -13,6 +13,7 @@ use Laravel\Mcp\Server\Attributes\Description; use Illuminate\Contracts\JsonSchema\JsonSchema; use App\Mcp\Tools\Concerns\InteractsWithRoadmap; +use Illuminate\Support\Facades\DB; #[Name('create-item')] #[Description('Create a new roadmap item (feature request, idea or bug), optionally on a board of a project. Admins and employees can create it as a private item, which does not send new item notifications. Available to admins and employees, and to other users when an admin allows it.')] @@ -84,16 +85,20 @@ public function handle(Request $request): Response return Response::error('A board is required, pass the board to create the item on.'); } - $item = Item::create([ - 'title' => $validated['title'], - 'content' => $validated['content'], - 'project_id' => $project?->id, - 'board_id' => $board?->id, - 'private' => $private, - ]); + $item = DB::transaction(function () use ($validated, $project, $board, $private, $user) { + $item = Item::create([ + 'title' => $validated['title'], + 'content' => $validated['content'], + 'project_id' => $project?->id, + 'board_id' => $board?->id, + 'private' => $private, + ]); + + $item->user()->associate($user)->save(); + $item->toggleUpvote($user); - $item->user()->associate($user)->save(); - $item->toggleUpvote($user); + return $item; + }); return Response::json([ 'message' => "Created \"{$item->title}\".", diff --git a/app/Models/ApiToken.php b/app/Models/ApiToken.php new file mode 100644 index 00000000..7622b7f3 --- /dev/null +++ b/app/Models/ApiToken.php @@ -0,0 +1,52 @@ + 'datetime', + ]; + } + + /** + * Only a hash is stored, so the returned plain text token can be shown once and never again. + * + * @return array{0: self, 1: string} + */ + public static function generate(string $name): array + { + $plainTextToken = 'rm_' . Str::random(40); + + return [ + static::create(['name' => $name, 'token' => static::hash($plainTextToken)]), + $plainTextToken, + ]; + } + + public static function findByPlainTextToken(string $plainTextToken): ?self + { + return static::where('token', static::hash($plainTextToken))->first(); + } + + private static function hash(string $plainTextToken): string + { + return hash('sha256', $plainTextToken); + } +} diff --git a/app/Models/WebhookEndpoint.php b/app/Models/WebhookEndpoint.php new file mode 100644 index 00000000..aa69abc2 --- /dev/null +++ b/app/Models/WebhookEndpoint.php @@ -0,0 +1,29 @@ + 'encrypted', + 'events' => 'array', + 'active' => 'boolean', + ]; + } +} diff --git a/app/Observers/CommentObserver.php b/app/Observers/CommentObserver.php index 86a00c41..b40dc057 100644 --- a/app/Observers/CommentObserver.php +++ b/app/Observers/CommentObserver.php @@ -4,6 +4,9 @@ use App\Models\User; use App\Models\Comment; +use App\Enums\WebhookEvent; +use App\Services\WebhookDispatcher; +use App\Http\Resources\Api\V1\CommentResource; use App\Services\MentionParser; use App\Notifications\CommentHasReplyNotification; use App\Notifications\Item\ItemHasNewCommentNotification; @@ -24,6 +27,8 @@ public function created(Comment $comment) { $this->processMentions($comment); + WebhookDispatcher::dispatch(WebhookEvent::CommentCreated, fn () => $this->webhookData($comment)); + $userIds = $comment->item?->votes() ->subscribed() ->where('user_id', '!=', auth()->id()) // Don't get the current user, they obviously already know about the new comment @@ -41,6 +46,23 @@ public function updated(Comment $comment) if ($comment->wasChanged('content')) { $this->processMentions($comment); } + + if ($comment->wasChanged(['content', 'private'])) { + WebhookDispatcher::dispatch(WebhookEvent::CommentUpdated, fn () => $this->webhookData($comment)); + } + } + + public function deleted(Comment $comment) + { + WebhookDispatcher::dispatch(WebhookEvent::CommentDeleted, fn () => $this->webhookData($comment)); + } + + /** + * @return array + */ + private function webhookData(Comment $comment): array + { + return (new CommentResource($comment))->resolve(); } public function deleting(Comment $comment) diff --git a/app/Observers/ItemObserver.php b/app/Observers/ItemObserver.php index 6d1817b4..5c98a7ba 100644 --- a/app/Observers/ItemObserver.php +++ b/app/Observers/ItemObserver.php @@ -4,22 +4,49 @@ use Mail; use Throwable; +use WeakMap; use App\Models\Item; use App\Models\User; use App\Models\Project; use App\Enums\ItemActivity; +use App\Enums\WebhookEvent; +use App\Services\WebhookDispatcher; +use App\Http\Resources\Api\V1\ItemResource; use App\Settings\GeneralSettings; use App\Jobs\SendWebhookForNewItemJob; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; use App\Mail\Admin\ItemHasBeenCreatedEmail; use App\Notifications\Item\ItemUpdatedNotification; class ItemObserver { + /** + * Items that are being created and not committed yet, their follow-up saves must not send `item.updated`. + * Static, because Laravel resolves a new observer instance for every model event. + * + * @var WeakMap|null + */ + private static ?WeakMap $pendingCreation = null; + + public function creating(Item $item): void + { + self::$pendingCreation ??= new WeakMap(); + self::$pendingCreation[$item] = true; + } + public function created(Item $item) { ItemActivity::createForItem($item, ItemActivity::Created); + // Creating an item takes several saves (slug, user, project, board, vote). Wrap them in a transaction + // and the webhook is sent once, with the complete item, after the commit. + DB::afterCommit(function () use ($item) { + unset(self::$pendingCreation[$item]); + + WebhookDispatcher::dispatch(WebhookEvent::ItemCreated, fn () => $this->webhookData($item->fresh())); + }); + if ($item->isPrivate()) { return; } @@ -50,6 +77,37 @@ public function created(Item $item) } } + public function deleted(Item $item): void + { + WebhookDispatcher::dispatch(WebhookEvent::ItemDeleted, fn () => $this->webhookData($item)); + } + + public function updated(Item $item): void + { + // Vote counts change on every vote, consumers can read them from the API. + $changes = array_diff_key($item->getChanges(), array_flip(['updated_at', 'notify_subscribers', 'total_votes'])); + + if ($changes === [] || isset(self::$pendingCreation[$item])) { + return; + } + + WebhookDispatcher::dispatch(WebhookEvent::ItemUpdated, fn () => $this->webhookData($item)); + + if (array_key_exists('board_id', $changes)) { + WebhookDispatcher::dispatch(WebhookEvent::ItemStatusChanged, fn () => $this->webhookData($item) + [ + 'previous_board_id' => $item->getOriginal('board_id'), + ]); + } + } + + /** + * @return array + */ + private function webhookData(Item $item): array + { + return (new ItemResource($item->load(['board', 'project'])))->resolve(); + } + public function updating(Item $item) { $isDirty = false; @@ -109,7 +167,8 @@ public function updating(Item $item) }); } - $item->updateQuietly(['notify_subscribers' => true]); + // Part of the update that is being saved. + $item->notify_subscribers = true; } public function deleting(Item $item) diff --git a/app/Observers/ProjectObserver.php b/app/Observers/ProjectObserver.php index c9f1f4cc..3c526c44 100644 --- a/app/Observers/ProjectObserver.php +++ b/app/Observers/ProjectObserver.php @@ -5,10 +5,18 @@ use Throwable; use App\Models\Board; use App\Models\Project; +use App\Enums\WebhookEvent; +use App\Services\WebhookDispatcher; +use App\Http\Resources\Api\V1\ProjectResource; use Illuminate\Support\Facades\Storage; class ProjectObserver { + public function created(Project $project): void + { + WebhookDispatcher::dispatch(WebhookEvent::ProjectCreated, fn () => $this->webhookData($project)); + } + public function updated(Project $project): void { $originalIconImage = $project->getOriginal('icon_image'); @@ -16,6 +24,28 @@ public function updated(Project $project): void if ($project->wasChanged('icon_image') && $originalIconImage) { Storage::disk('public')->delete($originalIconImage); } + + // The slug that is filled right after creation is part of `project.created`. + $changes = array_keys(array_diff_key($project->getChanges(), ['updated_at' => true])); + + if ($changes === [] || ($project->wasRecentlyCreated && $changes === ['slug'])) { + return; + } + + WebhookDispatcher::dispatch(WebhookEvent::ProjectUpdated, fn () => $this->webhookData($project)); + } + + public function deleted(Project $project): void + { + WebhookDispatcher::dispatch(WebhookEvent::ProjectDeleted, fn () => $this->webhookData($project)); + } + + /** + * @return array + */ + private function webhookData(Project $project): array + { + return (new ProjectResource($project))->resolve(); } public function deleting(Project $project) diff --git a/app/Policies/ApiTokenPolicy.php b/app/Policies/ApiTokenPolicy.php new file mode 100644 index 00000000..b2d56fad --- /dev/null +++ b/app/Policies/ApiTokenPolicy.php @@ -0,0 +1,13 @@ +isAdmin($user); + } + + public function view(User $user): bool + { + return $this->isAdmin($user); + } + + public function create(User $user): bool + { + return $this->isAdmin($user); + } + + public function update(User $user): bool + { + return $this->isAdmin($user); + } + + public function delete(User $user): bool + { + return $this->isAdmin($user); + } + + public function deleteAny(User $user): bool + { + return $this->isAdmin($user); + } + + private function isAdmin(User $user): bool + { + return $user->hasRole(UserRole::Admin); + } +} diff --git a/app/Policies/WebhookEndpointPolicy.php b/app/Policies/WebhookEndpointPolicy.php new file mode 100644 index 00000000..8bc3a2ce --- /dev/null +++ b/app/Policies/WebhookEndpointPolicy.php @@ -0,0 +1,13 @@ + $data + */ + public static function dispatch(WebhookEvent $event, Closure $data): void + { + $endpoints = WebhookEndpoint::query() + ->where('active', true) + ->get() + ->filter(fn (WebhookEndpoint $endpoint) => in_array($event->value, $endpoint->events ?? [], true)); + + if ($endpoints->isEmpty()) { + return; + } + + $payload = $data(); + $occurredAt = now()->toIso8601String(); + + $endpoints->each(function (WebhookEndpoint $endpoint) use ($event, $payload, $occurredAt) { + $pending = SendWebhookJob::dispatch($endpoint, $event->value, $payload, (string) Str::uuid(), $occurredAt); + + // On the sync queue delivery would otherwise block the user's request. + if (config('queue.default') === 'sync') { + $pending->afterResponse(); + } + }); + } +} diff --git a/database/factories/ApiTokenFactory.php b/database/factories/ApiTokenFactory.php new file mode 100644 index 00000000..f33b1d2b --- /dev/null +++ b/database/factories/ApiTokenFactory.php @@ -0,0 +1,22 @@ + + */ +class ApiTokenFactory extends Factory +{ + /** + * @return array + */ + public function definition(): array + { + return [ + 'name' => $this->faker->word(), + 'token' => hash('sha256', $this->faker->unique()->sha256()), + ]; + } +} diff --git a/database/factories/WebhookEndpointFactory.php b/database/factories/WebhookEndpointFactory.php new file mode 100644 index 00000000..b7f880cd --- /dev/null +++ b/database/factories/WebhookEndpointFactory.php @@ -0,0 +1,25 @@ + + */ +class WebhookEndpointFactory extends Factory +{ + /** + * @return array + */ + public function definition(): array + { + return [ + 'url' => 'https://1.1.1.1/hooks/roadmap', + 'secret' => $this->faker->sha256(), + 'events' => array_column(WebhookEvent::cases(), 'value'), + 'active' => true, + ]; + } +} diff --git a/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php b/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php new file mode 100644 index 00000000..357a8e97 --- /dev/null +++ b/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php @@ -0,0 +1,25 @@ +id(); + $table->string('url', 2048); + $table->text('secret'); + $table->json('events'); + $table->boolean('active')->default(true); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('webhook_endpoints'); + } +}; diff --git a/database/migrations/2026_11_02_124013_create_api_tokens_table.php b/database/migrations/2026_11_02_124013_create_api_tokens_table.php new file mode 100644 index 00000000..3d9a3367 --- /dev/null +++ b/database/migrations/2026_11_02_124013_create_api_tokens_table.php @@ -0,0 +1,24 @@ +id(); + $table->string('name'); + $table->string('token', 64)->unique(); + $table->timestamp('last_used_at')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('api_tokens'); + } +}; diff --git a/lang/en/nav.php b/lang/en/nav.php index e9259a69..6d138bd8 100644 --- a/lang/en/nav.php +++ b/lang/en/nav.php @@ -11,6 +11,8 @@ 'item' => 'Items', 'project' => 'Projects', 'tags' => 'Tags', + 'webhooks' => 'Webhooks', + 'api-tokens' => 'API tokens', 'votes' => 'Votes', 'public-view' => 'Public View', 'external' => 'External', diff --git a/lang/en/resources.php b/lang/en/resources.php index b3b89952..864c747a 100644 --- a/lang/en/resources.php +++ b/lang/en/resources.php @@ -121,6 +121,24 @@ 'name' => 'Name', 'changelog' => 'Changelog', ], + 'api-token' => [ + 'label' => 'API token', + 'label-plural' => 'API tokens', + 'name' => 'Name', + 'last-used-at' => 'Last used', + 'created-title' => 'API token created', + 'created-body' => 'Copy this token now, it will not be shown again: :token', + ], + 'webhook' => [ + 'label' => 'Webhook', + 'label-plural' => 'Webhooks', + 'url' => 'URL', + 'url-not-allowed' => 'The URL must use https and point to a public address.', + 'secret' => 'Secret', + 'secret-helper-text' => 'Used to sign every request with an HMAC SHA-256 signature in the X-Roadmap-Signature header.', + 'events' => 'Events', + 'active' => 'Active', + ], 'user' => [ 'label' => 'User', 'label-plural' => 'Users', diff --git a/routes/api.php b/routes/api.php index e165ea47..6338232e 100644 --- a/routes/api.php +++ b/routes/api.php @@ -3,6 +3,9 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\WidgetController; +use App\Http\Controllers\Api\V1\ItemController; +use App\Http\Controllers\Api\V1\CommentController; +use App\Http\Controllers\Api\V1\ProjectController; /* |-------------------------------------------------------------------------- @@ -30,3 +33,10 @@ Route::get('/config', [WidgetController::class, 'activityConfig']); Route::get('/activities', [WidgetController::class, 'activityList']); }); + +// Read API (API tokens from the admin panel) +Route::prefix('v1')->middleware(['api.json', 'api.token'])->group(function () { + Route::get('/projects', [ProjectController::class, 'index']); + Route::get('/items', [ItemController::class, 'index']); + Route::get('/comments', [CommentController::class, 'index']); +}); diff --git a/tests/Feature/Api/ReadApiTest.php b/tests/Feature/Api/ReadApiTest.php new file mode 100644 index 00000000..63224ec4 --- /dev/null +++ b/tests/Feature/Api/ReadApiTest.php @@ -0,0 +1,92 @@ +assertUnauthorized(); +}); + +it('rejects an unknown token', function () { + withToken('rm_unknown')->getJson('/api/v1/items')->assertUnauthorized(); +}); + +it('rejects user tokens', function () { + $token = createUser()->createToken('MCP')->plainTextToken; + + withToken($token)->getJson('/api/v1/items')->assertUnauthorized(); +}); + +it('records when a token was last used', function () { + [$apiToken, $plain] = ApiToken::generate('Polder'); + + withToken($plain)->getJson('/api/v1/items')->assertOk(); + + expect($apiToken->refresh()->last_used_at)->not->toBeNull(); +}); + +it('lists projects, items and comments including private ones', function () { + $project = Project::factory()->private()->create(); + $board = Board::factory()->create(['project_id' => $project->id]); + $item = Item::factory()->create(['project_id' => $project->id, 'board_id' => $board->id, 'private' => true]); + $comment = Comment::factory()->create(['item_id' => $item->id]); + + $token = apiToken(); + + withToken($token)->getJson('/api/v1/projects')->assertOk()->assertJsonPath('data.0.id', $project->id); + withToken($token)->getJson('/api/v1/items')->assertOk() + ->assertJsonPath('data.0.id', $item->id) + ->assertJsonPath('data.0.status', $board->title) + ->assertJsonPath('data.0.private', true); + withToken($token)->getJson('/api/v1/comments')->assertOk()->assertJsonPath('data.0.id', $comment->id); +}); + +it('paginates and filters on updated_since', function () { + $old = Item::factory()->create(); + $old->forceFill(['updated_at' => now()->subDays(10)])->saveQuietly(); + $new = Item::factory()->create(); + + $response = withToken(apiToken()) + ->getJson('/api/v1/items?per_page=1&updated_since=' . urlencode(now()->subDay()->toIso8601String())) + ->assertOk(); + + expect($response->json('data'))->toHaveCount(1) + ->and($response->json('data.0.id'))->toBe($new->id) + ->and($response->json('meta.total'))->toBe(1); +}); + +it('validates updated_since', function () { + withToken(apiToken())->getJson('/api/v1/items?updated_since=nope')->assertUnprocessable(); +}); + +it('converts the updated_since offset to the app timezone', function () { + $item = Item::factory()->create(); + $item->forceFill(['updated_at' => '2026-11-02 11:00:00'])->saveQuietly(); + + // 12:00+02:00 is 10:00 UTC, so an item updated at 11:00 UTC must be included. + withToken(apiToken()) + ->getJson('/api/v1/items?updated_since=' . urlencode('2026-11-02T12:00:00+02:00')) + ->assertOk() + ->assertJsonCount(1, 'data'); +}); + +it('falls back to the default page size for an empty per_page', function () { + Item::factory()->count(3)->create(); + + withToken(apiToken())->getJson('/api/v1/items?per_page=')->assertOk()->assertJsonPath('meta.per_page', 50); +}); + +it('answers with json errors without an Accept header', function () { + $this->get('/api/v1/items')->assertUnauthorized()->assertJsonPath('message', 'Unauthenticated.'); + $this->withToken(apiToken())->get('/api/v1/items?updated_since=nope')->assertUnprocessable(); +}); diff --git a/tests/Feature/Filament/ApiTokenResourceTest.php b/tests/Feature/Filament/ApiTokenResourceTest.php new file mode 100644 index 00000000..d0558203 --- /dev/null +++ b/tests/Feature/Filament/ApiTokenResourceTest.php @@ -0,0 +1,36 @@ + UserRole::Admin]); + + Livewire::test(CreateApiToken::class) + ->fillForm(['name' => 'Polder']) + ->call('create') + ->assertHasNoFormErrors() + ->assertNotified(trans('resources.api-token.created-title')); + + $token = ApiToken::first(); + + expect($token->name)->toBe('Polder') + ->and($token->getAttributes()['token'])->toHaveLength(64); +}); + +it('is not available to employees', function () { + createAndLoginUser(['role' => UserRole::Employee]); + + Livewire::test(ListApiTokens::class)->assertForbidden(); + Livewire::test(CreateApiToken::class)->assertForbidden(); +}); + +it('hides the navigation item from employees', function () { + createAndLoginUser(['role' => UserRole::Employee]); + + expect(ApiTokenResource::shouldRegisterNavigation())->toBeFalse(); +}); diff --git a/tests/Feature/Filament/WebhookResourceTest.php b/tests/Feature/Filament/WebhookResourceTest.php new file mode 100644 index 00000000..47f161bd --- /dev/null +++ b/tests/Feature/Filament/WebhookResourceTest.php @@ -0,0 +1,67 @@ + UserRole::Admin]); + + Livewire::test(CreateWebhook::class) + ->fillForm(['url' => 'https://1.1.1.1/hook', 'secret' => 'abc123', 'events' => ['item.created']]) + ->call('create') + ->assertHasNoFormErrors(); + + $endpoint = WebhookEndpoint::first(); + + expect($endpoint->url)->toBe('https://1.1.1.1/hook') + ->and($endpoint->secret)->toBe('abc123') + ->and($endpoint->events)->toBe(['item.created']); +}); + +it('requires events', function () { + createAndLoginUser(['role' => UserRole::Admin]); + + Livewire::test(CreateWebhook::class) + ->fillForm(['url' => 'https://1.1.1.1/hook', 'secret' => 'abc123', 'events' => []]) + ->call('create') + ->assertHasFormErrors(['events' => 'required']); +}); + +it('rejects urls that are not https or not public', function (string $url) { + createAndLoginUser(['role' => UserRole::Admin]); + + Livewire::test(CreateWebhook::class) + ->fillForm(['url' => $url, 'secret' => 'abc123', 'events' => ['item.created']]) + ->call('create') + ->assertHasFormErrors(['url']); +})->with(['http://1.1.1.1/hook', 'https://127.0.0.1/hook', 'https://169.254.169.254/latest', 'https://localhost/hook']); + +it('keeps the secret when an admin edits a webhook', function () { + createAndLoginUser(['role' => UserRole::Admin]); + $endpoint = WebhookEndpoint::factory()->create(['secret' => 'abc123']); + + Livewire::test(EditWebhook::class, ['record' => $endpoint->getKey()]) + ->assertSchemaStateSet(['secret' => 'abc123']) + ->fillForm(['active' => false]) + ->call('save') + ->assertHasNoFormErrors(); + + expect($endpoint->refresh()->active)->toBeFalse()->and($endpoint->secret)->toBe('abc123'); +}); + +it('is not available to employees', function () { + createAndLoginUser(['role' => UserRole::Employee]); + + Livewire::test(ListWebhooks::class)->assertForbidden(); +}); + +it('hides the navigation item from employees', function () { + createAndLoginUser(['role' => UserRole::Employee]); + + expect(WebhookResource::shouldRegisterNavigation())->toBeFalse(); +}); diff --git a/tests/Feature/Webhooks/WebhookDeliveryTest.php b/tests/Feature/Webhooks/WebhookDeliveryTest.php new file mode 100644 index 00000000..7b1995f3 --- /dev/null +++ b/tests/Feature/Webhooks/WebhookDeliveryTest.php @@ -0,0 +1,178 @@ +event; + + return true; + }); + + return $events; +} + +it('queues the events an endpoint subscribed to', function () { + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(['events' => ['item.created', 'item.deleted']]); + + $item = Item::factory()->create(); + $item->update(['title' => 'Changed']); + $item->delete(); + + expect(dispatchedEvents())->toBe(['item.created', 'item.deleted']); +}); + +it('does not queue anything for inactive endpoints', function () { + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(['active' => false]); + + Item::factory()->create(); + + Bus::assertNotDispatched(SendWebhookJob::class); +}); + +it('queues update, status change, comment and project events', function () { + $project = Project::factory()->create(); + $board = Board::factory()->create(['project_id' => $project->id]); + $item = Item::factory()->create(['project_id' => $project->id]); + + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(); + + $item->update(['board_id' => $board->id]); + Comment::factory()->create(['item_id' => $item->id]); + $project->update(['title' => 'Renamed']); + + expect(dispatchedEvents())->toEqualCanonicalizing([ + 'item.updated', 'item.status_changed', 'comment.created', 'project.updated', + ]); + + Bus::assertDispatched( + SendWebhookJob::class, + fn (SendWebhookJob $job) => $job->event === 'item.status_changed' && $job->data['board_id'] === $board->id + ); +}); + +it('sends a signed request and retries with backoff', function () { + Http::fake(['1.1.1.1/*' => Http::response('', 200)]); + $endpoint = WebhookEndpoint::factory()->create(['secret' => 'top-secret']); + + $job = new SendWebhookJob($endpoint, WebhookEvent::ItemCreated->value, ['id' => 1], 'delivery-1', now()->toIso8601String()); + $job->handle(); + + Http::assertSent(function ($request) { + $expected = 'sha256=' . hash_hmac('sha256', $request->header('X-Roadmap-Timestamp')[0] . '.' . $request->body(), 'top-secret'); + + return $request->header('X-Roadmap-Signature')[0] === $expected + && $request->header('X-Roadmap-Event')[0] === 'item.created' + && $request['data'] === ['id' => 1]; + }); + + expect($job->tries)->toBe(5)->and($job->backoff())->toHaveCount(4); +}); + +it('fails the job on a non-2xx response so it is retried', function () { + Http::fake(['1.1.1.1/*' => Http::response('', 500)]); + $endpoint = WebhookEndpoint::factory()->create(); + + config(['queue.default' => 'database']); + + (new SendWebhookJob($endpoint, 'item.created', [], 'delivery-1', now()->toIso8601String()))->handle(); +})->throws(Illuminate\Http\Client\RequestException::class); + +it('does not call addresses that are not public', function () { + Http::fake(); + config(['queue.default' => 'database']); + + foreach (['https://127.0.0.1/hook', 'https://169.254.169.254/latest', 'http://1.1.1.1/hook'] as $url) { + $endpoint = WebhookEndpoint::factory()->create(['url' => $url]); + + expect(fn () => (new SendWebhookJob($endpoint, 'item.created', [], 'd', now()->toIso8601String()))->handle()) + ->toThrow(RuntimeException::class); + } + + Http::assertNothingSent(); +}); + +it('does not let a failing endpoint break the request on the sync queue', function () { + Http::fake(['1.1.1.1/*' => Http::response('', 500)]); + $endpoint = WebhookEndpoint::factory()->create(); + + (new SendWebhookJob($endpoint, 'item.created', [], 'd', now()->toIso8601String()))->handle(); + + Http::assertSentCount(1); +}); + +it('sends one complete item.created for an item that is created in a transaction', function () { + $project = Project::factory()->create(); + $board = Board::factory()->create(['project_id' => $project->id]); + $user = createUser(); + + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(); + + DB::transaction(function () use ($project, $board, $user) { + $item = Item::create(['title' => 'Idea', 'content' => 'Content']); + $item->user()->associate($user)->save(); + $item->project()->associate($project)->save(); + $item->board()->associate($board)->save(); + $item->toggleUpvote($user); + }); + + expect(dispatchedEvents())->toBe(['item.created']); + + Bus::assertDispatched(SendWebhookJob::class, fn (SendWebhookJob $job) => $job->data['user_id'] === $user->id + && $job->data['project_id'] === $project->id + && $job->data['board_id'] === $board->id + && $job->data['total_votes'] === 1); +}); + +it('does not send item.updated for vote count changes', function () { + $item = Item::factory()->create(); + + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(); + + $item->toggleUpvote(createUser()); + + Bus::assertNotDispatched(SendWebhookJob::class); +}); + +it('sends the comment as stored, after mentions are linked', function () { + $jane = createUser(['username' => 'jane']); + + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(['events' => ['comment.created']]); + + $comment = Comment::factory()->create(['content' => 'thanks @jane']); + + Bus::assertDispatched(SendWebhookJob::class, fn (SendWebhookJob $job) => $job->data['content'] === $comment->fresh()->content); +}); + +it('sends project and comment lifecycle events', function () { + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(); + + $project = Project::factory()->create(); + $comment = Comment::factory()->create(); + $comment->update(['content' => 'Edited']); + $comment->delete(); + $project->delete(); + + expect(dispatchedEvents())->toEqualCanonicalizing([ + 'project.created', 'comment.created', 'comment.updated', 'comment.deleted', 'project.deleted', + ]); +});