diff --git a/app/Actions/Activity/IngestActivityLogs.php b/app/Actions/Activity/IngestActivityLogs.php index 848c11c66..1413ca16d 100644 --- a/app/Actions/Activity/IngestActivityLogs.php +++ b/app/Actions/Activity/IngestActivityLogs.php @@ -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, ip: string|null, timestamp: string} + * @phpstan-type ActivityEvent array{user: string|null, server: string, event: string, metadata: array, 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(), ]; diff --git a/app/Actions/Allocations/CreateAllocations.php b/app/Actions/Allocations/CreateAllocations.php index 73d72839b..8d4210f80 100644 --- a/app/Actions/Allocations/CreateAllocations.php +++ b/app/Actions/Allocations/CreateAllocations.php @@ -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]; diff --git a/app/Actions/Backups/InitiateBackup.php b/app/Actions/Backups/InitiateBackup.php index 76bdb10b5..81012b600 100644 --- a/app/Actions/Backups/InitiateBackup.php +++ b/app/Actions/Backups/InitiateBackup.php @@ -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); } } diff --git a/app/Actions/Databases/CreateDatabase.php b/app/Actions/Databases/CreateDatabase.php index 2114f3d52..d0aed53a3 100644 --- a/app/Actions/Databases/CreateDatabase.php +++ b/app/Actions/Databases/CreateDatabase.php @@ -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); diff --git a/app/Actions/Files/PullFile.php b/app/Actions/Files/PullFile.php index 9d7643b27..5f13e0595 100644 --- a/app/Actions/Files/PullFile.php +++ b/app/Actions/Files/PullFile.php @@ -11,7 +11,7 @@ use Pterodactyl\Models\Server; final readonly class PullFile implements PullsFiles { - /** @param array $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); diff --git a/app/Actions/Servers/CreateServer.php b/app/Actions/Servers/CreateServer.php index 6271e8f54..702c23a43 100644 --- a/app/Actions/Servers/CreateServer.php +++ b/app/Actions/Servers/CreateServer.php @@ -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, 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, 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, diff --git a/app/Actions/Servers/UpdateServerStartup.php b/app/Actions/Servers/UpdateServerStartup.php index 24add6a53..7ded96e11 100644 --- a/app/Actions/Servers/UpdateServerStartup.php +++ b/app/Actions/Servers/UpdateServerStartup.php @@ -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, 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); } } diff --git a/app/Actions/Users/ToggleTwoFactor.php b/app/Actions/Users/ToggleTwoFactor.php index 2fb0e143b..5334fa8f3 100644 --- a/app/Actions/Users/ToggleTwoFactor.php +++ b/app/Actions/Users/ToggleTwoFactor.php @@ -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')); diff --git a/app/Console/Commands/Location/MakeLocationCommand.php b/app/Console/Commands/Location/MakeLocationCommand.php index 850b9a3b1..b18628998 100644 --- a/app/Console/Commands/Location/MakeLocationCommand.php +++ b/app/Console/Commands/Location/MakeLocationCommand.php @@ -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); diff --git a/app/Console/Commands/Node/MakeNodeCommand.php b/app/Console/Commands/Node/MakeNodeCommand.php index 565675a38..8577f746b 100644 --- a/app/Console/Commands/Node/MakeNodeCommand.php +++ b/app/Console/Commands/Node/MakeNodeCommand.php @@ -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); diff --git a/app/Console/Commands/UpgradeCommand.php b/app/Console/Commands/UpgradeCommand.php index 828aaae56..7e6603f37 100644 --- a/app/Console/Commands/UpgradeCommand.php +++ b/app/Console/Commands/UpgradeCommand.php @@ -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 [{$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 [{$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.'); } } diff --git a/app/Console/Commands/User/DeleteUserCommand.php b/app/Console/Commands/User/DeleteUserCommand.php index 120a1209e..a7a8e3624 100644 --- a/app/Console/Commands/User/DeleteUserCommand.php +++ b/app/Console/Commands/User/DeleteUserCommand.php @@ -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%") diff --git a/app/Console/Commands/User/MakeUserCommand.php b/app/Console/Commands/User/MakeUserCommand.php index af47ba067..7184b8e01 100644 --- a/app/Console/Commands/User/MakeUserCommand.php +++ b/app/Console/Commands/User/MakeUserCommand.php @@ -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); diff --git a/app/Contracts/Files/PullsFiles.php b/app/Contracts/Files/PullsFiles.php index 916b028e0..403189b2e 100644 --- a/app/Contracts/Files/PullsFiles.php +++ b/app/Contracts/Files/PullsFiles.php @@ -8,6 +8,6 @@ use Pterodactyl\Models\Server; interface PullsFiles { - /** @param array $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; } diff --git a/app/Data/AllocationRange.php b/app/Data/AllocationRange.php index a2275de06..640d1d7fb 100644 --- a/app/Data/AllocationRange.php +++ b/app/Data/AllocationRange.php @@ -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; } diff --git a/app/Data/EggCatalogEntry.php b/app/Data/EggCatalogEntry.php index b79568452..5cdf39bc2 100644 --- a/app/Data/EggCatalogEntry.php +++ b/app/Data/EggCatalogEntry.php @@ -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) { diff --git a/app/Data/Extensions/ExtensionJobSnapshot.php b/app/Data/Extensions/ExtensionJobSnapshot.php index 6ecc1fb2f..3ae242ce0 100644 --- a/app/Data/Extensions/ExtensionJobSnapshot.php +++ b/app/Data/Extensions/ExtensionJobSnapshot.php @@ -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 { diff --git a/app/Data/LoginResult.php b/app/Data/LoginResult.php index 8cd55d9b9..bddbecf7c 100644 --- a/app/Data/LoginResult.php +++ b/app/Data/LoginResult.php @@ -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} + * @return array{complete: false, confirmation_token: string|null}|array{complete: true, intended: string, user: array} */ public function toResponseData(): array { diff --git a/app/Extensions/Illuminate/Auth/Passwords/PasswordBroker.php b/app/Extensions/Illuminate/Auth/Passwords/PasswordBroker.php index 98ad23d4c..bc4c1b261 100644 --- a/app/Extensions/Illuminate/Auth/Passwords/PasswordBroker.php +++ b/app/Extensions/Illuminate/Auth/Passwords/PasswordBroker.php @@ -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); diff --git a/app/Http/Controllers/Api/Admin/ApiKeys/ApiKeyController.php b/app/Http/Controllers/Api/Admin/ApiKeys/ApiKeyController.php index faf096711..477fcf184 100644 --- a/app/Http/Controllers/Api/Admin/ApiKeys/ApiKeyController.php +++ b/app/Http/Controllers/Api/Admin/ApiKeys/ApiKeyController.php @@ -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); } diff --git a/app/Http/Controllers/Api/Admin/Nodes/AllocationController.php b/app/Http/Controllers/Api/Admin/Nodes/AllocationController.php index 5340cbef2..895b8a10a 100644 --- a/app/Http/Controllers/Api/Admin/Nodes/AllocationController.php +++ b/app/Http/Controllers/Api/Admin/Nodes/AllocationController.php @@ -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'); } diff --git a/app/Http/Controllers/Api/Admin/Nodes/DeployTokenController.php b/app/Http/Controllers/Api/Admin/Nodes/DeployTokenController.php index 7074bb5ae..e507c97fd 100644 --- a/app/Http/Controllers/Api/Admin/Nodes/DeployTokenController.php +++ b/app/Http/Controllers/Api/Admin/Nodes/DeployTokenController.php @@ -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'), ]); diff --git a/app/Http/Controllers/Api/Admin/Settings/AdvancedController.php b/app/Http/Controllers/Api/Admin/Settings/AdvancedController.php index 5cbb899b3..e48446425 100644 --- a/app/Http/Controllers/Api/Admin/Settings/AdvancedController.php +++ b/app/Http/Controllers/Api/Admin/Settings/AdvancedController.php @@ -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); } diff --git a/app/Http/Controllers/Api/Admin/Settings/GeneralController.php b/app/Http/Controllers/Api/Admin/Settings/GeneralController.php index e9c4ce8fa..3c4baf3e4 100644 --- a/app/Http/Controllers/Api/Admin/Settings/GeneralController.php +++ b/app/Http/Controllers/Api/Admin/Settings/GeneralController.php @@ -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); } diff --git a/app/Http/Controllers/Api/Admin/Settings/MailController.php b/app/Http/Controllers/Api/Admin/Settings/MailController.php index 916c9f503..f75d05dd8 100644 --- a/app/Http/Controllers/Api/Admin/Settings/MailController.php +++ b/app/Http/Controllers/Api/Admin/Settings/MailController.php @@ -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); } diff --git a/app/Http/Controllers/Api/Application/Nodes/AllocationController.php b/app/Http/Controllers/Api/Application/Nodes/AllocationController.php index 1a3824b27..57e99fff6 100644 --- a/app/Http/Controllers/Api/Application/Nodes/AllocationController.php +++ b/app/Http/Controllers/Api/Application/Nodes/AllocationController.php @@ -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'); } diff --git a/app/Http/Controllers/Api/Client/Servers/FileController.php b/app/Http/Controllers/Api/Client/Servers/FileController.php index 8519f4a29..37fa61819 100644 --- a/app/Http/Controllers/Api/Client/Servers/FileController.php +++ b/app/Http/Controllers/Api/Client/Servers/FileController.php @@ -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); } diff --git a/app/Http/Controllers/Auth/LoginCheckpointController.php b/app/Http/Controllers/Auth/LoginCheckpointController.php index 76a10c5a6..86fa7a8cb 100644 --- a/app/Http/Controllers/Auth/LoginCheckpointController.php +++ b/app/Http/Controllers/Auth/LoginCheckpointController.php @@ -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; diff --git a/app/Http/Middleware/Api/AuthenticateIPAccess.php b/app/Http/Middleware/Api/AuthenticateIPAccess.php index dc0322298..78a7eb06b 100644 --- a/app/Http/Middleware/Api/AuthenticateIPAccess.php +++ b/app/Http/Middleware/Api/AuthenticateIPAccess.php @@ -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); } diff --git a/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php b/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php index 60d880336..a1f2fb9c9 100644 --- a/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php +++ b/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php @@ -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; } } diff --git a/app/Http/Requests/Api/Application/Servers/StoreServerRequest.php b/app/Http/Requests/Api/Application/Servers/StoreServerRequest.php index 677df4779..57bfef6cb 100644 --- a/app/Http/Requests/Api/Application/Servers/StoreServerRequest.php +++ b/app/Http/Requests/Api/Application/Servers/StoreServerRequest.php @@ -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)) { diff --git a/app/Http/Requests/Concerns/FiltersDeployTags.php b/app/Http/Requests/Concerns/FiltersDeployTags.php index 8da053143..51bd068c0 100644 --- a/app/Http/Requests/Concerns/FiltersDeployTags.php +++ b/app/Http/Requests/Concerns/FiltersDeployTags.php @@ -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; } } diff --git a/app/Http/Resources/Api/Admin/ServerDatabaseResource.php b/app/Http/Resources/Api/Admin/ServerDatabaseResource.php index 5a355859b..71ffca7f5 100644 --- a/app/Http/Resources/Api/Admin/ServerDatabaseResource.php +++ b/app/Http/Resources/Api/Admin/ServerDatabaseResource.php @@ -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'); } } diff --git a/app/Http/Resources/Api/Client/DatabaseResource.php b/app/Http/Resources/Api/Client/DatabaseResource.php index 6cd8b9d1e..ca886dc07 100644 --- a/app/Http/Resources/Api/Client/DatabaseResource.php +++ b/app/Http/Resources/Api/Client/DatabaseResource.php @@ -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'); } } diff --git a/app/Http/Resources/Api/Includes/IncludeSet.php b/app/Http/Resources/Api/Includes/IncludeSet.php index 07d187c04..e6eaa7069 100644 --- a/app/Http/Resources/Api/Includes/IncludeSet.php +++ b/app/Http/Resources/Api/Includes/IncludeSet.php @@ -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() diff --git a/app/Jobs/Schedule/RunTaskJob.php b/app/Jobs/Schedule/RunTaskJob.php index 1775cc0f3..e6ff19655 100644 --- a/app/Jobs/Schedule/RunTaskJob.php +++ b/app/Jobs/Schedule/RunTaskJob.php @@ -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) diff --git a/app/Models/Node.php b/app/Models/Node.php index bb570aa46..b2cc4b7dc 100644 --- a/app/Models/Node.php +++ b/app/Models/Node.php @@ -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; } diff --git a/app/Models/Server.php b/app/Models/Server.php index f680e9678..9dcdc0a4d 100644 --- a/app/Models/Server.php +++ b/app/Models/Server.php @@ -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(); diff --git a/app/Models/Tag.php b/app/Models/Tag.php index 9592af6b9..9993efefa 100644 --- a/app/Models/Tag.php +++ b/app/Models/Tag.php @@ -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); diff --git a/app/Models/Traits/HasAccessTokens.php b/app/Models/Traits/HasAccessTokens.php index 9ab3b5aec..47209e8a0 100644 --- a/app/Models/Traits/HasAccessTokens.php +++ b/app/Models/Traits/HasAccessTokens.php @@ -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, diff --git a/app/Models/User.php b/app/Models/User.php index 2b7a17968..617c5bec4 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -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|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 + * @return array */ 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]; } /** diff --git a/app/Services/Acl/Api/AdminAcl.php b/app/Services/Acl/Api/AdminAcl.php index b4e1fce8e..bbfe77904 100644 --- a/app/Services/Acl/Api/AdminAcl.php +++ b/app/Services/Acl/Api/AdminAcl.php @@ -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); } /** diff --git a/app/Services/Daemon/DaemonConnection.php b/app/Services/Daemon/DaemonConnection.php index 50515f0a4..8cec91fdf 100644 --- a/app/Services/Daemon/DaemonConnection.php +++ b/app/Services/Daemon/DaemonConnection.php @@ -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, query?: array, 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(); diff --git a/app/Services/Daemon/FilesClient.php b/app/Services/Daemon/FilesClient.php index f6e96fc15..58bb2f19f 100644 --- a/app/Services/Daemon/FilesClient.php +++ b/app/Services/Daemon/FilesClient.php @@ -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 $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 $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); diff --git a/app/Services/Daemon/NodeClient.php b/app/Services/Daemon/NodeClient.php index 4ce3d250e..e2d5ca81c 100644 --- a/app/Services/Daemon/NodeClient.php +++ b/app/Services/Daemon/NodeClient.php @@ -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 */ + /** @return array */ 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 diff --git a/app/Services/Daemon/ServerClient.php b/app/Services/Daemon/ServerClient.php index d10c3ff29..697e4155b 100644 --- a/app/Services/Daemon/ServerClient.php +++ b/app/Services/Daemon/ServerClient.php @@ -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|null} $data */ return $data['data'] ?? []; } diff --git a/app/Services/Deployment/AllocationSelectionService.php b/app/Services/Deployment/AllocationSelectionService.php index dffe53e41..e731c9633 100644 --- a/app/Services/Deployment/AllocationSelectionService.php +++ b/app/Services/Deployment/AllocationSelectionService.php @@ -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]]; } } diff --git a/app/Services/Deployment/FindViableNodesService.php b/app/Services/Deployment/FindViableNodesService.php index a6e0a5d36..d67a3268f 100644 --- a/app/Services/Deployment/FindViableNodesService.php +++ b/app/Services/Deployment/FindViableNodesService.php @@ -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; } diff --git a/app/Services/Eggs/EggImportData.php b/app/Services/Eggs/EggImportData.php index 7cd3f853a..903711e3c 100644 --- a/app/Services/Eggs/EggImportData.php +++ b/app/Services/Eggs/EggImportData.php @@ -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 diff --git a/app/Services/Extensions/ExtensionJobProgress.php b/app/Services/Extensions/ExtensionJobProgress.php index 9c3ebecc3..fd96bd1a4 100644 --- a/app/Services/Extensions/ExtensionJobProgress.php +++ b/app/Services/Extensions/ExtensionJobProgress.php @@ -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; } diff --git a/app/Services/Helpers/AssetHashService.php b/app/Services/Helpers/AssetHashService.php index d4589d462..77f3d9f66 100644 --- a/app/Services/Helpers/AssetHashService.php +++ b/app/Services/Helpers/AssetHashService.php @@ -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) { diff --git a/app/Services/Helpers/SoftwareVersionService.php b/app/Services/Helpers/SoftwareVersionService.php index 1afcdd84f..2b02baecc 100644 --- a/app/Services/Helpers/SoftwareVersionService.php +++ b/app/Services/Helpers/SoftwareVersionService.php @@ -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; diff --git a/app/Support/JsonValueGuard.php b/app/Support/JsonValueGuard.php deleted file mode 100644 index a86382448..000000000 --- a/app/Support/JsonValueGuard.php +++ /dev/null @@ -1,134 +0,0 @@ - */ - 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 $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 $value - * - * @return array - */ - 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 $value - * - * @return list - */ - 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 $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 $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); - } -} diff --git a/app/Traits/Commands/EnvironmentWriterTrait.php b/app/Traits/Commands/EnvironmentWriterTrait.php index c50acb7cd..23463a3ea 100644 --- a/app/Traits/Commands/EnvironmentWriterTrait.php +++ b/app/Traits/Commands/EnvironmentWriterTrait.php @@ -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; } /** diff --git a/app/Traits/Helpers/AvailableLanguages.php b/app/Traits/Helpers/AvailableLanguages.php index 2c32516c2..14fc73e12 100644 --- a/app/Traits/Helpers/AvailableLanguages.php +++ b/app/Traits/Helpers/AvailableLanguages.php @@ -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); diff --git a/app/Transformers/Api/Admin/EggTransformer.php b/app/Transformers/Api/Admin/EggTransformer.php index 590e6802b..274bc2787 100644 --- a/app/Transformers/Api/Admin/EggTransformer.php +++ b/app/Transformers/Api/Admin/EggTransformer.php @@ -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; diff --git a/tests/Unit/Http/Resources/Api/Includes/IncludeSetTest.php b/tests/Unit/Http/Resources/Api/Includes/IncludeSetTest.php index a1599dea6..021029744 100644 --- a/tests/Unit/Http/Resources/Api/Includes/IncludeSetTest.php +++ b/tests/Unit/Http/Resources/Api/Includes/IncludeSetTest.php @@ -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() diff --git a/tests/Unit/JsonValueGuardTest.php b/tests/Unit/JsonValueGuardTest.php deleted file mode 100644 index fcb60b19a..000000000 --- a/tests/Unit/JsonValueGuardTest.php +++ /dev/null @@ -1,69 +0,0 @@ -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; -}