Files
pterodactyl-panel/app/Http/Controllers/Api/Application/Servers/ServerController.php
T
Sky Mulleyandrobert dennis 71dd1911a5 Implement native support for hooking into forms with extensions (#7256)
## Problem

Extensions can render content before and after most admin pages, but not
inside the forms on them. The only exception was
`panel.users.detail.form`, and it could only re-render or validate the
user's existing fields. An extension had no way to add a field of its
own, because the Panel's save requests had nowhere to carry the value
and nothing loaded it back.

## Changes

### Slots inside every admin form

The create and edit forms for users, nodes, servers, eggs, locations,
mounts and database hosts each render a slot inside the form, such as
`panel.servers.create.form` and `panel.servers.detail.details.form`. The
slot receives the native `form`, the form's `kind` (`admin.server`), and
`mode` (`'create'` or `'edit'`). Edit slots also receive the saved
`resource`. Contributed `form.AppField` controls share the form's
validation, pending state and submit action.

### Extension-owned fields

An extension registers fields in its provider:

```php
$this->registerFormFields('admin.user', ['plan' => ['required', 'in:free,pro']]);

$this->registerFormFields(
    'admin.node',
    ['region' => ['required', 'string', 'max:32']],
    fn (Node $node): array => ['region' => NodeRegion::for($node)],
    fn (Node $node, array $values) => NodeRegion::store($node, $values['region']),
);
```

The 14 create and update endpoints accept an optional `extensions: {
[extensionId]: { [field]: value } }` body field. Each extension's rules
are applied as `extensions.{id}.{field}`, and only when the request
includes that extension's values. The extension's `save` callback runs
in the same database transaction as the core change, so a failure rolls
both back.

Server creation is the exception. Wings reads the new server while
provisioning it, so extension values are saved after provisioning
succeeds, outside the transaction.

For Node updates when Wings is unreachable. `UpdateNode` saves the node
and then throws `ConfigurationNotPersistedException` as a warning. The
node controller defers that exception until the extension values are
saved, so the node update is no longer rolled back.

`GET /api/admin/extensions/forms/{form}/{id}` returns every extension's
current values. It requires the resource's read permission. Edit pages
fetch it before rendering the form, but only when an extension has
registered fields for that form; the bootstrap payload now lists them
per extension in `forms`.

For users and servers the callbacks are optional, and values are stored
in the extension's scoped settings (`settings()->forUser($user)`,
`forServer($server)`). Values are limited to strings, numbers, booleans,
`null`, or lists of strings and numbers, which keeps the OpenAPI schema
and generated types concrete.

A `load` callback that throws, or returns an invalid value, is recorded
against the extension in the `form` phase. The frontend then hides that
extension's slot contributions on the edit page, so a save cannot
overwrite its stored values with defaults. Fields of a disabled or
failed extension are neither validated, saved nor loaded.

---------

Co-authored-by: robert dennis <31261583+robertdrakedennis@users.noreply.github.com>
2026-10-09 01:26:45 -04:00

