diff --git a/app/Actions/Extensions/UpdateExtensionSettings.php b/app/Actions/Extensions/UpdateExtensionSettings.php index 4a9a8e021..1042a1a90 100644 --- a/app/Actions/Extensions/UpdateExtensionSettings.php +++ b/app/Actions/Extensions/UpdateExtensionSettings.php @@ -10,7 +10,7 @@ use Pterodactyl\Services\Extensions\ExtensionSettingsDefinition; final readonly class UpdateExtensionSettings implements UpdatesExtensionSettings { /** - * @param ExtensionSettingValues $settings + * @param array $settings * @return list */ public function update(ExtensionSettingsDefinition $definition, array $settings): array diff --git a/app/Contracts/Extensions/UpdatesExtensionSettings.php b/app/Contracts/Extensions/UpdatesExtensionSettings.php index 96bd35ce6..394b2aeb7 100644 --- a/app/Contracts/Extensions/UpdatesExtensionSettings.php +++ b/app/Contracts/Extensions/UpdatesExtensionSettings.php @@ -9,7 +9,7 @@ use Pterodactyl\Services\Extensions\ExtensionSettingsDefinition; interface UpdatesExtensionSettings { /** - * @param ExtensionSettingValues $settings + * @param array $settings * @return list */ public function update(ExtensionSettingsDefinition $definition, array $settings): array; diff --git a/app/Http/Controllers/Api/Admin/Extensions/ExtensionAdminSettingsController.php b/app/Http/Controllers/Api/Admin/Extensions/ExtensionAdminSettingsController.php index e19e506b9..63def6dd6 100644 --- a/app/Http/Controllers/Api/Admin/Extensions/ExtensionAdminSettingsController.php +++ b/app/Http/Controllers/Api/Admin/Extensions/ExtensionAdminSettingsController.php @@ -8,28 +8,24 @@ use Illuminate\Http\Request; use Pterodactyl\Http\Controllers\Api\Admin\AdminApiController; use Pterodactyl\Services\Extensions\Contracts\ManagesExtensionSettings; use Pterodactyl\Services\Extensions\ExtensionSettingValueGuard; -use Pterodactyl\Support\JsonValueGuard; abstract class ExtensionAdminSettingsController extends AdminApiController { abstract protected function extensionSettings(): ManagesExtensionSettings; /** - * @param ApiPayload9 $extra - * @return ApiPayload + * @param array $extra + * @return array */ protected function settingsPayload(array $extra = []): array { - $payload = [ + return [ ...$extra, 'settings' => $this->extensionSettings()->publicSettings(), ]; - JsonValueGuard::assertPayload($payload); - - return $payload; } - /** @return ApiPayload */ + /** @return array */ protected function updateExtensionSettings(Request $request): array { $data = $request->validate($this->extensionSettings()->validationRules()); diff --git a/app/Http/Requests/Api/Admin/Extensions/UpdateExtensionSettingsRequest.php b/app/Http/Requests/Api/Admin/Extensions/UpdateExtensionSettingsRequest.php index e7e00f4f6..4533c1fb3 100644 --- a/app/Http/Requests/Api/Admin/Extensions/UpdateExtensionSettingsRequest.php +++ b/app/Http/Requests/Api/Admin/Extensions/UpdateExtensionSettingsRequest.php @@ -17,7 +17,7 @@ class UpdateExtensionSettingsRequest extends UpdateExtensionRequest return ['settings' => ['bail', 'present', 'array', new ValidExtensionSettings]]; } - /** @return ExtensionSettingValues */ + /** @return array */ public function settings(ExtensionSettingsDefinition $definition): array { $input = $this->validated('settings'); diff --git a/app/Http/Requests/Concerns/ValidatesExtensionFields.php b/app/Http/Requests/Concerns/ValidatesExtensionFields.php index 199ff8bd9..f82fd724d 100644 --- a/app/Http/Requests/Concerns/ValidatesExtensionFields.php +++ b/app/Http/Requests/Concerns/ValidatesExtensionFields.php @@ -8,8 +8,8 @@ use Illuminate\Contracts\Validation\Validator; use Illuminate\Database\Eloquent\Model; use Pterodactyl\Http\Requests\Api\Application\ApplicationApiRequest; use Pterodactyl\Services\Extensions\ExtensionFields; +use Pterodactyl\Services\Extensions\ExtensionSettingValueGuard; use Pterodactyl\Services\Extensions\ValidatedExtensionValues; -use Pterodactyl\Support\JsonValueGuard; use UnexpectedValueException; /** @@ -86,7 +86,7 @@ trait ValidatesExtensionFields * ignored without being read. * * @param list $running - * @return array> + * @return array> */ private function submittedExtensionValues(Validator $validator, array $running): array { @@ -110,7 +110,8 @@ trait ValidatesExtensionFields } try { - $submitted[$extension] = JsonValueGuard::jsonArray($values); + ExtensionSettingValueGuard::assertValue($values); + $submitted[$extension] = $values; } catch (UnexpectedValueException) { $validator->errors()->add('extensions.'.$extension, sprintf('The %s values are nested too deeply.', $extension)); } diff --git a/app/Services/Extensions/Contracts/ManagesExtensionSettings.php b/app/Services/Extensions/Contracts/ManagesExtensionSettings.php index 2dbf4ae48..2c65fb0aa 100644 --- a/app/Services/Extensions/Contracts/ManagesExtensionSettings.php +++ b/app/Services/Extensions/Contracts/ManagesExtensionSettings.php @@ -6,12 +6,12 @@ namespace Pterodactyl\Services\Extensions\Contracts; interface ManagesExtensionSettings { - /** @return ExtensionSettingValues */ + /** @return array */ public function publicSettings(): array; /** @return NormalizedValidationRules */ public function validationRules(): array; - /** @param ExtensionSettingValues $settings */ + /** @param array $settings */ public function update(array $settings): void; } diff --git a/app/Services/Extensions/ExtensionConsoleRegistry.php b/app/Services/Extensions/ExtensionConsoleRegistry.php index 8a56b0f7e..d428b6f4c 100644 --- a/app/Services/Extensions/ExtensionConsoleRegistry.php +++ b/app/Services/Extensions/ExtensionConsoleRegistry.php @@ -9,7 +9,6 @@ use Illuminate\Console\Application as Artisan; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Contracts\Foundation\Application; use InvalidArgumentException; -use Pterodactyl\Support\JsonValueGuard; use ReflectionClass; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; @@ -76,7 +75,7 @@ final class ExtensionConsoleRegistry if ($names === null) { $command = $this->app->make($class); throw_unless($command instanceof Command, InvalidArgumentException::class, sprintf('Extension "%s" registered "%s", which is not a console command.', $identifier, $class)); - $names = [$command->getName(), ...array_map(JsonValueGuard::string(...), $command->getAliases())]; + $names = [$command->getName(), ...array_filter($command->getAliases(), is_string(...))]; } foreach ($names as $name) { diff --git a/app/Services/Extensions/ExtensionFields.php b/app/Services/Extensions/ExtensionFields.php index 7e24ba0e2..86320f16c 100644 --- a/app/Services/Extensions/ExtensionFields.php +++ b/app/Services/Extensions/ExtensionFields.php @@ -11,8 +11,8 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Validation\Factory as ValidationFactory; use Pterodactyl\Extensions\Fields; use Pterodactyl\Rules\ExtensionFieldValue; -use Pterodactyl\Support\JsonValueGuard; use Throwable; +use UnexpectedValueException; /** * Runs the Fields extensions register for a model: authorizes and validates their @@ -93,7 +93,7 @@ final readonly class ExtensionFields * and its values are refused. * * @param Model|class-string $model the model being updated, or the class being created - * @param array> $submitted each extension's submitted values + * @param array> $submitted each extension's submitted values * @param list $defaults extensions to validate even when $submitted leaves them out */ public function validate(Validator $validator, Model|string $model, array $submitted, bool $applicationApi = false, array $defaults = []): ValidatedExtensionValues @@ -208,7 +208,7 @@ final readonly class ExtensionFields * * @param class-string $fields * @param Model|class-string $model - * @param array $submitted + * @param array $submitted * @return array{array>, ExtensionFieldValues} */ private function check(string $extension, string $fields, Model|string $model, array $submitted): array @@ -268,7 +268,6 @@ final readonly class ExtensionFields $settings = $this->extensions->settings($extension)->fields($model); $values = []; foreach ($this->fieldNames($this->rules($fields, $model)) as $field) { - // SAFETY: the panel only stores values that passed the ExtensionFieldValue rule. $values[$field] = ExtensionSettingValueGuard::fieldValue($settings->get($field)); } @@ -283,8 +282,8 @@ final readonly class ExtensionFields * * @param class-string $fields * @param Model|class-string $model - * @param array $submitted - * @return array + * @param array $submitted + * @return array */ private function withStoredSecrets(string $extension, string $fields, Model|string $model, array $submitted): array { @@ -356,9 +355,20 @@ final readonly class ExtensionFields */ private function secrets(string $fields, Model|string $model): array { - return method_exists($fields, 'secrets') - ? JsonValueGuard::stringList($this->container->call($fields.'@secrets', $this->modelParameters($model))) - : []; + if (! method_exists($fields, 'secrets')) { + return []; + } + + $secrets = $this->container->call($fields.'@secrets', $this->modelParameters($model)); + throw_unless(is_array($secrets), UnexpectedValueException::class, 'Extension field secrets must be a list of field names.'); + + $names = []; + foreach ($secrets as $name) { + throw_unless(is_string($name), UnexpectedValueException::class, 'Extension field secrets must be a list of field names.'); + $names[] = $name; + } + + return $names; } /** diff --git a/app/Services/Extensions/ExtensionHeadTag.php b/app/Services/Extensions/ExtensionHeadTag.php index 968bbc074..8d77f787a 100644 --- a/app/Services/Extensions/ExtensionHeadTag.php +++ b/app/Services/Extensions/ExtensionHeadTag.php @@ -65,7 +65,7 @@ final readonly class ExtensionHeadTag ) {} /** - * @param array $entry `['tag' => 'meta'|'link', => , ...]` + * @param array $entry `['tag' => 'meta'|'link', => , ...]` * * @throws InvalidArgumentException */ diff --git a/app/Services/Extensions/ExtensionHeadTags.php b/app/Services/Extensions/ExtensionHeadTags.php index 95ab6e228..3e42f1e4e 100644 --- a/app/Services/Extensions/ExtensionHeadTags.php +++ b/app/Services/Extensions/ExtensionHeadTags.php @@ -8,7 +8,6 @@ use Closure; use Illuminate\Contracts\Support\Htmlable; use Illuminate\Support\Facades\Cache; use InvalidArgumentException; -use Pterodactyl\Support\JsonValueGuard; use Throwable; use UnexpectedValueException; @@ -33,7 +32,7 @@ final class ExtensionHeadTags implements Htmlable public function __construct(private readonly ExtensionRepository $extensions) {} /** - * @param array|Closure $tags + * @param array|Closure $tags * * @throws InvalidArgumentException|UnexpectedValueException */ @@ -89,7 +88,7 @@ final class ExtensionHeadTags implements Htmlable } /** - * @param array $tags + * @param array $tags * @return list * * @throws InvalidArgumentException|UnexpectedValueException @@ -100,7 +99,8 @@ final class ExtensionHeadTags implements Htmlable $parsed = []; foreach ($tags as $tag) { - $parsed[] = ExtensionHeadTag::fromArray(JsonValueGuard::jsonArray($tag)); + throw_unless(is_array($tag), UnexpectedValueException::class, 'Each head tag must be an array of attributes.'); + $parsed[] = ExtensionHeadTag::fromArray($tag); } return $parsed; @@ -148,12 +148,14 @@ final class ExtensionHeadTags implements Htmlable $key = $this->cacheKey($identifier, $version); $seconds = config()->integer('extensions.head_tags_cache_seconds'); $cached = $seconds > 0 ? Cache::get($key) : null; - if ($cached !== null) { - return $this->parse(JsonValueGuard::jsonArray($cached)); + if (is_array($cached)) { + return $this->parse($cached); } try { - $parsed = $this->parse(JsonValueGuard::jsonArray($tags())); + $resolved = $tags(); + throw_unless(is_array($resolved), UnexpectedValueException::class, 'Head tag callbacks must return a list of tags.'); + $parsed = $this->parse($resolved); } catch (Throwable $throwable) { // Remember the failure too, or a broken callback would run on every page load. $this->remember($key, $seconds, []); diff --git a/app/Services/Extensions/ExtensionIconCatalog.php b/app/Services/Extensions/ExtensionIconCatalog.php index c9efb290b..0933de178 100644 --- a/app/Services/Extensions/ExtensionIconCatalog.php +++ b/app/Services/Extensions/ExtensionIconCatalog.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Pterodactyl\Services\Extensions; use Illuminate\Support\Facades\File; -use Pterodactyl\Support\JsonValueGuard; /** * The lucide icon names this panel build can render for `nav.icon`. The list is @@ -36,6 +35,6 @@ final class ExtensionIconCatalog /** @return list */ public function names(): array { - return JsonValueGuard::stringList(File::json(base_path(self::PATH))); + return array_values(array_filter(File::json(base_path(self::PATH)), is_string(...))); } } diff --git a/app/Services/Extensions/ExtensionLock.php b/app/Services/Extensions/ExtensionLock.php index ec16e7bba..1f68dc293 100644 --- a/app/Services/Extensions/ExtensionLock.php +++ b/app/Services/Extensions/ExtensionLock.php @@ -16,7 +16,7 @@ final class ExtensionLock private int $depth = 0; /** - * @template T of object|ApiValue10|void + * @template T * * @param Closure(): T $callback * @return T diff --git a/app/Services/Extensions/ExtensionManifestValidator.php b/app/Services/Extensions/ExtensionManifestValidator.php index e356e3a19..9ca076fa3 100644 --- a/app/Services/Extensions/ExtensionManifestValidator.php +++ b/app/Services/Extensions/ExtensionManifestValidator.php @@ -12,7 +12,6 @@ use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; use JsonException; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; -use Pterodactyl\Support\JsonValueGuard; use ReflectionClass; use UnexpectedValueException; @@ -234,7 +233,7 @@ class ExtensionManifestValidator * The PSR-4 map of the package's composer.json, which Composer and editors read. It is * used when extension.json declares no `autoload` of its own. * - * @return array + * @return array */ private function composerAutoload(string $directory): array { @@ -244,19 +243,21 @@ class ExtensionManifestValidator } try { - $composer = JsonValueGuard::decodeArray8(File::get($path)); - } catch (JsonException|UnexpectedValueException) { + $composer = json_decode(File::get($path), true, flags: JSON_THROW_ON_ERROR); + } catch (JsonException) { throw new InvalidExtensionException("{$path} is not valid JSON."); } - $psr4 = is_array($composer['autoload'] ?? null) ? $composer['autoload']['psr-4'] ?? [] : []; + throw_unless(is_array($composer), InvalidExtensionException::class, "{$path} is not valid JSON."); + + $psr4 = data_get($composer, 'autoload.psr-4', []); throw_unless(is_array($psr4), InvalidExtensionException::class, 'composer.json "autoload.psr-4" must map "Vendor\\\\Prefix\\\\" to a source directory.'); return $psr4; } /** - * @param array $autoload + * @param array $autoload * @return array */ private function normalizeAutoload(array $autoload, string $field): array diff --git a/app/Services/Extensions/ExtensionPackageLocator.php b/app/Services/Extensions/ExtensionPackageLocator.php index ba6f07ba0..02f1cafc9 100644 --- a/app/Services/Extensions/ExtensionPackageLocator.php +++ b/app/Services/Extensions/ExtensionPackageLocator.php @@ -18,7 +18,7 @@ class ExtensionPackageLocator public const int MAX_ARCHIVE_UNCOMPRESSED_BYTES = 200 * 1024 * 1024; /** - * @template T of object|ApiValue10 + * @template T * * @param Closure(string): T $callback * @return T diff --git a/app/Services/Extensions/ExtensionRepository.php b/app/Services/Extensions/ExtensionRepository.php index 49fd8628c..05a50b287 100644 --- a/app/Services/Extensions/ExtensionRepository.php +++ b/app/Services/Extensions/ExtensionRepository.php @@ -288,7 +288,7 @@ class ExtensionRepository * as ctx.config; with $publicOnly just the ->public() ones, for guests. * Never allowed to break page rendering. * - * @return ExtensionSettingValues + * @return array */ private function frontendConfig(string $identifier, bool $publicOnly): array { diff --git a/app/Services/Extensions/ExtensionSettingDefinition.php b/app/Services/Extensions/ExtensionSettingDefinition.php index 046be94ce..7d72313c3 100644 --- a/app/Services/Extensions/ExtensionSettingDefinition.php +++ b/app/Services/Extensions/ExtensionSettingDefinition.php @@ -21,10 +21,10 @@ class ExtensionSettingDefinition /** Fields whose values are structured or stored elsewhere; these cannot be ->secret(). */ private const array RICH_FIELDS = ['color', 'textarea', 'multiselect', 'list', 'file']; - /** @var (Closure(ExtensionSettingValue): ExtensionSettingValue)|null */ + /** @var (Closure(mixed): mixed)|null */ private ?Closure $normalizer = null; - /** @var (Closure(ExtensionSettingValue): ExtensionSettingValue)|null */ + /** @var (Closure(mixed): mixed)|null */ private ?Closure $publicSerializer = null; private ?string $label = null; @@ -60,7 +60,6 @@ class ExtensionSettingDefinition private array $mimes = []; /** - * @param ExtensionSettingValue $default * @param ValidationRuleSet $rules */ public function __construct( @@ -72,7 +71,6 @@ class ExtensionSettingDefinition ) {} /** - * @param ExtensionSettingValue $default * @param ValidationRuleSet $rules */ public static function make(string $key, string $input, mixed $default, array $rules = [], ?string $public = null): self @@ -80,7 +78,7 @@ class ExtensionSettingDefinition return new self($key, $input, $default, $rules, $public); } - /** @param callable(ExtensionSettingValue): ExtensionSettingValue $normalizer */ + /** @param callable(mixed): mixed $normalizer */ public function normalizeUsing(callable $normalizer): self { $this->normalizer = $normalizer instanceof Closure ? $normalizer : Closure::fromCallable($normalizer); @@ -88,7 +86,7 @@ class ExtensionSettingDefinition return $this; } - /** @param callable(ExtensionSettingValue): ExtensionSettingValue $serializer */ + /** @param callable(mixed): mixed $serializer */ public function publicUsing(callable $serializer): self { $this->publicSerializer = $serializer instanceof Closure ? $serializer : Closure::fromCallable($serializer); @@ -351,9 +349,6 @@ class ExtensionSettingDefinition /** * Coerce a submitted or stored value to the field type's shape, then apply * normalizeUsing(). A value that does not fit falls back to the default. - * - * @param ExtensionSettingValue $value - * @return ExtensionSettingValue */ public function normalize(mixed $value): mixed { @@ -368,10 +363,6 @@ class ExtensionSettingDefinition return $this->normalizer instanceof Closure ? ($this->normalizer)($value) : $value; } - /** - * @param ExtensionSettingValue $value - * @return ExtensionSettingValue - */ public function serializePublic(mixed $value): mixed { if ($this->secret) { @@ -392,7 +383,6 @@ class ExtensionSettingDefinition * `constraints` carries the limits the field's control enforces up front, * and `visibility` who receives the value. * - * @param ExtensionSettingValue $currentValue * @return ExtensionSettingField */ public function describe(mixed $currentValue): array diff --git a/app/Services/Extensions/ExtensionSettingFiles.php b/app/Services/Extensions/ExtensionSettingFiles.php index 6ebf00f16..e48c72c2d 100644 --- a/app/Services/Extensions/ExtensionSettingFiles.php +++ b/app/Services/Extensions/ExtensionSettingFiles.php @@ -147,7 +147,7 @@ class ExtensionSettingFiles continue; } - $value = rescue(fn (): bool|float|int|string|array|null => ExtensionSettingValueGuard::decode($encoded), report: false); + $value = rescue(fn (): mixed => ExtensionSettingValueGuard::decode($encoded), report: false); if (ExtensionSettingValueGuard::fileReference($value) !== null) { $references[] = $row->id; } diff --git a/app/Services/Extensions/ExtensionSettingValueGuard.php b/app/Services/Extensions/ExtensionSettingValueGuard.php index a0d53e1f9..33fa3fbd7 100644 --- a/app/Services/Extensions/ExtensionSettingValueGuard.php +++ b/app/Services/Extensions/ExtensionSettingValueGuard.php @@ -8,7 +8,6 @@ use Closure; use Illuminate\Contracts\Validation\Rule as RuleContract; use Illuminate\Contracts\Validation\ValidationRule as ValidationRuleContract; use Illuminate\Support\Facades\Crypt; -use Pterodactyl\Support\JsonValueGuard; use Stringable; use UnexpectedValueException; @@ -20,21 +19,20 @@ final class ExtensionSettingValueGuard private const string COLOR_PATTERN = '/\A(?:#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|oklch\((?&n)%? (?&n)%? (?&n)(?:deg)?(?: \/ (?&n)%?)?\))\z(?(DEFINE)(?\d{1,3}(?:\.\d{1,6})?|\.\d{1,6}))/'; /** - * @return ExtensionSettingValue + * A stored setting, decrypted first when it is a secret. */ - public static function decode(string $encoded, bool $secret = false): bool|float|int|string|array|null + public static function decode(string $encoded, bool $secret = false): mixed { - $value = JsonValueGuard::decode($encoded); + $value = json_decode($encoded, true, flags: JSON_THROW_ON_ERROR); if (! $secret) { return $value; } throw_unless(is_string($value), UnexpectedValueException::class, 'Encrypted extension settings must be strings.'); - return JsonValueGuard::decode(Crypt::decryptString($value)); + return json_decode(Crypt::decryptString($value), true, flags: JSON_THROW_ON_ERROR); } - /** @param ExtensionSettingValue $value */ public static function encode(mixed $value, bool $secret = false): string { $encoded = json_encode($value, JSON_THROW_ON_ERROR); @@ -43,14 +41,25 @@ final class ExtensionSettingValueGuard } /** - * @phpstan-assert ExtensionSettingValue $value + * Rejects what JSON cannot hold, such as objects and uploaded files, and nesting + * deeper than ten levels. */ public static function assertValue(mixed $value, int $remainingDepth = 10): void { - JsonValueGuard::assertValue($value, $remainingDepth); + if (! is_array($value)) { + throw_unless($value === null || is_scalar($value), UnexpectedValueException::class, 'Extension setting values must be JSON scalars or arrays.'); + + return; + } + + throw_if($remainingDepth === 0, UnexpectedValueException::class, 'Extension setting values may be nested at most 10 levels.'); + + foreach ($value as $item) { + self::assertValue($item, $remainingDepth - 1); + } } - /** @phpstan-assert ExtensionSettingValues $value */ + /** @phpstan-assert array $value */ public static function assertValues(mixed $value): void { throw_unless(is_array($value), UnexpectedValueException::class, 'Extension settings must be an object.'); @@ -159,10 +168,8 @@ final class ExtensionSettingValueGuard /** * The canonical form of a colour setting (lower case, single spaces), or * null when the value is not a colour this panel accepts. - * - * @param ExtensionSettingValue $value */ - public static function color(bool|float|int|string|array|null $value): ?string + public static function color(mixed $value): ?string { if (! is_string($value) || mb_strlen($value) > 64) { return null; @@ -177,10 +184,8 @@ final class ExtensionSettingValueGuard /** * A multi-line text setting with its line endings normalized, or null when * the value is not a string. - * - * @param ExtensionSettingValue $value */ - public static function text(bool|float|int|string|array|null $value): ?string + public static function text(mixed $value): ?string { return is_string($value) ? str_replace(["\r\n", "\r"], "\n", $value) : null; } @@ -189,10 +194,9 @@ final class ExtensionSettingValueGuard * The string items of a list setting, in order, or null when the value is * not a list. * - * @param ExtensionSettingValue $value * @return list|null */ - public static function strings(bool|float|int|string|array|null $value): ?array + public static function strings(mixed $value): ?array { if (! is_array($value) || ! array_is_list($value)) { return null; @@ -206,11 +210,10 @@ final class ExtensionSettingValueGuard * declaration order, or null when the value is not a list. Anything that is * not a declared choice is dropped. * - * @param ExtensionSettingValue $value * @param list $choices * @return list|null */ - public static function choices(bool|float|int|string|array|null $value, array $choices): ?array + public static function choices(mixed $value, array $choices): ?array { if (! is_array($value) || ! array_is_list($value)) { return null; @@ -219,12 +222,10 @@ final class ExtensionSettingValueGuard $selected = []; foreach ($value as $item) { if (is_string($item) || is_int($item)) { - // SAFETY: only strings and integers reach this cast, and both stringify losslessly. $selected[(string) $item] = true; } } - // SAFETY: declared choices are strings or integers, which stringify losslessly. return array_values(array_filter($choices, fn (string|int $choice): bool => isset($selected[(string) $choice]))); } @@ -233,10 +234,9 @@ final class ExtensionSettingValueGuard * stores: text is a string or a number, a select value is identical to one of * the declared choices. Null always fits; other fields have their own checks. * - * @param ExtensionSettingValue $value * @param list $choices */ - public static function fitsField(string $field, bool|float|int|string|array|null $value, array $choices = []): bool + public static function fitsField(string $field, mixed $value, array $choices = []): bool { return $value === null || match ($field) { 'text', 'password' => is_string($value) || is_int($value) || is_float($value), @@ -249,16 +249,13 @@ final class ExtensionSettingValueGuard /** * The stored name of an uploaded settings file, or null when the value is not one. - * - * @param ExtensionSettingValue $value */ - public static function fileReference(bool|float|int|string|array|null $value): ?string + public static function fileReference(mixed $value): ?string { return is_string($value) && preg_match(ExtensionSettingFiles::NAME_PATTERN, $value) === 1 ? $value : null; } /** - * @param ExtensionSettingValue $value * @param 'string'|'number'|'boolean'|'array'|'object'|'null'|'json' $type */ public static function assertFrontendType(mixed $value, string $type): void diff --git a/app/Services/Extensions/ExtensionSettings.php b/app/Services/Extensions/ExtensionSettings.php index a8bcaac55..c25e7431e 100644 --- a/app/Services/Extensions/ExtensionSettings.php +++ b/app/Services/Extensions/ExtensionSettings.php @@ -38,7 +38,7 @@ class ExtensionSettings 'database_host' => DatabaseHost::class, ]; - /** @var ExtensionSettingValues|null all rows, loaded once per instance on first read */ + /** @var array|null all rows, loaded once per instance on first read */ private ?array $loaded = null; public function __construct( @@ -118,10 +118,6 @@ class ExtensionSettings return $this->for($server); } - /** - * @param ExtensionSettingValue $default - * @return ExtensionSettingValue - */ public function get(string $key, mixed $default = null): mixed { $loaded = $this->loaded ??= $this->all(); @@ -129,7 +125,7 @@ class ExtensionSettings return array_key_exists($key, $loaded) ? $loaded[$key] : $default; } - /** @return ExtensionSettingValues */ + /** @return array */ public function all(): array { $values = []; @@ -140,26 +136,24 @@ class ExtensionSettings return $this->loaded = $values; } - /** @param ExtensionSettingValue $value */ public function set(string $key, mixed $value): void { $this->setMany([$key => $value]); } - /** @param ExtensionSettingValue $value */ public function setSecret(string $key, mixed $value): void { $this->setManySecrets([$key => $value], [$key]); } - /** @param ExtensionSettingValues $values */ + /** @param array $values */ public function setMany(array $values): void { $this->persist($values, []); } /** - * @param ExtensionSettingValues $values + * @param array $values * @param list $secretKeys */ public function setManySecrets(array $values, array $secretKeys): void @@ -176,7 +170,7 @@ class ExtensionSettings unset($this->loaded[$key]); } - /** @return ExtensionSettingValues keys matching the prefix, prefix stripped */ + /** @return array keys matching the prefix, prefix stripped */ public function getByPrefix(string $prefix): array { return $this->query() @@ -198,7 +192,7 @@ class ExtensionSettings } /** - * @param ExtensionSettingValues $values + * @param array $values * @param list $secretKeys */ private function persist(array $values, array $secretKeys): void diff --git a/app/Services/Extensions/ExtensionSettingsDefinition.php b/app/Services/Extensions/ExtensionSettingsDefinition.php index e1fa2d3c5..855148c1e 100644 --- a/app/Services/Extensions/ExtensionSettingsDefinition.php +++ b/app/Services/Extensions/ExtensionSettingsDefinition.php @@ -44,8 +44,6 @@ class ExtensionSettingsDefinition implements ManagesExtensionSettings /** * The setting's current value. A file setting reads as the public URL of * its uploaded file, or its default while nothing is uploaded. - * - * @return ExtensionSettingValue */ public function get(string $key): mixed { @@ -63,7 +61,7 @@ class ExtensionSettingsDefinition implements ManagesExtensionSettings return $definition->normalize($this->settings->get($definition->key, $definition->default)); } - /** @return ExtensionSettingValues */ + /** @return array */ public function publicSettings(): array { $values = []; @@ -91,7 +89,7 @@ class ExtensionSettingsDefinition implements ManagesExtensionSettings return $rules; } - /** @param ExtensionSettingValues $input */ + /** @param array $input */ public function update(array $input): void { $input = $this->withoutBlankSecrets($input); @@ -121,8 +119,8 @@ class ExtensionSettingsDefinition implements ManagesExtensionSettings * Drops secret inputs that would replace the stored value with nothing or with * its own mask, whatever the field type, so they keep the stored value. * - * @param ExtensionSettingValues $input - * @return ExtensionSettingValues + * @param array $input + * @return array */ public function withoutBlankSecrets(array $input): array { @@ -182,7 +180,7 @@ class ExtensionSettingsDefinition implements ManagesExtensionSettings * are visible to every logged-in user. With $publicOnly, only those also * marked ->public(), which is what visitors who are not signed in receive. * - * @return ExtensionSettingValues + * @return array */ public function frontendConfig(bool $publicOnly = false): array { diff --git a/phpstan.neon b/phpstan.neon index 11987f988..2181281b3 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -73,17 +73,15 @@ parameters: GeneralSettingsData: "array{'app:name': string, 'pterodactyl:auth:2fa_required': int, 'app:locale': string}" AdvancedSettingsData: "array{'recaptcha:enabled': string, 'recaptcha:secret_key'?: string, 'recaptcha:website_key': string, 'pterodactyl:guzzle:timeout': int, 'pterodactyl:guzzle:connect_timeout': int, 'pterodactyl:client_features:allocations:enabled': string, 'pterodactyl:client_features:allocations:range_start': int|null, 'pterodactyl:client_features:allocations:range_end': int|null}" MailSettingsData: "array{'mail:mailers:smtp:host': string, 'mail:mailers:smtp:port': int, 'mail:mailers:smtp:encryption': string|null, 'mail:mailers:smtp:username': string|null, 'mail:from:address': string, 'mail:from:name': string|null, 'mail:mailers:smtp:password'?: string}" - ExtensionSettingValue: 'JsonValue' - ExtensionSettingValues: 'array' - ExtensionSettingField: 'array{input: string, label: string, help: string|null, tab: string|null, field: string, options: list, value: ExtensionSettingValue, constraints: array{max_length: int|null, max_items: int|null, max_kilobytes: int|null, accept: list}, visibility: ''admin''|''frontend''|''public''}' - ExtensionFieldValue: 'ApiScalar|list' + ExtensionSettingField: 'array{input: string, label: string, help: string|null, tab: string|null, field: string, options: list, value: mixed, constraints: array{max_length: int|null, max_items: int|null, max_kilobytes: int|null, accept: list}, visibility: ''admin''|''frontend''|''public''}' + ExtensionFieldValue: 'bool|float|int|string|list|null' ExtensionFieldValues: 'array' ExtensionFieldInput: 'array' ExtensionFieldEntry: 'array{fields: class-string<\Pterodactyl\Extensions\Fields>, registration: \Pterodactyl\Services\Extensions\ExtensionRegistration, applicationApi: bool}' ExtensionScreenMatcher: 'array{any?: list, all?: list}' ExtensionScreenCondition: 'array{eggFeatures?: ExtensionScreenMatcher, eggTags?: ExtensionScreenMatcher, match?: string, runtime?: bool}' ExtensionScreenDefinition: 'array{id: string, area: string, path: string, parent?: string, nav?: array{label: string, exact?: bool, params?: array, order?: int, group?: string, badge?: string, icon?: string}, permission?: list, when?: ExtensionScreenCondition}' - ExtensionManifestInput: 'array{id: string, name: string, version: string, requires?: array{panel?: string, sdk?: string, php?: string, extensions?: array}, description?: string|null, author?: string|null, provider?: string|null, icon?: string|null, autoload?: array, ui?: array{entry: string, mode?: string, prefix?: string, screens?: list, components?: list}, routes?: array{root?: list}, ...}' + ExtensionManifestInput: 'array{id: string, name: string, version: string, requires?: array{panel?: string, sdk?: string, php?: string, extensions?: array}, description?: string|null, author?: string|null, provider?: string|null, icon?: string|null, autoload?: array, ui?: array{entry: string, mode?: string, prefix?: string, screens?: list, components?: list}, routes?: array{root?: list}, ...}' paths: - app ignoreErrors: diff --git a/tests/Unit/Services/Extensions/ExtensionSettingValueGuardTest.php b/tests/Unit/Services/Extensions/ExtensionSettingValueGuardTest.php index ca8927e18..088f0cf69 100644 --- a/tests/Unit/Services/Extensions/ExtensionSettingValueGuardTest.php +++ b/tests/Unit/Services/Extensions/ExtensionSettingValueGuardTest.php @@ -10,10 +10,22 @@ use stdClass; use UnexpectedValueException; uses(TestCase::class); -test('delegates decoding and assertion to the json value guard', function () { +test('decodes stored values and rejects what json cannot hold', function () { expect(ExtensionSettingValueGuard::decode('{"enabled":true,"limits":[1,2.5,null]}'))->toBe(['enabled' => true, 'limits' => [1, 2.5, null]]); expect(fn () => ExtensionSettingValueGuard::assertValue(new stdClass()))->toThrow(UnexpectedValueException::class); }); +test('decodes encrypted values', function () { + $encoded = ExtensionSettingValueGuard::encode(['key' => 'secret'], secret: true); + + expect($encoded)->not->toContain('secret') + ->and(ExtensionSettingValueGuard::decode($encoded, secret: true))->toBe(['key' => 'secret']); +}); +test('values may be nested at most ten levels', function () { + $nested = fn (int $depth): array => array_reduce(range(1, $depth), fn (mixed $value): array => [$value], 'leaf'); + + expect(fn () => ExtensionSettingValueGuard::assertValue($nested(10)))->not->toThrow(UnexpectedValueException::class) + ->and(fn () => ExtensionSettingValueGuard::assertValue($nested(11)))->toThrow(UnexpectedValueException::class); +}); test('color accepts hex and oklch colours only', function (mixed $value, ?string $expected) { expect(ExtensionSettingValueGuard::color($value))->toBe($expected); })->with([