drop json guard

This commit is contained in:
robert dennis
2026-10-12 05:18:57 -04:00
parent ae296bda86
commit 987eab6f72
58 changed files with 122 additions and 395 deletions
+2 -8
View File
@@ -18,10 +18,9 @@ use Pterodactyl\Models\ActivityLogSubject;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\User;
use Pterodactyl\Support\JsonValueGuard;
/**
* @phpstan-type ActivityEvent array{user: string|null, server: string, event: string, metadata: array<string, mixed>, ip: string|null, timestamp: string}
* @phpstan-type ActivityEvent array{user: string|null, server: string, event: string, metadata: array<mixed>, ip: string|null, timestamp: string}
*/
final class IngestActivityLogs implements IngestsActivityLogs
{
@@ -63,16 +62,11 @@ final class IngestActivityLogs implements IngestsActivityLogs
foreach (array_keys($input->array('data')) as $key) {
$event = 'data.'.$key.'.';
// Metadata is whatever Wings recorded for the event, so Laravel's typed accessors
// have no type to give it; it is checked as the JSON object it was sent as.
$metadata = $input->array($event.'metadata');
JsonValueGuard::assertPayload9($metadata);
$events[] = [
'user' => $input->filled($event.'user') ? $input->string($event.'user')->toString() : null,
'server' => $input->string($event.'server')->toString(),
'event' => $input->string($event.'event')->toString(),
'metadata' => $metadata,
'metadata' => $input->array($event.'metadata'),
'ip' => $input->filled($event.'ip') ? $input->string($event.'ip')->toString() : null,
'timestamp' => $input->string($event.'timestamp')->toString(),
];
@@ -126,15 +126,12 @@ final readonly class CreateAllocations implements CreatesAllocations
throw_if(! $isPort && ! $isRange, InvalidPortMappingException::class, $port);
if ($isRange) {
// SAFETY: PORT_RANGE_REGEX captures two decimal integer strings.
$start = (int) $matches[1];
// SAFETY: PORT_RANGE_REGEX captures two decimal integer strings.
$end = (int) $matches[2];
$block = range($start, $end);
throw_if(count($block) > self::PORT_RANGE_LIMIT, TooManyPortsInRangeException::class);
throw_if($start <= self::PORT_FLOOR || $end > self::PORT_CEIL, PortOutOfRangeException::class);
} else {
// SAFETY: ctype_digit() above proves a decimal port string in the non-range branch.
$portNumber = (int) $port;
throw_if($portNumber <= self::PORT_FLOOR || $portNumber > self::PORT_CEIL, PortOutOfRangeException::class);
$block = [$portNumber];
-1
View File
@@ -132,7 +132,6 @@ final class InitiateBackup implements InitiatesBackups
->orderByDesc('created_at')
->first() ?? throw new UnexpectedValueException('The backup throttle query returned an empty result set.');
// SAFETY: HTTP Retry-After uses whole seconds, so truncating Carbon's fractional difference is intentional.
throw new TooManyRequestsHttpException((int) CarbonImmutable::now()->diffInSeconds($latest->created_at->addSeconds($period)), $message);
}
}
+6 -5
View File
@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace Pterodactyl\Actions\Databases;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
@@ -104,24 +103,26 @@ final class CreateDatabase implements CreatesDatabases
throw_if(($server->database_limit) !== null && $server->databases()->count() >= $server->database_limit, TooManyDatabasesException::class);
}
$username = sprintf('u%d_%s', $server->id, Str::random(10));
$password = Utilities::randomStringWithSpecialCharacters(24);
$data = [
...self::attributes($input),
'server_id' => $server->id,
'username' => sprintf('u%d_%s', $server->id, Str::random(10)),
'password' => Crypt::encrypt(Utilities::randomStringWithSpecialCharacters(24)),
'username' => $username,
'password' => Crypt::encrypt($password),
];
$database = null;
try {
$database = DB::transaction(function () use ($data, &$database): Database {
$database = DB::transaction(function () use ($data, $password, &$database): Database {
$this->dynamic->set('dynamic', $data['database_host_id']);
$database = $this->createModel($data);
$this->gateway->createDatabase($database->database);
$this->gateway->createUser(
$database->username,
$database->remote,
Arr::string(['password' => Crypt::decrypt($database->password)], 'password'),
$password,
$database->max_connections
);
$this->gateway->assignUserToDatabase($database->database, $database->username, $database->remote);
+1 -1
View File
@@ -11,7 +11,7 @@ use Pterodactyl\Models\Server;
final readonly class PullFile implements PullsFiles
{
/** @param array<mixed> $options */
/** @param array{filename?: string|null, use_header?: bool, foreground?: bool, timeout?: int} $options */
public function pull(Server $server, string $url, ?string $directory, array $options): void
{
Daemon::server($server)->files()->pull($url, $directory, $options);
+6 -3
View File
@@ -31,9 +31,9 @@ use Pterodactyl\Services\Deployment\FindViableNodesService;
use Pterodactyl\Services\Extensions\ExtensionFields;
use Pterodactyl\Services\Extensions\ValidatedExtensionValues;
use Pterodactyl\Services\Servers\VariableValidatorService;
use Pterodactyl\Support\JsonValueGuard;
use Ramsey\Uuid\Uuid;
use Throwable;
use UnexpectedValueException;
/**
* @phpstan-type CreationAttributes array{external_id: string|null, name: string, description: string, owner_id: int, egg_id: int, image: string, startup: string, environment: array<string, bool|float|int|string|null>, skip_scripts: bool, oom_disabled: bool, memory: int, swap: int, disk: int, io: int, threads: string|null, cpu: int, database_limit: int, allocation_limit: int, backup_limit: int, allocation_id: int|null, allocation_additional: list<int>, start_on_completion: bool}
@@ -108,8 +108,11 @@ final readonly class CreateServer implements CreatesServers
// Laravel's typed accessors would turn every value into one type, but the egg's
// variable rules have to see each value as it was sent.
$environment = $input->array('environment');
JsonValueGuard::assertScalarPayload($environment);
$environment = [];
foreach ($input->array('environment') as $key => $value) {
throw_unless(is_string($key) && ($value === null || is_scalar($value)), UnexpectedValueException::class, 'Server environment variables must map names to scalar values.');
$environment[$key] = $value;
}
return [
'external_id' => $input->filled('external_id') ? $input->string('external_id')->toString() : null,
+6 -4
View File
@@ -15,8 +15,8 @@ use Pterodactyl\Models\Egg;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\User;
use Pterodactyl\Services\Servers\VariableValidatorService;
use Pterodactyl\Support\JsonValueGuard;
use Throwable;
use UnexpectedValueException;
/**
* @phpstan-type StartupAttributes array{environment: array<string, bool|float|int|string|null>, egg_id?: int, startup?: string, docker_image?: string, skip_scripts?: bool}
@@ -74,8 +74,11 @@ final readonly class UpdateServerStartup implements UpdatesServerStartup
// Laravel's typed accessors would turn every value into one type, but the egg's
// variable rules have to see each value as it was sent.
$environment = $input->array('environment');
JsonValueGuard::assertScalarPayload($environment);
$environment = [];
foreach ($input->array('environment') as $key => $value) {
throw_unless(is_string($key) && ($value === null || is_scalar($value)), UnexpectedValueException::class, 'Server environment variables must map names to scalar values.');
$environment[$key] = $value;
}
$attributes = ['environment' => $environment];
if ($userLevel !== User::USER_LEVEL_ADMIN) {
@@ -124,7 +127,6 @@ final readonly class UpdateServerStartup implements UpdatesServerStartup
$results = $this->validatorService->setUserLevel($userLevel)->handle($egg, $attributes['environment']);
foreach ($results as $result) {
// SAFETY: validated variable values are JSON scalars, which all have a string form.
$this->variables->update($server, $result->id, $result->value === null ? '' : (string) $result->value);
}
}
+3 -2
View File
@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace Pterodactyl\Actions\Users;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
@@ -19,6 +18,7 @@ use Pterodactyl\Facades\Activity;
use Pterodactyl\Models\RecoveryToken;
use Pterodactyl\Models\User;
use Throwable;
use UnexpectedValueException;
final readonly class ToggleTwoFactor implements TogglesTwoFactor
{
@@ -41,7 +41,8 @@ final readonly class ToggleTwoFactor implements TogglesTwoFactor
$encryptedSecret = $user->totp_secret;
throw_if($encryptedSecret === null, TwoFactorAuthenticationTokenInvalid::class);
$secret = Arr::string(['secret' => Crypt::decrypt($encryptedSecret)], 'secret');
$secret = Crypt::decrypt($encryptedSecret);
throw_unless(is_string($secret), UnexpectedValueException::class, 'The decrypted two-factor secret must be a string.');
$isValidToken = $this->google2FA->verifyKey($secret, $token, config('pterodactyl.auth.2fa.window'));
@@ -7,7 +7,6 @@ namespace Pterodactyl\Console\Commands\Location;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Fluent;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Locations\CreatesLocations;
@@ -22,16 +21,13 @@ class MakeLocationCommand extends Command
*/
public function handle(CreatesLocations $locations): int
{
$input = Fluent::make([
$input = [
'short' => $this->option('short') ?? $this->ask(trans('command/messages.location.ask_short')),
'long' => $this->option('long') ?? $this->ask(trans('command/messages.location.ask_long')),
]);
];
try {
$location = $locations->create([
'short' => $input->get('short') === null ? null : $input->string('short')->toString(),
'long' => $input->get('long') === null ? null : $input->string('long')->toString(),
]);
$location = $locations->create($input);
} catch (ValidationException $validationException) {
foreach ($validationException->validator->errors()->all() as $error) {
$this->error($error);
@@ -9,7 +9,6 @@ use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Nodes\CreatesNodes;
use Pterodactyl\Support\JsonValueGuard;
#[Description('Creates a new node on the system via the CLI.')]
#[Signature('p:node:make
@@ -58,7 +57,6 @@ class MakeNodeCommand extends Command
'daemon_sftp' => $this->option('daemonSFTPPort') ?? $this->ask('Enter the wings SFTP listening port', '2022'),
'daemon_base' => $this->option('daemonBase') ?? $this->ask('Enter the base folder', '/var/lib/pterodactyl/volumes'),
];
JsonValueGuard::assertScalarPayload($input);
try {
$node = $nodes->create($input);
+9 -9
View File
@@ -9,11 +9,10 @@ use Exception;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Fluent;
use Illuminate\Support\Str;
use InvalidArgumentException;
use Pterodactyl\Services\FilesystemChanges;
use Symfony\Component\Console\Helper\ProgressBar;
@@ -47,9 +46,8 @@ class UpgradeCommand extends Command
$this->line($this->getUrl());
}
$options = Fluent::make($this->options());
$user = $this->option('user') === null ? 'www-data' : $options->string('user')->toString();
$group = $this->option('group') === null ? 'www-data' : $options->string('group')->toString();
$user = is_string($this->option('user')) ? $this->option('user') : 'www-data';
$group = is_string($this->option('group')) ? $this->option('group') : 'www-data';
if ($this->input->isInteractive()) {
if (! $skipDownload) {
$skipDownload = ! $this->confirm('Would you like to download and unpack the archive files for the latest version?', true);
@@ -61,14 +59,15 @@ class UpgradeCommand extends Command
$user = $userDetails !== false ? $userDetails['name'] : 'www-data';
if (! $this->confirm("Your webserver user has been detected as <fg=blue>[{$user}]:</> is this correct?", true)) {
$user = Arr::string(['user' => $this->anticipate(
$user = $this->anticipate(
'Please enter the name of the user running your webserver process. This varies from system to system, but is generally "www-data", "nginx", or "apache".',
[
'www-data',
'nginx',
'apache',
]
)], 'user');
);
throw_unless(is_string($user), InvalidArgumentException::class, 'A webserver user is required.');
}
}
@@ -78,14 +77,15 @@ class UpgradeCommand extends Command
$group = $groupDetails !== false ? $groupDetails['name'] : 'www-data';
if (! $this->confirm("Your webserver group has been detected as <fg=blue>[{$group}]:</> is this correct?", true)) {
$group = Arr::string(['group' => $this->anticipate(
$group = $this->anticipate(
'Please enter the name of the group running your webserver process. Normally this is the same as your user.',
[
'www-data',
'nginx',
'apache',
]
)], 'group');
);
throw_unless(is_string($group), InvalidArgumentException::class, 'A webserver group is required.');
}
}
@@ -7,7 +7,6 @@ namespace Pterodactyl\Console\Commands\User;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use InvalidArgumentException;
use Pterodactyl\Contracts\Users\DeletesUsers;
use Pterodactyl\Models\User;
@@ -19,12 +18,10 @@ class DeleteUserCommand extends Command
public function handle(DeletesUsers $users): int
{
$search = $this->option('user') ?? $this->ask(trans('command/messages.user.search_users'));
if (empty($search)) {
if (! is_string($search) || empty($search)) {
throw new InvalidArgumentException(sprintf('Search term should be an email address, got: %s.', get_debug_type($search)));
}
$search = Arr::string(['search' => $search], 'search');
$results = User::query()
->where('id', 'LIKE', "$search%")
->orWhere('username', 'LIKE', "$search%")
+6 -18
View File
@@ -7,7 +7,6 @@ namespace Pterodactyl\Console\Commands\User;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Fluent;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Users\CreatesUsers;
use Throwable;
@@ -23,34 +22,23 @@ class MakeUserCommand extends Command
*/
public function handle(CreatesUsers $users): int
{
$root_admin = $this->option('admin') === null
? $this->confirm(trans('command/messages.user.ask_admin'))
: Fluent::make($this->options())->string('admin')->toString();
$input = Fluent::make([
$input = [
'root_admin' => $this->option('admin') ?? $this->confirm(trans('command/messages.user.ask_admin')),
'email' => $this->option('email') ?? $this->ask(trans('command/messages.user.ask_email')),
'username' => $this->option('username') ?? $this->ask(trans('command/messages.user.ask_username')),
'name_first' => $this->option('name-first') ?? $this->ask(trans('command/messages.user.ask_name_first')),
'name_last' => $this->option('name-last') ?? $this->ask(trans('command/messages.user.ask_name_last')),
'password' => $this->option('password'),
]);
];
if ($input->get('password') === null && ! $this->option('no-password')) {
if ($input['password'] === null && ! $this->option('no-password')) {
$this->warn(trans('command/messages.user.ask_password_help'));
$this->line(trans('command/messages.user.ask_password_tip'));
$input->set('password', $this->secret(trans('command/messages.user.ask_password')));
$input['password'] = $this->secret(trans('command/messages.user.ask_password'));
}
$text = fn (string $key): ?string => $input->get($key) === null ? null : $input->string($key)->toString();
try {
$user = $users->create([
'email' => $text('email'),
'username' => $text('username'),
'name_first' => $text('name_first'),
'name_last' => $text('name_last'),
'password' => $text('password'),
'root_admin' => $root_admin,
]);
$user = $users->create($input);
} catch (ValidationException $validationException) {
foreach ($validationException->validator->errors()->all() as $error) {
$this->error($error);
+1 -1
View File
@@ -8,6 +8,6 @@ use Pterodactyl\Models\Server;
interface PullsFiles
{
/** @param array<mixed> $options */
/** @param array{filename?: string|null, use_header?: bool, foreground?: bool, timeout?: int} $options */
public function pull(Server $server, string $url, ?string $directory, array $options): void;
}
-1
View File
@@ -32,7 +32,6 @@ final readonly class AllocationRange
}
if (is_string($value) && preg_match('/^-?\d+$/', $value)) {
// SAFETY: the anchored decimal-integer pattern proves the string has an integer representation.
return (int) $value;
}
+4 -6
View File
@@ -7,9 +7,7 @@ namespace Pterodactyl\Data;
use GuzzleHttp\Psr7\Uri;
use InvalidArgumentException;
use JsonException;
use Pterodactyl\Support\JsonValueGuard;
use Symfony\Component\HttpKernel\Exception\HttpException;
use UnexpectedValueException;
final readonly class EggCatalogEntry
{
@@ -25,12 +23,12 @@ final readonly class EggCatalogEntry
public static function listFromJson(string $contents): array
{
try {
$data = JsonValueGuard::decodeArray8($contents);
} catch (JsonException|UnexpectedValueException $exception) {
throw new HttpException(502, 'Pterodactyl returned an invalid egg catalog. Please try again later.', $exception);
$data = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $jsonException) {
throw new HttpException(502, 'Pterodactyl returned an invalid egg catalog. Please try again later.', $jsonException);
}
throw_unless(array_is_list($data), HttpException::class, 502, 'Pterodactyl returned an invalid egg catalog. Please try again later.');
throw_unless(is_array($data) && array_is_list($data), HttpException::class, 502, 'Pterodactyl returned an invalid egg catalog. Please try again later.');
$entries = [];
foreach ($data as $value) {
@@ -4,8 +4,6 @@ declare(strict_types=1);
namespace Pterodactyl\Data\Extensions;
use UnexpectedValueException;
final readonly class ExtensionJobSnapshot
{
/** @param 'running'|'completed'|'failed' $status */
@@ -22,12 +20,6 @@ final readonly class ExtensionJobSnapshot
public string $updatedAt,
) {}
/** @phpstan-assert self|null $value */
public static function assertCacheValue(mixed $value): void
{
throw_if($value !== null && ! $value instanceof self, UnexpectedValueException::class, 'Invalid cached extension progress snapshot.');
}
/** @return array{id: string, extension: string, status: 'running'|'completed'|'failed', percent: int, message: string, sequence: int, updated_at: string} */
public function payload(): array
{
+1 -1
View File
@@ -32,7 +32,7 @@ final readonly class LoginResult
/**
* The `data` payload the panel's login screens expect from a JSON login endpoint.
*
* @return array{complete: false, confirmation_token: string|null}|array{complete: true, intended: string, user: array<string, mixed>}
* @return array{complete: false, confirmation_token: string|null}|array{complete: true, intended: string, user: array<mixed>}
*/
public function toResponseData(): array
{
@@ -8,11 +8,11 @@ use Closure;
use Illuminate\Auth\Events\PasswordResetLinkSent;
use Illuminate\Auth\Passwords\PasswordBroker as IlluminatePasswordBroker;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Pterodactyl\Models\User;
use SensitiveParameter;
use UnexpectedValueException;
class PasswordBroker extends IlluminatePasswordBroker
{
@@ -41,7 +41,10 @@ class PasswordBroker extends IlluminatePasswordBroker
$token = $this->tokens->create($user);
if ($callback instanceof Closure) {
return Arr::string(['status' => $callback($user, $token) ?? static::RESET_LINK_SENT], 'status');
$status = $callback($user, $token) ?? static::RESET_LINK_SENT;
throw_unless(is_string($status), UnexpectedValueException::class, 'The password reset callback must return a status string.');
return $status;
}
$user->sendPasswordResetNotification($token);
@@ -6,7 +6,6 @@ namespace Pterodactyl\Http\Controllers\Api\Admin\ApiKeys;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Knuckles\Scribe\Attributes\Endpoint;
use Knuckles\Scribe\Attributes\Group;
@@ -28,6 +27,7 @@ use Pterodactyl\Http\Requests\Api\Admin\ApiKeys\UpdateApiKeyRequest;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Transformers\Api\Admin\ApiKeyTransformer;
use Spatie\QueryBuilder\QueryBuilder;
use UnexpectedValueException;
#[Group('Admin API', 'Root administrator endpoints for managing panel configuration and resources.')]
#[Subgroup('API Keys', 'Create and manage application API keys.')]
@@ -72,10 +72,13 @@ class ApiKeyController extends AdminApiController
->property('identifier', $key->identifier)
->log();
$token = Crypt::decrypt($key->token);
throw_unless(is_string($token), UnexpectedValueException::class, 'The decrypted API key must be a string.');
return Fractal::item($key)
->transformWith($this->getTransformer(ApiKeyTransformer::class))
->addMeta([
'secret_token' => $key->identifier.Arr::string(['token' => Crypt::decrypt($key->token)], 'token'),
'secret_token' => $key->identifier.$token,
])
->respond(Response::HTTP_CREATED);
}
@@ -80,7 +80,6 @@ class AllocationController extends AdminApiController
return $builder->whereNull('server_id');
}
// SAFETY: the boundary checks above limit the filter to an integer or string before decimal validation.
if (! ctype_digit((string) $value)) {
return $builder->whereNull('server_id');
}
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Controllers\Api\Admin\Nodes;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Knuckles\Scribe\Attributes\Endpoint;
use Knuckles\Scribe\Attributes\Group;
@@ -18,6 +17,7 @@ use Pterodactyl\Http\Requests\Api\Admin\Nodes\DeployTokenRequest;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Models\Node;
use Pterodactyl\Services\Acl\Api\AdminAcl;
use UnexpectedValueException;
#[Group('Admin API', 'Root administrator endpoints for managing panel configuration and resources.')]
#[Subgroup('Nodes', 'Create, update, retrieve, and delete Wings nodes.')]
@@ -61,9 +61,12 @@ class DeployTokenController extends AdminApiController
->property('name', $node->name)
->log();
$token = Crypt::decrypt($key->token);
throw_unless(is_string($token), UnexpectedValueException::class, 'The decrypted API key must be a string.');
return new JsonResponse([
'node' => $node->id,
'token' => $key->identifier.Arr::string(['token' => Crypt::decrypt($key->token)], 'token'),
'token' => $key->identifier.$token,
'panel_url' => config('app.url'),
'allow_insecure' => config('app.debug'),
]);
@@ -26,7 +26,6 @@ class AdvancedController extends AdminApiController
public function __invoke(UpdateAdvancedSettingsRequest $request, Kernel $kernel): Response
{
foreach ($request->normalize() as $key => $value) {
// SAFETY: settings are persisted in the environment store as strings; null retains its deletion semantics.
Setting::put('settings::'.$key, ($value) === null ? null : (string) $value);
}
@@ -26,7 +26,6 @@ class GeneralController extends AdminApiController
public function __invoke(UpdateGeneralSettingsRequest $request, Kernel $kernel): Response
{
foreach ($request->normalize() as $key => $value) {
// SAFETY: settings are persisted in the environment store as strings.
Setting::put('settings::'.$key, (string) $value);
}
@@ -52,7 +52,6 @@ class MailController extends AdminApiController
$value = Crypt::encrypt($value);
}
// SAFETY: settings are persisted in the environment store as strings; null retains its deletion semantics.
Setting::put('settings::'.$key, ($value) === null ? null : (string) $value);
}
@@ -90,7 +90,6 @@ class AllocationController extends ApplicationApiController
return $builder->whereNull('server_id');
}
// SAFETY: the boundary checks above limit the filter to an integer or string before decimal validation.
if (! ctype_digit((string) $value)) {
return $builder->whereNull('server_id');
}
@@ -45,7 +45,6 @@ use Pterodactyl\Http\Requests\Api\Client\Servers\Files\RenameFileRequest;
use Pterodactyl\Http\Requests\Api\Client\Servers\Files\WriteFileContentRequest;
use Pterodactyl\Models\Server;
use Pterodactyl\Services\Nodes\NodeJWTService;
use Pterodactyl\Support\JsonValueGuard;
use Pterodactyl\Transformers\Api\Client\FileObjectTransformer;
use Throwable;
@@ -236,7 +235,7 @@ class FileController extends ClientApiController
#[ScribeResponse(self::DAEMON_ERROR, status: 502, description: 'Wings could not rename the files.')]
public function rename(RenameFileRequest $request, RenamesFiles $operation, Server $server): JsonResponse
{
$operation->rename($server, $this->path($request, 'root'), JsonValueGuard::jsonArray($request->validated('files')));
$operation->rename($server, $this->path($request, 'root'), $request->safe()->array('files'));
return new JsonResponse([], Response::HTTP_NO_CONTENT);
}
@@ -266,7 +265,7 @@ class FileController extends ClientApiController
#[ScribeResponse(self::DAEMON_ERROR, status: 502, description: 'Wings could not create the archive.')]
public function compress(CompressFilesRequest $request, CompressesFiles $operation, Server $server): array
{
$file = $operation->compress($server, $this->path($request, 'root'), JsonValueGuard::jsonArray($request->validated('files')));
$file = $operation->compress($server, $this->path($request, 'root'), $request->safe()->array('files'));
return Fractal::item($file)
->transformWith($this->getTransformer(FileObjectTransformer::class))
@@ -296,7 +295,7 @@ class FileController extends ClientApiController
#[ScribeResponse(self::DAEMON_ERROR, status: 502, description: 'Wings could not delete the files.')]
public function delete(DeleteFileRequest $request, DeletesFiles $operation, Server $server): JsonResponse
{
$operation->delete($server, $this->path($request, 'root'), JsonValueGuard::jsonArray($request->validated('files')));
$operation->delete($server, $this->path($request, 'root'), $request->safe()->array('files'));
return new JsonResponse([], Response::HTTP_NO_CONTENT);
}
@@ -311,7 +310,7 @@ class FileController extends ClientApiController
#[ScribeResponse(self::DAEMON_ERROR, status: 502, description: 'Wings could not update file permissions.')]
public function chmod(ChmodFilesRequest $request, ChangesFilePermissions $operation, Server $server): JsonResponse
{
$operation->change($server, $this->path($request, 'root'), JsonValueGuard::jsonArray($request->validated('files')));
$operation->change($server, $this->path($request, 'root'), $request->safe()->array('files'));
return new JsonResponse([], Response::HTTP_NO_CONTENT);
}
@@ -7,7 +7,6 @@ namespace Pterodactyl\Http\Controllers\Auth;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
@@ -26,6 +25,7 @@ use Pterodactyl\Data\LoginCheckpoint;
use Pterodactyl\Events\Auth\ProvidedAuthenticationToken;
use Pterodactyl\Http\Requests\Auth\LoginCheckpointRequest;
use Pterodactyl\Models\User;
use UnexpectedValueException;
#[Group('Authentication', 'Browser session authentication endpoints used by the panel frontend.', authenticated: false)]
class LoginCheckpointController extends AbstractLoginController
@@ -114,8 +114,8 @@ class LoginCheckpointController extends AbstractLoginController
$this->sendFailedLoginResponse($request, $user, self::TOKEN_EXPIRED_MESSAGE);
}
$decrypted = Arr::string(['secret' => Crypt::decrypt($totpSecret)], 'secret');
// SAFETY: TOTP counters are discrete intervals, so flooring and converting the quotient to an integer is required.
$decrypted = Crypt::decrypt($totpSecret);
throw_unless(is_string($decrypted), UnexpectedValueException::class, 'The decrypted two-factor secret must be a string.');
$oldTimestamp = $user->totp_authenticated_at
? (int) floor($user->totp_authenticated_at->unix() / $google2FA->getKeyRegeneration())
: null;
@@ -11,10 +11,10 @@ use IPTools\Exception\IpException;
use IPTools\Exception\NetworkException;
use IPTools\IP;
use IPTools\Range;
use Laravel\Sanctum\Contracts\HasAbilities;
use Laravel\Sanctum\TransientToken;
use Pterodactyl\Facades\Activity;
use Pterodactyl\Http\Concerns\ResolvesRequestContext;
use Pterodactyl\Models\ApiKey;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@@ -35,15 +35,13 @@ class AuthenticateIPAccess
public function handle(Request $request, Closure $next): mixed
{
$user = $this->authenticatedUser($request);
// SAFETY: Sanctum may supply a TransientToken for stateful requests; authenticated API requests use the configured ApiKey model.
/** @var TransientToken|ApiKey|null $token */
$token = $user->currentAccessToken();
// If this is a stateful request just push the request through to the next
// middleware in the stack, there is nothing we need to explicitly check. If
// this is a valid API Key, but there is no allowed IP restriction, also pass
// the request through.
if ($token === null || $token instanceof TransientToken || empty($token->allowed_ips)) {
if (! $token instanceof HasAbilities || $token instanceof TransientToken || empty($token->allowed_ips)) {
return $next($request);
}
@@ -59,7 +59,6 @@ class SyncTagsRequest extends AdminApiRequest
foreach ($tags as $key => $tag) {
if (is_int($tag)) {
// SAFETY: integer tag IDs have an exact decimal string representation.
$tags[$key] = (string) $tag;
}
}
@@ -150,7 +150,6 @@ class StoreServerRequest extends ApplicationApiRequest
return Server::class;
}
/** @phpstan-assert int|string $value */
private function validateDeployTagReference(string $attribute, mixed $value, Closure $fail): void
{
if (! is_int($value) && ! is_string($value)) {
@@ -98,7 +98,6 @@ trait FiltersDeployTags
if (is_string($tag) && mb_trim($tag) !== '') {
$tags[] = mb_trim($tag);
} elseif (is_int($tag)) {
// SAFETY: integer tag IDs have an exact decimal string representation.
$tags[] = (string) $tag;
}
}
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Resources\Api\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseField;
use Pterodactyl\Facades\Hashids;
@@ -69,7 +68,7 @@ class ServerDatabaseResource extends AdminResource
private function includePassword(): ApiResource
{
return $this->item($this->resource, fn (Database $model): array => [
'password' => Arr::string(['password' => Crypt::decrypt($model->password)], 'password'),
'password' => Crypt::decrypt($model->password),
], 'database_password');
}
}
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Resources\Api\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseField;
@@ -74,7 +73,7 @@ class DatabaseResource extends ClientResource
}
return $this->item($this->resource, fn (Database $model): array => [
'password' => Arr::string(['password' => Crypt::decrypt($model->password)], 'password'),
'password' => Crypt::decrypt($model->password),
], 'database_password');
}
}
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Resources\Api\Includes;
use Illuminate\Http\Request;
use Pterodactyl\Support\JsonValueGuard;
use UnexpectedValueException;
/**
* The includes a request asked for, parsed as league/fractal's Manager parses them, so API
@@ -30,9 +30,8 @@ final readonly class IncludeSet
*/
public static function fromRequest(Request $request, array $forced = [], int $limit = 2): self
{
$requested = JsonValueGuard::stringList(array_values($request->collect('include')->all()));
$names = collect($requested)
$names = $request->collect('include')
->map(fn (mixed $value): string => is_string($value) ? $value : throw new UnexpectedValueException('The requested includes must be strings.'))
->flatMap(fn (string $value): array => explode(',', $value))
->map(fn (string $value): string => mb_trim($value))
->filter()
-2
View File
@@ -102,8 +102,6 @@ class RunTaskJob implements ShouldQueue
*/
private function queueNextTask(): void
{
// SAFETY: this query is rooted in the Task model and first() therefore returns Task|null.
/** @var Task|null $nextTask */
$nextTask = Task::query()->where('schedule_id', $this->task->schedule_id)
->orderBy('sequence_id', 'asc')
->where('sequence_id', '>', $this->task->sequence_id)
+3 -6
View File
@@ -17,7 +17,6 @@ use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Fluent;
use Illuminate\Support\Str;
use Pterodactyl\Contracts\Models\Identifiable;
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
@@ -339,9 +338,9 @@ class Node extends Model implements Identifiable
{
if (array_key_exists('sum_memory', $this->getAttributes()) && array_key_exists('sum_disk', $this->getAttributes())) {
// The SUM aliases come back from the database as numeric strings, or null for no servers.
$sums = Fluent::make($this->getAttributes());
$memory = $sums->integer('sum_memory');
$disk = $sums->integer('sum_disk');
$sums = $this->getAttributes();
$memory = is_numeric($sums['sum_memory']) ? (int) $sums['sum_memory'] : 0;
$disk = is_numeric($sums['sum_disk']) ? (int) $sums['sum_disk'] : 0;
} else {
$resources = $this->servers()->toBase()
->selectRaw('COALESCE(SUM(memory), 0) AS memory, COALESCE(SUM(disk), 0) AS disk')
@@ -349,9 +348,7 @@ class Node extends Model implements Identifiable
throw_if($resources === null || ! is_numeric($resources->memory) || ! is_numeric($resources->disk), UnexpectedValueException::class, 'The node resource aggregate query returned malformed values.');
// SAFETY: the aggregate values were validated as numeric immediately above.
$memory = (int) $resources->memory;
// SAFETY: the aggregate values were validated as numeric immediately above.
$disk = (int) $resources->disk;
}
-1
View File
@@ -235,7 +235,6 @@ class Server extends Model implements Identifiable
return null;
}
// SAFETY: the type check above limits route binding values to integers and strings.
$routeValue = (string) $value;
if (ctype_digit($routeValue)) {
$server = self::query()->whereKey($routeValue)->first();
-1
View File
@@ -139,7 +139,6 @@ class Tag extends Model
#[Scope]
protected function whereKeyOrSlug(Builder $query, string|array $identifier): void
{
// SAFETY: the declared union is either one string or a list of strings; array casting only wraps the scalar case.
$identifiers = array_values((array) $identifier);
self::filterKeysOrSlugs($query, $identifiers);
-1
View File
@@ -46,7 +46,6 @@ trait HasAccessTokens
*/
public function createToken(?string $memo, ?array $ips): NewAccessToken
{
// SAFETY: Sanctum is configured globally to persist personal access tokens with the ApiKey model.
/** @var ApiKey $token */
$token = $this->tokens()->forceCreate([
'user_id' => $this->id,
+10 -13
View File
@@ -10,6 +10,7 @@ use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Attributes\RouteKey;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Concerns\HasVersion4Uuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -20,14 +21,12 @@ use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Notifications\DatabaseNotificationCollection;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Laravel\Sanctum\TransientToken;
use Pterodactyl\Contracts\Models\Identifiable;
use Pterodactyl\Facades\Activity;
use Pterodactyl\Models\Traits\HasAccessTokens;
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
use Pterodactyl\Notifications\SendPasswordReset as ResetPasswordNotification;
use Pterodactyl\Support\JsonValueGuard;
use Pterodactyl\Traits\Helpers\AvailableLanguages;
/**
@@ -50,19 +49,19 @@ use Pterodactyl\Traits\Helpers\AvailableLanguages;
* @property bool $gravatar
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property \Illuminate\Database\Eloquent\Collection|ApiKey[] $apiKeys
* @property Collection|ApiKey[] $apiKeys
* @property int|null $api_keys_count
* @property string $name
* @property DatabaseNotificationCollection<int, DatabaseNotification>|DatabaseNotification[] $notifications
* @property int|null $notifications_count
* @property \Illuminate\Database\Eloquent\Collection|RecoveryToken[] $recoveryTokens
* @property Collection|RecoveryToken[] $recoveryTokens
* @property int|null $recovery_tokens_count
* @property \Illuminate\Database\Eloquent\Collection|Server[] $servers
* @property Collection|Server[] $servers
* @property int|null $servers_count
* @property int|null $subuser_of_count
* @property \Illuminate\Database\Eloquent\Collection|UserSSHKey[] $sshKeys
* @property Collection|UserSSHKey[] $sshKeys
* @property int|null $ssh_keys_count
* @property \Illuminate\Database\Eloquent\Collection|ApiKey[] $tokens
* @property Collection|ApiKey[] $tokens
* @property int|null $tokens_count
*
* @method static UserFactory factory(...$parameters)
@@ -166,16 +165,14 @@ class User extends Authenticatable implements Identifiable
}
/**
* @return array<string, mixed>
* @return array<mixed>
*/
public function toVueObject(): array
{
$payload = Collection::make($this->toArray())->except(['id', 'external_id'])
->merge(['identifier' => $this->identifier])
->toArray();
JsonValueGuard::assertPayload($payload);
$attributes = $this->toArray();
unset($attributes['id'], $attributes['external_id']);
return $payload;
return [...$attributes, 'identifier' => $this->identifier];
}
/**
+3 -2
View File
@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace Pterodactyl\Services\Acl\Api;
use Illuminate\Support\Fluent;
use Pterodactyl\Models\ApiKey;
use ReflectionClass;
use ReflectionException;
@@ -62,7 +61,9 @@ class AdminAcl
*/
public static function check(ApiKey $key, string $resource, int $action = self::READ): bool
{
return self::can(Fluent::make($key->getAttributes())->integer(self::COLUMN_IDENTIFIER.$resource, self::NONE), $action);
$permission = $key->getAttributes()[self::COLUMN_IDENTIFIER.$resource] ?? self::NONE;
return self::can(is_numeric($permission) ? (int) $permission : self::NONE, $action);
}
/**
+3 -6
View File
@@ -14,7 +14,6 @@ use Illuminate\Validation\ValidationException;
use JsonException;
use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException;
use Pterodactyl\Models\Node;
use Pterodactyl\Support\JsonValueGuard;
use UnexpectedValueException;
/** @phpstan-type RequestOptions array{json?: array<string, mixed>, query?: array<string, int|string>, body?: string, timeout?: int} */
@@ -57,11 +56,9 @@ final readonly class DaemonConnection
public function decode(Response $response, array $rules = [], bool $expectsList = false): array
{
try {
$data = JsonValueGuard::jsonArray(json_decode($response->body(), true, 512, JSON_THROW_ON_ERROR));
if (! $expectsList) {
JsonValueGuard::assertPayload($data);
}
$data = json_decode($response->body(), true, 512, JSON_THROW_ON_ERROR);
throw_unless(is_array($data), UnexpectedValueException::class, 'Wings did not return a JSON object or list.');
throw_if(! $expectsList && array_any(array_keys($data), fn (int|string $key): bool => is_int($key)), UnexpectedValueException::class, 'Wings returned a list where a JSON object was expected.');
Validator::make(['data' => $data], $rules)->validate();
+6 -10
View File
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace Pterodactyl\Services\Daemon;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Fluent;
use Illuminate\Support\Str;
use Pterodactyl\Exceptions\Http\Server\FileSizeTooLargeException;
@@ -52,7 +51,6 @@ final readonly class FilesClient
...$this->fileRules('data.*'),
], expectsList: true);
// SAFETY: list and file entries are validated by the transport above.
/** @var list<DaemonFileObject> $data */
return $data;
}
@@ -99,7 +97,6 @@ final readonly class FilesClient
]);
$data = $this->connection->decode($response, $this->fileRules('data'));
// SAFETY: the transport validates the bounded JSON and file shape above.
/** @var DaemonFileObject $data */
return $data;
}
@@ -120,21 +117,20 @@ final readonly class FilesClient
]);
}
/** @param array<mixed> $params */
/** @param array{filename?: string|null, use_header?: bool, foreground?: bool, timeout?: int} $params */
public function pull(string $url, ?string $directory, array $params = []): Response
{
$input = Fluent::make($params);
$attributes = [
'url' => $url,
'root' => $directory ?? '/',
'file_name' => $input->get('filename') === null ? null : $input->string('filename')->toString(),
'use_header' => $input->get('use_header') === null ? null : $input->boolean('use_header'),
'foreground' => $input->get('foreground') === null ? null : $input->boolean('foreground'),
'file_name' => $params['filename'] ?? null,
'use_header' => $params['use_header'] ?? null,
'foreground' => $params['foreground'] ?? null,
];
$options = ['json' => array_filter($attributes, fn (bool|string|null $value): bool => $value !== null)];
if ($input->get('timeout') !== null) {
$options['timeout'] = $input->integer('timeout');
if (isset($params['timeout'])) {
$options['timeout'] = $params['timeout'];
}
return $this->connection->request('POST', "/api/servers/{$this->uuid}/files/pull", $options);
+2 -5
View File
@@ -6,7 +6,6 @@ namespace Pterodactyl\Services\Daemon;
use Illuminate\Http\Client\Response;
use Pterodactyl\Models\Node;
use Pterodactyl\Support\JsonValueGuard;
final readonly class NodeClient
{
@@ -17,16 +16,14 @@ final readonly class NodeClient
return new self(DaemonConnection::forNode($node));
}
/** @return array<string, mixed> */
/** @return array<mixed> */
public function systemInformation(?int $version = null): array
{
$response = $this->connection->request('GET', '/api/system', [
'query' => $version === null ? [] : ['v' => $version],
]);
$data = $this->connection->decode($response);
JsonValueGuard::assertPayload($data);
return $data;
return $this->connection->decode($response);
}
public function update(Node $node): Response
-2
View File
@@ -46,7 +46,6 @@ final readonly class ServerClient
'data.utilization.network.tx_bytes' => ['sometimes', 'integer:strict'],
]);
// SAFETY: the transport validates the bounded JSON and the stats shape above.
/** @var DaemonStats $data */
return $data;
}
@@ -103,7 +102,6 @@ final readonly class ServerClient
'data.data.*' => ['string'],
]);
// SAFETY: the transport validates the bounded JSON and the list of lines above.
/** @var array{data: list<string>|null} $data */
return $data['data'] ?? [];
}
@@ -71,20 +71,16 @@ class AllocationSelectionService
$stored = [];
$ranges = [];
foreach ($ports as $port) {
// SAFETY: deployment ports are JSON scalars; string conversion is used only to test decimal port syntax.
if (! is_bool($port) && ctype_digit((string) $port)) {
// SAFETY: ctype_digit() above proves the scalar is a decimal integer before normalization.
$stored[] = (int) $port;
}
// Ranges are stored as a [start, end] pair for the onPorts() scope.
// SAFETY: deployment ports are JSON scalars; string conversion is used only to match the anchored range grammar.
if (preg_match(CreateAllocations::PORT_RANGE_REGEX, (string) $port, $matches)) {
if (abs($matches[2] - $matches[1]) > CreateAllocations::PORT_RANGE_LIMIT) {
throw new DisplayException(trans('exceptions.allocations.too_many_ports'));
}
// SAFETY: PORT_RANGE_REGEX captures two decimal integer strings.
$ranges[] = [(int) $matches[1], (int) $matches[2]];
}
}
@@ -50,7 +50,6 @@ class FindViableNodesService
foreach ($locations as $location) {
throw_if(is_string($location) && preg_match('/^-?\d+$/', $location) !== 1, InvalidArgumentException::class, 'An array of location IDs should be provided when calling setLocations.');
// SAFETY: integers pass directly and strings are accepted only after the anchored integer check above.
$parsed[] = (int) $location;
}
+1 -2
View File
@@ -9,7 +9,6 @@ use Pterodactyl\Actions\Eggs\CreateEgg;
use Pterodactyl\Actions\Eggs\Variables\CreateEggVariable;
use Pterodactyl\Exceptions\Service\InvalidFileUploadException;
use Pterodactyl\Models\Egg;
use Pterodactyl\Support\JsonValueGuard;
use Pterodactyl\Support\ValidationRuleSubset;
final readonly class EggImportData
@@ -41,7 +40,7 @@ final readonly class EggImportData
public static function fromJson(string $contents): self
{
return self::fromValue(JsonValueGuard::decodeArray8($contents));
return self::fromValue(json_decode($contents, true, flags: JSON_THROW_ON_ERROR));
}
private static function fromValue(mixed $value): self
@@ -10,6 +10,7 @@ use InvalidArgumentException;
use Pterodactyl\Data\Extensions\ExtensionJobSnapshot;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\User;
use UnexpectedValueException;
/** Shared snapshots survive reconnects and worker boundaries for the configured retention period. */
final class ExtensionJobProgress
@@ -48,8 +49,7 @@ final class ExtensionJobProgress
public function find(string $extension, string $id): ?ExtensionJobSnapshot
{
$snapshot = Cache::get($this->key($extension, $id));
ExtensionJobSnapshot::assertCacheValue($snapshot);
throw_if($snapshot !== null && ! $snapshot instanceof ExtensionJobSnapshot, UnexpectedValueException::class, 'Invalid cached extension progress snapshot.');
return $snapshot;
}
+4 -2
View File
@@ -7,7 +7,7 @@ namespace Pterodactyl\Services\Helpers;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Filesystem\FilesystemManager;
use Pterodactyl\Exceptions\ManifestDoesNotExistException;
use Pterodactyl\Support\JsonValueGuard;
use UnexpectedValueException;
class AssetHashService
{
@@ -206,7 +206,9 @@ class AssetHashService
/** @return ViteManifest */
private function parseManifest(string $contents): array
{
$decoded = JsonValueGuard::decodeArray8($contents);
$decoded = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);
throw_unless(is_array($decoded), UnexpectedValueException::class, 'The asset manifest must be a JSON object.');
$manifest = [];
foreach ($decoded as $source => $value) {
@@ -9,7 +9,6 @@ use Exception;
use GuzzleHttp\Client;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Pterodactyl\Exceptions\Service\Helper\CdnVersionFetchingException;
use Pterodactyl\Support\JsonValueGuard;
class SoftwareVersionService
{
@@ -93,7 +92,9 @@ class SoftwareVersionService
$response = $this->client->request('GET', config()->string('pterodactyl.cdn.url'), ['timeout' => 5, 'connect_timeout' => 2]);
if ($response->getStatusCode() === 200) {
return JsonValueGuard::decodeArray8($response->getBody()->__toString());
$data = json_decode($response->getBody()->__toString(), true, flags: JSON_THROW_ON_ERROR);
return is_array($data) ? $data : [];
}
throw new CdnVersionFetchingException;
-134
View File
@@ -1,134 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Support;
use UnexpectedValueException;
final class JsonValueGuard
{
public static function decode(string $encoded, int $maximumDepth = 10): mixed
{
$value = json_decode($encoded, true, flags: JSON_THROW_ON_ERROR);
self::assertValue($value, $maximumDepth);
return $value;
}
public static function decode8(string $encoded): mixed
{
$value = json_decode($encoded, true, flags: JSON_THROW_ON_ERROR);
self::assertValue8($value);
return $value;
}
/** @return array<mixed> */
public static function decodeArray8(string $encoded): array
{
$value = self::decode8($encoded);
throw_unless(is_array($value), UnexpectedValueException::class, 'The JSON value must be an array.');
return $value;
}
public static function assertValue(mixed $value, int $remainingDepth = 10): void
{
if ($value === null || is_bool($value) || is_float($value) || is_int($value) || is_string($value)) {
return;
}
if ($value instanceof JsonEmptyObject) {
return;
}
throw_if(! is_array($value) || $remainingDepth === 0, UnexpectedValueException::class, 'JSON values must be scalars or arrays nested at most 10 levels.');
foreach ($value as $nestedValue) {
self::assertValue($nestedValue, $remainingDepth - 1);
}
}
/** @phpstan-assert array<string, mixed> $value */
public static function assertPayload(mixed $value): void
{
self::assertValue($value);
throw_unless(is_array($value), UnexpectedValueException::class, 'API payloads must be arrays.');
foreach (array_keys($value) as $key) {
throw_unless(is_string($key), UnexpectedValueException::class, 'API payload keys must be strings.');
}
}
/** @phpstan-assert bool|float|int|string|null $value */
public static function assertScalar(mixed $value): void
{
throw_if($value !== null && ! is_bool($value) && ! is_float($value) && ! is_int($value) && ! is_string($value), UnexpectedValueException::class, 'Expected a scalar JSON value.');
}
/** @phpstan-assert string $value */
public static function string(mixed $value): string
{
throw_unless(is_string($value), UnexpectedValueException::class, 'Expected a string value.');
return $value;
}
/**
* @phpstan-assert array<mixed> $value
*
* @return array<mixed>
*/
public static function jsonArray(mixed $value): array
{
self::assertValue($value);
throw_unless(is_array($value), UnexpectedValueException::class, 'Expected a JSON array.');
return $value;
}
/**
* @phpstan-assert list<string> $value
*
* @return list<string>
*/
public static function stringList(mixed $value): array
{
throw_if(! is_array($value) || ! array_is_list($value), UnexpectedValueException::class, 'Expected a list of strings.');
foreach ($value as $item) {
throw_unless(is_string($item), UnexpectedValueException::class, 'Expected a list of strings.');
}
return $value;
}
/** @phpstan-assert array<string, bool|float|int|string|null> $value */
public static function assertScalarPayload(mixed $value): void
{
throw_unless(is_array($value), UnexpectedValueException::class, 'Expected a scalar payload.');
foreach ($value as $key => $item) {
throw_unless(is_string($key), UnexpectedValueException::class, 'Scalar payload keys must be strings.');
self::assertScalar($item);
}
}
/** @phpstan-assert array<string, mixed> $value */
public static function assertPayload9(mixed $value): void
{
self::assertValue($value, 9);
throw_unless(is_array($value), UnexpectedValueException::class, 'OpenAPI schema payloads must be arrays.');
foreach (array_keys($value) as $key) {
throw_unless(is_string($key), UnexpectedValueException::class, 'OpenAPI schema keys must be strings.');
}
}
private static function assertValue8(mixed $value): void
{
self::assertValue($value, 8);
}
}
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace Pterodactyl\Traits\Commands;
use Closure;
use Illuminate\Support\Fluent;
use Pterodactyl\Exceptions\PterodactylException;
trait EnvironmentWriterTrait
@@ -45,7 +44,6 @@ trait EnvironmentWriterTrait
collect($values)->each(function ($value, $key) use (&$saveContents): void {
$key = mb_strtoupper($key);
// SAFETY: EnvironmentValue is restricted to JSON scalars, which have deterministic string representations for .env persistence.
$saveValue = sprintf('%s=%s', $key, $this->escapeEnvironmentValue($value === null ? null : (string) $value));
if (preg_match_all('/^'.$key.'=(.*)$/m', $saveContents) < 1) {
@@ -66,9 +64,9 @@ trait EnvironmentWriterTrait
*/
protected function answer(Closure $prompt): ?string
{
$answer = Fluent::make(['value' => $prompt()]);
$answer = $prompt();
return $answer->get('value') === null ? null : $answer->string('value')->toString();
return is_scalar($answer) ? (string) $answer : null;
}
/**
+1 -2
View File
@@ -7,7 +7,6 @@ namespace Pterodactyl\Traits\Helpers;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Locale;
use Pterodactyl\Support\JsonValueGuard;
trait AvailableLanguages
{
@@ -20,7 +19,7 @@ trait AvailableLanguages
public function getAvailableLanguages(bool $localize = false): array
{
$languages = [];
foreach (JsonValueGuard::stringList(File::directories(resource_path('lang'))) as $path) {
foreach (array_filter(File::directories(resource_path('lang')), is_string(...)) as $path) {
$code = basename($path);
$value = Locale::getDisplayLanguage($code, $localize ? $code : 'en') ?: $code;
$languages[$code] = Str::title($value);
@@ -13,7 +13,6 @@ use Pterodactyl\Models\EggVariable;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Tag;
use Pterodactyl\Support\JsonEmptyObject;
use Pterodactyl\Support\JsonValueGuard;
#[ResponseField('description', nullable: true)]
#[ResponseField('features', nullable: true)]
@@ -125,7 +124,7 @@ class EggTransformer extends BaseAdminTransformer
return null;
}
$value = JsonValueGuard::decode($encoded);
$value = json_decode($encoded, true, flags: JSON_THROW_ON_ERROR);
// Decoding to arrays reads "{}" as an empty list, which would reach the editor as "[]".
return $value === [] && str_starts_with(mb_ltrim($encoded), '{') ? new JsonEmptyObject : $value;
@@ -8,10 +8,10 @@ use Illuminate\Http\Request;
use League\Fractal\Manager;
use Pterodactyl\Extensions\Spatie\Fractalistic\Fractal;
use Pterodactyl\Http\Resources\Api\Includes\IncludeSet;
use Pterodactyl\Support\JsonValueGuard;
use Pterodactyl\Tests\TestCase;
use Random\Engine\Mt19937;
use Random\Randomizer;
use UnexpectedValueException;
uses(TestCase::class);
@@ -59,9 +59,8 @@ function managerIncludes(string|array $includes, int $limit): array
*/
function bindingNames(Request $request): array
{
$requested = JsonValueGuard::stringList(array_values($request->collect('include')->all()));
return collect($requested)
return $request->collect('include')
->map(fn (mixed $value): string => is_string($value) ? $value : throw new UnexpectedValueException('The requested includes must be strings.'))
->flatMap(fn (string $value): array => explode(',', $value))
->map(fn (string $value): string => mb_trim($value))
->filter()
-69
View File
@@ -1,69 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Unit\JsonValueGuardTest;
use JsonException;
use Pterodactyl\Support\JsonEmptyObject;
use Pterodactyl\Support\JsonValueGuard;
use Pterodactyl\Tests\TestCase;
use stdClass;
use UnexpectedValueException;
uses(TestCase::class);
test('decodes nested json values', function () {
expect(JsonValueGuard::decode('{"enabled":true,"limits":[1,2.5,null]}'))->toBe(['enabled' => true, 'limits' => [1, 2.5, null]]);
});
test('accepts a caller defined maximum depth', function () {
$this->expectException(UnexpectedValueException::class);
JsonValueGuard::assertValue([['leaf']], 1);
});
test('decode enforces the caller defined maximum depth', function () {
$this->expectException(UnexpectedValueException::class);
JsonValueGuard::decode(nestedJson(2), 1);
});
test('decode8 accepts eight nested arrays', function () {
expect(JsonValueGuard::decode8(nestedJson(8)))->toBe(nestedValue(8));
});
test('decode8 rejects nine nested arrays', function () {
$this->expectException(UnexpectedValueException::class);
JsonValueGuard::decode8(nestedJson(9));
});
test('rejects objects', function () {
$this->expectException(UnexpectedValueException::class);
JsonValueGuard::assertValue(new stdClass());
});
test('accepts json empty objects', function () {
expect(fn () => JsonValueGuard::assertValue(new JsonEmptyObject()))->not->toThrow(UnexpectedValueException::class);
});
test('string lists preserve sequential string values', function () {
expect(JsonValueGuard::stringList(['first', 'second']))->toBe(['first', 'second']);
});
test('string lists reject invalid shapes', function (mixed $value) {
$this->expectException(UnexpectedValueException::class);
JsonValueGuard::stringList($value);
})->with([
'associative array' => [['name' => 'value']],
'non-string item' => [['value', 1]],
]);
test('rejects invalid json', function () {
$this->expectException(JsonException::class);
JsonValueGuard::decode('{');
});
function nestedJson(int $depth): string
{
return str_repeat('[', $depth).'"leaf"'.str_repeat(']', $depth);
}
function nestedValue(int $depth): array|string
{
$value = 'leaf';
for ($index = 0; $index < $depth; $index++) {
$value = [$value];
}
return $value;
}