Manage technologies through the API, with SVG logos
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

/api/v1/technologies is a full CRUD with the panel's own rules: name and
slug are plain strings, the prose is translatable, `radar_ring: null`
takes one off the radar, and TechnologyPolicy still refuses to delete
one a project, member or call uses. The MCP server picks the tools up
from openapi.yaml on its own.

A logo is an SVG, so POST /v1/media now accepts one — sanitized with
enshrined/svg-sanitize (scripts, event handlers and remote references
removed), and served by Caddy under a Content-Security-Policy that
would stop a script regardless. `for` (pages or technologies) says what
an upload is for, which picks the directory the panel uses for it and
the permission it takes.

Creating a technology without a category answered 500: the column's
default never reached the model, so the response read a null enum. The
controller now states the default, as the panel does.

Beside a file, the MCP upload tool no longer demands the JSON body's
`url`: the body then carries the upload's other fields, such as `for`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-28 19:49:00 +02:00
parent a49816eb46
commit ac546eba2b
21 changed files with 789 additions and 38 deletions

View File

@@ -9,6 +9,7 @@ use App\Http\Requests\Api\V1\MediaRequest;
use App\Http\Resources\MediaResource;
use App\Models\Media;
use App\Services\Media\RemoteImage;
use enshrined\svgSanitize\Sanitizer;
use finfo;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
@@ -40,11 +41,14 @@ class MediaController extends Controller
'image/webp' => 'webp',
'image/gif' => 'gif',
'image/avif' => 'avif',
'image/svg+xml' => 'svg',
];
public function store(MediaRequest $request, RemoteImage $remote): JsonResponse
{
$this->authorize('upload', Media::class);
$for = (string) $request->input('for', 'pages');
$this->authorize('upload', [Media::class, $for]);
$field = $request->hasFile('file') ? 'file' : 'url';
@@ -53,16 +57,22 @@ class MediaController extends Controller
: $remote->fetch((string) $request->string('url'));
$mime = (new finfo(FILEINFO_MIME_TYPE))->buffer($contents) ?: null;
$size = @getimagesizefromstring($contents);
// Both, because each catches what the other misses: the type is read
// from the magic bytes, and a file that has them but does not decode
// is not an image anybody can render.
if ($size === false || ! in_array($mime, (array) config('media.upload.mimes'), true)) {
throw ValidationException::withMessages([$field => [__('rules.media.not_an_image')]]);
if (! in_array($mime, (array) config('media.upload.mimes'), true)) {
$this->refuse($field);
}
$path = config('media.upload.directory').'/'.Str::random(40).'.'.self::EXTENSIONS[$mime];
if ($mime === 'image/svg+xml') {
$contents = $this->sanitize($contents) ?? $this->refuse($field);
// A vector has no pixel size; the processor copies it through.
$size = [null, null];
} else {
// The type is read from the magic bytes; this catches a file that
// has them but does not decode, which nobody could render either.
$size = @getimagesizefromstring($contents) ?: $this->refuse($field);
}
$path = config("media.upload.for.{$for}").'/'.Str::random(40).'.'.self::EXTENSIONS[$mime];
Storage::disk((string) config('media.disk'))->put($path, $contents);
@@ -82,4 +92,24 @@ class MediaController extends Controller
return MediaResource::make($media->fresh())->response()->setStatusCode(201);
}
/**
* An SVG with what could run taken out: scripts, event handlers, and
* references to anything outside the file. Null when what is left is not
* an SVG at all.
*/
protected function sanitize(string $svg): ?string
{
$sanitizer = new Sanitizer;
$sanitizer->removeRemoteReferences(true);
$clean = $sanitizer->sanitize($svg);
return is_string($clean) && str_contains($clean, '<svg') ? $clean : null;
}
protected function refuse(string $field): never
{
throw ValidationException::withMessages([$field => [__('rules.media.not_an_image')]]);
}
}

View File

@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Enums\TechnologyCategory;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\TechnologyRequest;
use App\Http\Resources\TechnologyResource;
use App\Models\Technology;
use App\Support\TranslatablePayload;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
/**
* The technologies the collective uses, and their place on the radar.
*
* Same rules as the panel: TechnologyPolicy refuses to delete one a project,
* member or call still points at.
*/
class TechnologyController extends Controller
{
/**
* Filters: category, radar_ring (`none` for those off the radar), search.
*/
public function index(Request $request): AnonymousResourceCollection
{
$this->authorize('viewAny', Technology::class);
$technologies = Technology::query()
->with('logoMedia')
->withCount('projects')
->when($request->filled('category'), fn ($q) => $q->where('category', $request->string('category')))
->when($request->filled('radar_ring'), fn ($q) => $request->string('radar_ring')->toString() === 'none'
? $q->whereNull('radar_ring')
: $q->where('radar_ring', $request->string('radar_ring')))
->when($request->filled('search'), fn ($q) => $q->where('name', 'like', '%'.$request->string('search').'%'))
->orderBy('position')
->orderBy('name')
->paginate(perPage: min($request->integer('per_page', 25), 100))
->withQueryString();
return TechnologyResource::collection($technologies);
}
public function store(TechnologyRequest $request): JsonResponse
{
$this->authorize('create', Technology::class);
$technology = new Technology;
$technology->fill(TranslatablePayload::merge($technology, $request->validated(), $technology->translatable));
// The column's default, and the panel's, stated here so the model
// knows it too: otherwise the answer to a create without a category
// would be missing the one the row was given.
$technology->category ??= TechnologyCategory::Tool;
$technology->save();
return TechnologyResource::make($this->loaded($technology))->response()->setStatusCode(201);
}
public function show(Technology $technology): TechnologyResource
{
$this->authorize('view', $technology);
return TechnologyResource::make($this->loaded($technology));
}
public function update(TechnologyRequest $request, Technology $technology): TechnologyResource
{
$this->authorize('update', $technology);
$technology->fill(TranslatablePayload::merge($technology, $request->validated(), $technology->translatable));
$technology->save();
return TechnologyResource::make($this->loaded($technology));
}
public function destroy(Technology $technology): JsonResponse
{
$this->authorize('delete', $technology);
$technology->delete();
return response()->json(status: 204);
}
protected function loaded(Technology $technology): Technology
{
return $technology->load('logoMedia')->loadCount('projects');
}
}