142 lines
7.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Pterodactyl\Http\Controllers\Api\Application\Servers;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Knuckles\Scribe\Attributes\Endpoint;
use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Response as ScribeResponse;
use Knuckles\Scribe\Attributes\Subgroup;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Pterodactyl\Contracts\Servers\CreatesServers;
use Pterodactyl\Contracts\Servers\DeletesServers;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Exceptions\Service\Deployment\NoViableAllocationException;
use Pterodactyl\Exceptions\Service\Deployment\NoViableNodeException;
use Pterodactyl\Extensions\Scribe\Attributes\ExtensionFieldsParam;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Http\Requests\Api\Application\Servers\GetServerRequest;
use Pterodactyl\Http\Requests\Api\Application\Servers\GetServersRequest;
use Pterodactyl\Http\Requests\Api\Application\Servers\ServerWriteRequest;
use Pterodactyl\Http\Requests\Api\Application\Servers\StoreServerRequest;
use Pterodactyl\Models\Server;
use Pterodactyl\Transformers\Api\Application\ServerTransformer;
use Spatie\QueryBuilder\QueryBuilder;
use Throwable;
#[Group('Application API', 'Root administrator endpoints for managing panel resources using application API tokens.')]
#[Subgroup('Servers', 'Create, update, retrieve, manage, and delete servers.')]
class ServerController extends ApplicationApiController
{
private const array DEPLOYMENT_ERROR = [
'errors' => [
[
'code' => 'NoViableNodeException',
'status' => '400',
'detail' => 'No nodes satisfying the requirements specified for automatic deployment could be found.',
],
],
];
/**
* Return all the servers that currently exist on the Panel.
*
* @return ApiPayload
*/
#[Endpoint('List servers', 'Returns a paginated list of servers visible to the application API key.')]
#[QueryParam('per_page', 'integer', 'Number of servers to return per page, up to 100.', required: false, example: 50)]
#[QueryParam('filter[uuid]', 'string', 'Filter servers by UUID.', required: false, example: '4fcb1f44-0f90-4a1a-a8bf-7cc8a14d0f26')]
#[QueryParam('filter[uuidShort]', 'string', 'Filter servers by short UUID identifier.', required: false, example: '4fcb1f44')]
#[QueryParam('filter[name]', 'string', 'Filter servers by name.', required: false, example: 'Minecraft Server')]
#[QueryParam('filter[description]', 'string', 'Filter servers by description.', required: false, example: 'Production')]
#[QueryParam('filter[image]', 'string', 'Filter servers by Docker image.', required: false, example: 'ghcr.io/pterodactyl/yolks:java_23')]
#[QueryParam('filter[external_id]', 'string', 'Filter servers by external identifier.', required: false, example: 'billing-server-42')]
#[QueryParam('search', 'string', 'Search term accepted by the list request. Must not exceed 100 characters.', required: false, example: 'minecraft')]
#[QueryParam('sort', 'string', 'Sort servers by id or uuid. Prefix with "-" for descending order.', required: false, example: '-id', enum: ['id', '-id', 'uuid', '-uuid'])]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "allocations", "user", "subusers", "egg", "variables", "location", "node", "databases", and "transfer" when the key can read those resources.', required: false, example: 'user,node,allocations')]
#[ResponseFromTransformer(ServerTransformer::class, Server::class, collection: true, factoryStates: ['withRelationships'], resourceKey: 'server', paginate: [IlluminatePaginatorAdapter::class, 50])]
public function index(GetServersRequest $request): array
{
$query = Server::query()->with(['egg.variables', 'serverVariables', 'location']);
$search = $request->validated('search');
if (is_string($search) && $search !== '') {
$query->where(function (Builder $query) use ($search): void {
$query->where('uuid', 'like', "%{$search}%")
->orWhere('uuidShort', 'like', "%{$search}%")
->orWhere('name', 'like', "%{$search}%")
->orWhere('description', 'like', "%{$search}%")
->orWhere('external_id', 'like', "%{$search}%");
});
}
$servers = QueryBuilder::for($query)
->allowedFilters(['uuid', 'uuidShort', 'name', 'description', 'image', 'external_id'])
->allowedSorts(['id', 'uuid'])
->paginate($request->perPage());
return Fractal::collection($servers)
->transformWith($this->getTransformer(ServerTransformer::class))
->toResponseArray();
}
/**
* Create a new server on the system.
*
* @throws Throwable
* @throws ValidationException
* @throws DisplayException
* @throws NoViableAllocationException
* @throws NoViableNodeException
*/
#[Endpoint('Create server', 'Creates a new server using either explicit allocations or automatic deployment constraints.')]
#[ResponseFromTransformer(ServerTransformer::class, Server::class, status: 201, description: 'Server created.', factoryStates: ['withRelationships'], resourceKey: 'server')]
#[ScribeResponse(self::DEPLOYMENT_ERROR, status: 400, description: 'Automatic deployment could not find a viable node or allocation.')]
#[ExtensionFieldsParam]
public function store(StoreServerRequest $request, CreatesServers $creation): JsonResponse
{
$server = $creation->create($request->payload(), $request->getDeploymentObject());
return Fractal::item($server)
->transformWith($this->getTransformer(ServerTransformer::class)->withExtensionFields())
->respond(201);
}
/**
* Show a single server transformed for the application API.
*
* @return ApiPayload
*/
#[Endpoint('Get server', 'Returns a single server by internal numeric ID.')]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "allocations", "user", "subusers", "egg", "variables", "location", "node", "databases", and "transfer" when the key can read those resources.', required: false, example: 'user,node,allocations')]
#[ResponseFromTransformer(ServerTransformer::class, Server::class, factoryStates: ['withRelationships'], resourceKey: 'server')]
public function view(GetServerRequest $request, Server $server): array
{
return Fractal::item($server)
->transformWith($this->getTransformer(ServerTransformer::class)->withExtensionFields())
->toResponseArray();
}
/**
* Deletes a server.
*
* @throws DisplayException
*/
#[Endpoint('Delete server', 'Deletes a server. The force route bypasses recoverable Wings or database host deletion failures.')]
#[ScribeResponse(status: 204, description: 'Server deleted.')]
public function delete(ServerWriteRequest $request, DeletesServers $deletion, Server $server, string $force = ''): Response
{
$deletion->withForce($force === 'force')->delete($server);
return $this->returnNoContent();
}
}