View File

@@ -40,6 +40,7 @@ class MediaRequest extends FormRequest
'mimetypes:'.implode(',', (array) config('media.upload.mimes')),
],
'url' => ['required_without:file', 'string', 'url:https', 'max:2048'],
'for' => ['sometimes', 'string', 'in:'.implode(',', array_keys((array) config('media.upload.for')))],
];
}
}

View File

@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use App\Enums\RadarRing;
use App\Enums\TechnologyCategory;
use App\Models\Technology;
use App\Rules\Translatable;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
/**
* The panel's technology form, as rules. On update every field is optional
* (PATCH semantics) but keeps the same shape.
*
* `name` and `slug` are plain strings: a technology's name is a proper noun,
* the same in every language. Only the prose about it is translatable.
*/
class TechnologyRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
$technology = $this->route('technology');
$creating = ! $technology instanceof Technology;
$sometimes = $creating ? 'required' : 'sometimes';
return [
'name' => [$sometimes, 'string', 'max:120'],
'slug' => [
$sometimes,
'string',
'max:120',
'alpha_dash:ascii',
Rule::unique('technologies', 'slug')->ignore($technology?->id),
],
'description' => ['sometimes', 'nullable', new Translatable(max: 1000)],
'radar_note' => ['sometimes', 'nullable', new Translatable(max: 1000)],
'category' => ['sometimes', Rule::enum(TechnologyCategory::class)],
// Null keeps it off the radar while projects can still be tagged with it.
'radar_ring' => ['sometimes', 'nullable', Rule::enum(RadarRing::class)],
'color' => ['sometimes', 'nullable', 'string', 'regex:/^#[0-9a-fA-F]{6}$/'],
'logo' => ['sometimes', 'nullable', 'string', 'max:255'],
// 255, not the panel's 2048: that is the column's width.
'website' => ['sometimes', 'nullable', 'url', 'max:255'],
'position' => ['sometimes', 'integer', 'min:0'],
];
}
}

View File

@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources;
use App\Models\Technology;
use App\Support\ImagePayload;
use App\Support\TranslatablePayload;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin Technology
*/
class TechnologyResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
$locale = $request->query(config('locales.query_parameter')) ?? app()->getLocale();
return [
'id' => $this->id,
'locale' => $locale,
'name' => $this->name,
'slug' => $this->slug,
...TranslatablePayload::resolve($this->resource, $this->translatable, $locale),
'category' => $this->category->value,
'radar_ring' => $this->radar_ring?->value,
'color' => $this->color,
// The stored path, which is what a client PATCHes back; what was
// derived from it travels alongside, as on a page.
'logo' => $this->logo,
'logo_media' => ImagePayload::make(
$this->logo,
$this->resource->relationLoaded('logoMedia') ? $this->resource->getRelation('logoMedia') : null,
$this->name,
),
'website' => $this->website,
'position' => $this->position,
'projects_count' => $this->whenCounted('projects'),
'created_at' => $this->created_at?->toIso8601String(),
'updated_at' => $this->updated_at?->toIso8601String(),
'translations' => $this->when(
in_array('translations', explode(',', (string) $request->query('with')), true),
fn () => TranslatablePayload::all($this->resource, $this->translatable),
),
];
}
}

View File

@@ -24,14 +24,15 @@ class MediaPolicy extends ResourcePolicy
/**
* Uploading through the API, which has no form to attach a file to.
*
* Still true to the rule above in spirit: through the API the one record
* that holds an image is a page, so whoever may write pages may upload the
* image for one — and nobody else, whatever their `media.*` permissions,
* which only ever described looking after files that already exist.
* Still true to the rule above in spirit: an upload says which kind of
* record it is for — a page, a technology — and whoever may write that kind
* of record may upload its image. Nobody else, whatever their `media.*`
* permissions, which only ever described looking after files that already
* exist.
*/
public function upload(User $user): bool
public function upload(User $user, string $for = 'pages'): bool
{
return $user->can('pages.create') || $user->can('pages.update');
return $user->can("{$for}.create") || $user->can("{$for}.update");
}
/**