diff --git a/app/Actions/Backups/InitiateBackup.php b/app/Actions/Backups/InitiateBackup.php index 8e37398eb..c3385d60f 100644 --- a/app/Actions/Backups/InitiateBackup.php +++ b/app/Actions/Backups/InitiateBackup.php @@ -8,6 +8,7 @@ use Carbon\CarbonImmutable; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; +use Illuminate\Support\Fluent; use Illuminate\Validation\ValidationException; use Pterodactyl\Contracts\Backups\DeletesBackups; use Pterodactyl\Contracts\Backups\InitiatesBackups; @@ -17,7 +18,6 @@ use Pterodactyl\Facades\Activity; use Pterodactyl\Facades\Daemon; use Pterodactyl\Models\Backup; use Pterodactyl\Models\Server; -use Pterodactyl\Support\JsonValueGuard; use Ramsey\Uuid\Uuid; use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException; use Throwable; @@ -115,8 +115,9 @@ final class InitiateBackup implements InitiatesBackups $attributes = self::attributes(['name' => $name, 'is_locked' => $this->isLocked, 'ignored_files' => $this->ignoredFiles]); [$backup, $rotated] = DB::transaction(/** @return array{Backup, Collection} */ function () use ($server, $attributes, $override): array { - $limit = JsonValueGuard::integer(config('backups.throttles.limit')); - $period = JsonValueGuard::integer(config('backups.throttles.period')); + $throttles = Fluent::make(config()->array('backups.throttles')); + $limit = $throttles->integer('limit'); + $period = $throttles->integer('period'); if ($period > 0) { $previousCount = $server->backups() ->withTrashed() diff --git a/app/Actions/Backups/PresignBackupUpload.php b/app/Actions/Backups/PresignBackupUpload.php index ab92e48ab..63ed025c6 100644 --- a/app/Actions/Backups/PresignBackupUpload.php +++ b/app/Actions/Backups/PresignBackupUpload.php @@ -9,7 +9,6 @@ use Pterodactyl\Contracts\Backups\PresignsBackupUploads; use Pterodactyl\Extensions\Backups\BackupManager; use Pterodactyl\Extensions\Filesystem\S3Filesystem; use Pterodactyl\Models\Backup; -use Pterodactyl\Support\JsonValueGuard; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; final readonly class PresignBackupUpload implements PresignsBackupUploads @@ -32,7 +31,7 @@ final readonly class PresignBackupUpload implements PresignsBackupUploads throw_unless($adapter instanceof S3Filesystem, BadRequestHttpException::class, 'The configured backup adapter is not an S3 compatible adapter.'); $client = $adapter->getClient(); - $expires = CarbonImmutable::now()->addMinutes(JsonValueGuard::integer(config('backups.presigned_url_lifespan', 60))); + $expires = CarbonImmutable::now()->addMinutes(config()->integer('backups.presigned_url_lifespan', 60)); $params = [ 'Bucket' => $adapter->getBucket(), diff --git a/app/Actions/Eggs/CreateEgg.php b/app/Actions/Eggs/CreateEgg.php index 305b76027..56e2ba4f9 100644 --- a/app/Actions/Eggs/CreateEgg.php +++ b/app/Actions/Eggs/CreateEgg.php @@ -13,7 +13,6 @@ use Pterodactyl\Models\Egg; use Pterodactyl\Rules\DockerImageList; use Pterodactyl\Services\Extensions\ExtensionFields; use Pterodactyl\Services\Extensions\ValidatedExtensionValues; -use Pterodactyl\Support\JsonValueGuard; final readonly class CreateEgg implements CreatesEggs { @@ -125,7 +124,7 @@ final readonly class CreateEgg implements CreatesEggs return DB::transaction(function () use ($attributes, $extensions): Egg { $egg = Egg::query()->forceCreate([ ...$attributes, - 'author' => JsonValueGuard::string(Config::get('pterodactyl.service.author')), + 'author' => Config::string('pterodactyl.service.author'), ]); $this->extensions->save($egg, $extensions); diff --git a/app/Actions/Files/ReadFileContents.php b/app/Actions/Files/ReadFileContents.php index 6cf6ba621..6da716a57 100644 --- a/app/Actions/Files/ReadFileContents.php +++ b/app/Actions/Files/ReadFileContents.php @@ -4,10 +4,10 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Files; +use Illuminate\Support\Fluent; use Pterodactyl\Contracts\Files\ReadsFileContents; use Pterodactyl\Facades\Daemon; use Pterodactyl\Models\Server; -use Pterodactyl\Support\JsonValueGuard; final readonly class ReadFileContents implements ReadsFileContents { @@ -15,7 +15,7 @@ final readonly class ReadFileContents implements ReadsFileContents { return Daemon::server($server)->files()->getContent( $path, - $maxBytes ?? JsonValueGuard::integer(config('pterodactyl.files.max_edit_size')) + $maxBytes ?? Fluent::make(config()->array('pterodactyl.files'))->integer('max_edit_size') ); } } diff --git a/app/Actions/Schedules/CreateScheduleTask.php b/app/Actions/Schedules/CreateScheduleTask.php index 0c363708a..efc0b8fa3 100644 --- a/app/Actions/Schedules/CreateScheduleTask.php +++ b/app/Actions/Schedules/CreateScheduleTask.php @@ -6,6 +6,7 @@ namespace Pterodactyl\Actions\Schedules; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; +use Illuminate\Support\Fluent; use Illuminate\Validation\Rule; use Pterodactyl\Contracts\Schedules\CreatesScheduleTasks; use Pterodactyl\Exceptions\Http\HttpForbiddenException; @@ -13,7 +14,6 @@ use Pterodactyl\Exceptions\Service\ServiceLimitExceededException; use Pterodactyl\Facades\Activity; use Pterodactyl\Models\Schedule; use Pterodactyl\Models\Task; -use Pterodactyl\Support\JsonValueGuard; use Throwable; final readonly class CreateScheduleTask implements CreatesScheduleTasks @@ -81,7 +81,7 @@ final readonly class CreateScheduleTask implements CreatesScheduleTasks $task = DB::transaction(function () use ($schedule, $attributes): Task { $schedule = $schedule->newQuery()->whereKey($schedule->getKey())->lockForUpdate()->firstOrFail(); - $limit = JsonValueGuard::integer(config('pterodactyl.client_features.schedules.per_schedule_task_limit', 10)); + $limit = Fluent::make(config()->array('pterodactyl.client_features.schedules'))->integer('per_schedule_task_limit', 10); throw_if($schedule->tasks()->count() >= $limit, ServiceLimitExceededException::class, "Schedules may not have more than $limit tasks associated with them. Creating this task would put this schedule over the limit."); $next = ($schedule->tasks()->orderByDesc('sequence_id')->first()->sequence_id ?? 0) + 1; diff --git a/app/Actions/Users/SetupTwoFactor.php b/app/Actions/Users/SetupTwoFactor.php index d7bc513c4..a8cf934cf 100644 --- a/app/Actions/Users/SetupTwoFactor.php +++ b/app/Actions/Users/SetupTwoFactor.php @@ -8,7 +8,6 @@ use Exception; use Illuminate\Support\Facades\Crypt; use Pterodactyl\Contracts\Users\SetsUpTwoFactor; use Pterodactyl\Models\User; -use Pterodactyl\Support\JsonValueGuard; use RuntimeException; final readonly class SetupTwoFactor implements SetsUpTwoFactor @@ -26,7 +25,7 @@ final readonly class SetupTwoFactor implements SetsUpTwoFactor { $secret = ''; try { - for ($i = 0; $i < JsonValueGuard::integer(config('pterodactyl.auth.2fa.bytes', 16)); $i++) { + for ($i = 0; $i < config()->integer('pterodactyl.auth.2fa.bytes', 16); $i++) { $secret .= mb_substr(self::VALID_BASE32_CHARACTERS, random_int(0, 31), 1); } } catch (Exception $exception) { @@ -35,7 +34,7 @@ final readonly class SetupTwoFactor implements SetsUpTwoFactor $user->update(['totp_secret' => Crypt::encrypt($secret)]); - $company = urlencode(preg_replace('/\s/', '', JsonValueGuard::string(config('app.name'))) ?? ''); + $company = urlencode(preg_replace('/\s/', '', config()->string('app.name')) ?? ''); return [ 'image_url_data' => sprintf( diff --git a/app/Actions/Users/ToggleTwoFactor.php b/app/Actions/Users/ToggleTwoFactor.php index 8e475e8f7..de1eeff2f 100644 --- a/app/Actions/Users/ToggleTwoFactor.php +++ b/app/Actions/Users/ToggleTwoFactor.php @@ -7,6 +7,7 @@ namespace Pterodactyl\Actions\Users; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Fluent; use Illuminate\Support\Str; use PragmaRX\Google2FA\Exceptions\IncompatibleWithGoogleAuthenticatorException; use PragmaRX\Google2FA\Exceptions\InvalidCharactersException; @@ -43,7 +44,7 @@ final readonly class ToggleTwoFactor implements TogglesTwoFactor $secret = JsonValueGuard::string(Crypt::decrypt($encryptedSecret)); - $isValidToken = $this->google2FA->verifyKey($secret, $token, JsonValueGuard::integer(config()->get('pterodactyl.auth.2fa.window'))); + $isValidToken = $this->google2FA->verifyKey($secret, $token, Fluent::make(config()->array('pterodactyl.auth.2fa'))->integer('window')); throw_unless($isValidToken, TwoFactorAuthenticationTokenInvalid::class); diff --git a/app/Console/Commands/InfoCommand.php b/app/Console/Commands/InfoCommand.php index 4b6aeecd0..99adfb177 100644 --- a/app/Console/Commands/InfoCommand.php +++ b/app/Console/Commands/InfoCommand.php @@ -8,7 +8,6 @@ use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; use Pterodactyl\Services\Helpers\SoftwareVersionService; -use Pterodactyl\Support\JsonValueGuard; #[Description('Displays the application, database, and email configurations along with the panel version.')] #[Signature('p:info')] @@ -34,7 +33,7 @@ class InfoCommand extends Command $this->output->title('Application Configuration'); $this->table([], [ - ['Environment', $this->formatText(JsonValueGuard::string(config('app.env')), config('app.env') === 'production' ? '' : 'bg=red')], + ['Environment', $this->formatText(config()->string('app.env'), config('app.env') === 'production' ? '' : 'bg=red')], ['Debug Mode', $this->formatText(config('app.debug') ? 'Yes' : 'No', config('app.debug') ? 'bg=red' : '')], ['Installation URL', config('app.url')], ['Installation Directory', base_path()], @@ -48,7 +47,7 @@ class InfoCommand extends Command ], 'compact'); $this->output->title('Database Configuration'); - $driver = JsonValueGuard::string(config('database.default')); + $driver = config()->string('database.default'); $this->table([], [ ['Driver', $driver], ['Host', config("database.connections.$driver.host")], diff --git a/app/Extensions/Backups/BackupManager.php b/app/Extensions/Backups/BackupManager.php index 61c867f21..b73d9b8c3 100644 --- a/app/Extensions/Backups/BackupManager.php +++ b/app/Extensions/Backups/BackupManager.php @@ -6,7 +6,7 @@ namespace Pterodactyl\Extensions\Backups; use Aws\S3\S3Client; use Closure; -use Illuminate\Contracts\Config\Repository as ConfigRepository; +use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Foundation\Application; use Illuminate\Support\Arr; use InvalidArgumentException; @@ -88,7 +88,7 @@ class BackupManager */ public function getDefaultAdapter(): string { - return JsonValueGuard::string($this->config->get('backups.default')); + return $this->config->string('backups.default'); } /** diff --git a/app/Extensions/Illuminate/Auth/Passwords/PasswordBrokerManager.php b/app/Extensions/Illuminate/Auth/Passwords/PasswordBrokerManager.php index 6af7bf102..69e4948a0 100644 --- a/app/Extensions/Illuminate/Auth/Passwords/PasswordBrokerManager.php +++ b/app/Extensions/Illuminate/Auth/Passwords/PasswordBrokerManager.php @@ -6,12 +6,11 @@ namespace Pterodactyl\Extensions\Illuminate\Auth\Passwords; use Illuminate\Auth\AuthManager; use Illuminate\Auth\Passwords\PasswordBrokerManager as IlluminatePasswordBrokerManager; -use Illuminate\Contracts\Config\Repository as ConfigRepository; +use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Contracts\Hashing\Hasher; use Illuminate\Database\DatabaseManager; use InvalidArgumentException; -use Pterodactyl\Support\JsonValueGuard; class PasswordBrokerManager extends IlluminatePasswordBrokerManager { @@ -26,27 +25,27 @@ class PasswordBrokerManager extends IlluminatePasswordBrokerManager throw_unless($config->has($prefix), InvalidArgumentException::class, "Password resetter [{$name}] is not defined."); $users = $this->app->make(AuthManager::class)->createUserProvider( - JsonValueGuard::nullableString($config->get("{$prefix}.provider")) + $config->get("{$prefix}.provider") === null ? null : $config->string("{$prefix}.provider") ); throw_if($users === null, InvalidArgumentException::class, "Password resetter [{$name}] has no user provider."); - $key = JsonValueGuard::string($config->get('app.key')); + $key = $config->string('app.key'); $tokens = new DatabaseTokenRepository( - $this->app->make(DatabaseManager::class)->connection(JsonValueGuard::nullableString($config->get("{$prefix}.connection"))), + $this->app->make(DatabaseManager::class)->connection($config->get("{$prefix}.connection") === null ? null : $config->string("{$prefix}.connection")), $this->app->make(Hasher::class), - JsonValueGuard::string($config->get("{$prefix}.table")), + $config->string("{$prefix}.table"), str_starts_with($key, 'base64:') ? base64_decode(mb_substr($key, 7)) : $key, - JsonValueGuard::integer($config->get("{$prefix}.expire", 60)) * 60, - JsonValueGuard::integer($config->get("{$prefix}.throttle", 0)), + $config->integer("{$prefix}.expire", 60) * 60, + $config->integer("{$prefix}.throttle", 0), ); return new PasswordBroker( $tokens, $users, $this->app->make(Dispatcher::class), - timeboxDuration: JsonValueGuard::integer($config->get('auth.timebox_duration', 200000)), + timeboxDuration: $config->integer('auth.timebox_duration', 200000), ); } } diff --git a/app/Http/Controllers/Api/Admin/Settings/SettingsController.php b/app/Http/Controllers/Api/Admin/Settings/SettingsController.php index 8f52d2868..ce7d8b448 100644 --- a/app/Http/Controllers/Api/Admin/Settings/SettingsController.php +++ b/app/Http/Controllers/Api/Admin/Settings/SettingsController.php @@ -5,13 +5,13 @@ declare(strict_types=1); namespace Pterodactyl\Http\Controllers\Api\Admin\Settings; use Illuminate\Http\JsonResponse; +use Illuminate\Support\Fluent; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; use Pterodactyl\Http\Controllers\Api\Admin\AdminApiController; use Pterodactyl\Http\Requests\Api\Admin\Settings\GetSettingsRequest; -use Pterodactyl\Support\JsonValueGuard; #[Group('Admin API', 'Root administrator endpoints for managing panel configuration and resources.')] #[Subgroup('Settings', 'View and update global panel settings.')] @@ -56,16 +56,19 @@ class SettingsController extends AdminApiController #[ScribeResponse(self::SETTINGS_EXAMPLE, description: 'Settings returned.')] public function index(GetSettingsRequest $request): JsonResponse { + // Settings saved from the panel come back from the database as strings, so numbers are cast on read. + $settings = Fluent::make(config()->all()); + return new JsonResponse([ 'general' => [ 'app:name' => config('app.name'), - 'pterodactyl:auth:2fa_required' => JsonValueGuard::integer(config('pterodactyl.auth.2fa_required')), + 'pterodactyl:auth:2fa_required' => $settings->integer('pterodactyl.auth.2fa_required'), 'app:locale' => config('app.locale'), ], 'mail' => [ 'mail:default' => config('mail.default'), 'mail:mailers:smtp:host' => config('mail.mailers.smtp.host'), - 'mail:mailers:smtp:port' => JsonValueGuard::integer(config('mail.mailers.smtp.port')), + 'mail:mailers:smtp:port' => $settings->integer('mail.mailers.smtp.port'), 'mail:mailers:smtp:encryption' => config('mail.mailers.smtp.encryption'), 'mail:mailers:smtp:username' => config('mail.mailers.smtp.username'), // Never return the SMTP password to the client. @@ -74,17 +77,17 @@ class SettingsController extends AdminApiController 'mail:from:name' => config('mail.from.name'), ], 'advanced' => [ - 'recaptcha:enabled' => JsonValueGuard::boolean(config('recaptcha.enabled')), + 'recaptcha:enabled' => config()->boolean('recaptcha.enabled'), 'recaptcha:secret_key' => '', 'recaptcha:website_key' => config('recaptcha.website_key'), - 'pterodactyl:guzzle:timeout' => JsonValueGuard::integer(config('pterodactyl.guzzle.timeout')), - 'pterodactyl:guzzle:connect_timeout' => JsonValueGuard::integer(config('pterodactyl.guzzle.connect_timeout')), - 'pterodactyl:client_features:allocations:enabled' => JsonValueGuard::boolean(config('pterodactyl.client_features.allocations.enabled')), + 'pterodactyl:guzzle:timeout' => $settings->integer('pterodactyl.guzzle.timeout'), + 'pterodactyl:guzzle:connect_timeout' => $settings->integer('pterodactyl.guzzle.connect_timeout'), + 'pterodactyl:client_features:allocations:enabled' => config()->boolean('pterodactyl.client_features.allocations.enabled'), 'pterodactyl:client_features:allocations:range_start' => config('pterodactyl.client_features.allocations.range_start'), 'pterodactyl:client_features:allocations:range_end' => config('pterodactyl.client_features.allocations.range_end'), ], 'meta' => [ - 'load_environment_only' => JsonValueGuard::boolean(config('pterodactyl.load_environment_only', false)), + 'load_environment_only' => config()->boolean('pterodactyl.load_environment_only', false), 'show_recaptcha_warning' => config('recaptcha._shipped_secret_key') === config('recaptcha.secret_key') || config('recaptcha._shipped_website_key') === config('recaptcha.website_key'), ], diff --git a/app/Http/Controllers/Auth/LoginCheckpointController.php b/app/Http/Controllers/Auth/LoginCheckpointController.php index e56164c74..c8f76f90d 100644 --- a/app/Http/Controllers/Auth/LoginCheckpointController.php +++ b/app/Http/Controllers/Auth/LoginCheckpointController.php @@ -10,6 +10,7 @@ use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Fluent; use Illuminate\Validation\ValidationException; use Knuckles\Scribe\Attributes\BodyParam; use Knuckles\Scribe\Attributes\Endpoint; @@ -124,7 +125,7 @@ class LoginCheckpointController extends AbstractLoginController $decrypted, JsonValueGuard::nullableString($request->validated('authentication_code')) ?? '', $oldTimestamp, - JsonValueGuard::integer(config('pterodactyl.auth.2fa.window', 1)) + Fluent::make(config()->array('pterodactyl.auth.2fa'))->integer('window', 1) ); if ($verified !== false) { diff --git a/app/Http/Middleware/EnsureStatefulRequests.php b/app/Http/Middleware/EnsureStatefulRequests.php index c001ae8d5..3d89309cb 100644 --- a/app/Http/Middleware/EnsureStatefulRequests.php +++ b/app/Http/Middleware/EnsureStatefulRequests.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Pterodactyl\Http\Middleware; use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful; -use Pterodactyl\Support\JsonValueGuard; class EnsureStatefulRequests extends EnsureFrontendRequestsAreStateful { @@ -20,6 +19,6 @@ class EnsureStatefulRequests extends EnsureFrontendRequestsAreStateful return true; } - return $request->hasCookie(JsonValueGuard::string(config('session.cookie'))); + return $request->hasCookie(config()->string('session.cookie')); } } diff --git a/app/Http/Middleware/LanguageMiddleware.php b/app/Http/Middleware/LanguageMiddleware.php index f9cca2f70..c91bc3da4 100644 --- a/app/Http/Middleware/LanguageMiddleware.php +++ b/app/Http/Middleware/LanguageMiddleware.php @@ -8,7 +8,6 @@ use Closure; use Illuminate\Foundation\Application; use Illuminate\Http\Request; use Pterodactyl\Models\User; -use Pterodactyl\Support\JsonValueGuard; use Symfony\Component\HttpFoundation\Response; class LanguageMiddleware @@ -28,7 +27,7 @@ class LanguageMiddleware public function handle(Request $request, Closure $next): mixed { $user = $request->user(); - $this->app->setLocale($user instanceof User ? $user->language : JsonValueGuard::string(config('app.locale', 'en'))); + $this->app->setLocale($user instanceof User ? $user->language : config()->string('app.locale', 'en')); return $next($request); } diff --git a/app/Http/Middleware/VerifyReCaptcha.php b/app/Http/Middleware/VerifyReCaptcha.php index 547b30073..bef8685a6 100644 --- a/app/Http/Middleware/VerifyReCaptcha.php +++ b/app/Http/Middleware/VerifyReCaptcha.php @@ -11,7 +11,6 @@ use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Arr; use Pterodactyl\Events\Auth\FailedCaptcha; -use Pterodactyl\Support\JsonValueGuard; use Symfony\Component\HttpKernel\Exception\HttpException; class VerifyReCaptcha @@ -58,7 +57,7 @@ class VerifyReCaptcha try { $client = new Client(['timeout' => 5, 'connect_timeout' => 2]); - $res = $client->post(JsonValueGuard::string(config('recaptcha.domain')), [ + $res = $client->post(config()->string('recaptcha.domain'), [ 'form_params' => [ 'secret' => config('recaptcha.secret_key'), 'response' => $request->input('g-recaptcha-response'), diff --git a/app/Listeners/RevocationListener.php b/app/Listeners/RevocationListener.php index 43dca9dc9..69e110c04 100644 --- a/app/Listeners/RevocationListener.php +++ b/app/Listeners/RevocationListener.php @@ -15,7 +15,6 @@ use Pterodactyl\Events\User\PasswordChanged; use Pterodactyl\Extensions\Illuminate\Events\Contracts\SubscribesToEvents; use Pterodactyl\Jobs\RevokeSftpAccessJob; use Pterodactyl\Models\Node; -use Pterodactyl\Support\JsonValueGuard; class RevocationListener implements SubscribesToEvents { @@ -28,7 +27,7 @@ class RevocationListener implements SubscribesToEvents ])->saveQuietly(); if (config('session.driver') === 'database') { - $table = JsonValueGuard::string(config('session.table', 'sessions')); + $table = config()->string('session.table', 'sessions'); if ($table !== '') { $currentSessionId = session()->isStarted() ? session()->getId() : null; diff --git a/app/Models/ActivityLog.php b/app/Models/ActivityLog.php index 01c72db38..34957e3f5 100644 --- a/app/Models/ActivityLog.php +++ b/app/Models/ActivityLog.php @@ -18,6 +18,7 @@ use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Support\Carbon; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Event; +use Illuminate\Support\Fluent; use LogicException; use Pterodactyl\Contracts\Models\Identifiable; use Pterodactyl\Events\ActivityLogged; @@ -144,7 +145,7 @@ class ActivityLog extends Model implements Identifiable { throw_if((config('activity.prune_days')) === null, LogicException::class, 'Cannot prune activity logs: no "prune_days" configuration value is set.'); - return static::query()->where('timestamp', '<=', now()->subDays(JsonValueGuard::integer(config('activity.prune_days')))); + return static::query()->where('timestamp', '<=', now()->subDays(Fluent::make(config()->array('activity'))->integer('prune_days'))); } /** diff --git a/app/Models/Node.php b/app/Models/Node.php index 60fd65d97..753867ce8 100644 --- a/app/Models/Node.php +++ b/app/Models/Node.php @@ -149,6 +149,9 @@ class Node extends Model implements Identifiable $allowedMounts[] = $mount->source; } + $remote = config()->string('app.url'); + throw_if($remote === '', UnexpectedValueException::class, 'The application URL must not be empty.'); + return [ 'debug' => false, 'uuid' => $this->uuid, @@ -171,7 +174,7 @@ class Node extends Model implements Identifiable ], ], 'allowed_mounts' => $allowedMounts, - 'remote' => mb_rtrim(JsonValueGuard::nonEmptyString(config('app.url')), '/'), + 'remote' => mb_rtrim($remote, '/'), ]; } diff --git a/app/Notifications/AccountCreated.php b/app/Notifications/AccountCreated.php index 2badabdd1..38b181e41 100644 --- a/app/Notifications/AccountCreated.php +++ b/app/Notifications/AccountCreated.php @@ -9,7 +9,6 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; use Pterodactyl\Models\User; -use Pterodactyl\Support\JsonValueGuard; class AccountCreated extends Notification implements ShouldQueue { @@ -40,7 +39,7 @@ class AccountCreated extends Notification implements ShouldQueue { $message = (new MailMessage) ->greeting('Hello '.$this->user->name.'!') - ->line('You are receiving this email because an account has been created for you on '.JsonValueGuard::string(config('app.name')).'.') + ->line('You are receiving this email because an account has been created for you on '.config()->string('app.name').'.') ->line('Username: '.$this->user->username) ->line('Email: '.$this->user->email); diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 4d7d15d52..ba510996c 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -19,6 +19,7 @@ use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\View; +use Illuminate\Support\Fluent; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Str; use Illuminate\Validation\Rules\Password; @@ -86,7 +87,7 @@ class AppServiceProvider extends ServiceProvider // doesn't, and it triggers a lot of support requests, so lets just head it off here. // // @see https://github.com/pterodactyl/panel/issues/3623 - if (Str::startsWith(JsonValueGuard::nullableString(config('app.url')) ?? '', 'https://')) { + if (config('app.url') !== null && Str::startsWith(config()->string('app.url'), 'https://')) { URL::forceScheme('https'); } @@ -213,9 +214,8 @@ class AppServiceProvider extends ServiceProvider $user = $request->user(); $key = $user instanceof User ? $user->uuid : $request->ip(); - return Limit::perMinutes( - JsonValueGuard::integer(config("http.rate_limit.{$name}_period")), - JsonValueGuard::integer(config("http.rate_limit.{$name}")), - )->by($key); + $limits = Fluent::make(config()->array('http.rate_limit')); + + return Limit::perMinutes($limits->integer("{$name}_period"), $limits->integer($name))->by($key); } } diff --git a/app/Providers/ExtensionServiceProvider.php b/app/Providers/ExtensionServiceProvider.php index a51b9466d..c11960894 100644 --- a/app/Providers/ExtensionServiceProvider.php +++ b/app/Providers/ExtensionServiceProvider.php @@ -25,7 +25,6 @@ use Pterodactyl\Services\Extensions\ExtensionPermissionRegistry; use Pterodactyl\Services\Extensions\ExtensionProviderLoader; use Pterodactyl\Services\Extensions\ExtensionRepository; use Pterodactyl\Services\Extensions\ExtensionSettingsRegistry; -use Pterodactyl\Support\JsonValueGuard; use Throwable; class ExtensionServiceProvider extends ServiceProvider @@ -61,7 +60,7 @@ class ExtensionServiceProvider extends ServiceProvider RateLimiter::for('extensions.root', function (Request $request): Limit { $user = $request->user(); - return Limit::perMinute(JsonValueGuard::integer(config('extensions.root_routes_per_minute'))) + return Limit::perMinute(config()->integer('extensions.root_routes_per_minute')) ->by($user instanceof User ? $user->uuid : $request->ip()); }); diff --git a/app/Providers/HashidsServiceProvider.php b/app/Providers/HashidsServiceProvider.php index 3fc903354..06e428075 100644 --- a/app/Providers/HashidsServiceProvider.php +++ b/app/Providers/HashidsServiceProvider.php @@ -4,11 +4,10 @@ declare(strict_types=1); namespace Pterodactyl\Providers; -use Illuminate\Contracts\Config\Repository; +use Illuminate\Config\Repository; use Illuminate\Support\ServiceProvider; use Pterodactyl\Contracts\Extensions\HashidsInterface; use Pterodactyl\Extensions\Hashids; -use Pterodactyl\Support\JsonValueGuard; class HashidsServiceProvider extends ServiceProvider { @@ -22,9 +21,9 @@ class HashidsServiceProvider extends ServiceProvider $length = filter_var($config->get('hashids.length', 0), FILTER_VALIDATE_INT); return new Hashids( - JsonValueGuard::string($config->get('hashids.salt', '')), + $config->string('hashids.salt', ''), $length === false ? 0 : $length, - JsonValueGuard::string($config->get('hashids.alphabet', 'abcdefghijkmlnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890')) + $config->string('hashids.alphabet', 'abcdefghijkmlnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') ); }); diff --git a/app/Services/Daemon/DaemonConnection.php b/app/Services/Daemon/DaemonConnection.php index 2096eded3..1fea1c4f4 100644 --- a/app/Services/Daemon/DaemonConnection.php +++ b/app/Services/Daemon/DaemonConnection.php @@ -10,6 +10,7 @@ use Illuminate\Http\Client\Response; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Validator; +use Illuminate\Support\Fluent; use Illuminate\Validation\ValidationException; use JsonException; use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException; @@ -30,12 +31,15 @@ final readonly class DaemonConnection /** @param RequestOptions $options */ public function request(string $method, string $path, array $options = [], bool $useStatusCode = true): Response { + // Timeouts saved from the panel's settings come back from the database as strings. + $guzzle = Fluent::make(config()->array('pterodactyl.guzzle')); + $request = Http::baseUrl($this->url) ->withToken($this->token) ->acceptJson() ->asJson() - ->timeout(JsonValueGuard::integer(config('pterodactyl.guzzle.timeout'))) - ->connectTimeout(JsonValueGuard::integer(config('pterodactyl.guzzle.connect_timeout'))) + ->timeout($guzzle->integer('timeout')) + ->connectTimeout($guzzle->integer('connect_timeout')) ->withOptions(['verify' => App::isProduction()]); if (isset($options['body'])) { diff --git a/app/Services/Extensions/ExtensionAssetPublisher.php b/app/Services/Extensions/ExtensionAssetPublisher.php index 70bc4c282..20e2ad48d 100644 --- a/app/Services/Extensions/ExtensionAssetPublisher.php +++ b/app/Services/Extensions/ExtensionAssetPublisher.php @@ -8,7 +8,6 @@ use Closure; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; -use Pterodactyl\Support\JsonValueGuard; use Throwable; class ExtensionAssetPublisher @@ -196,7 +195,7 @@ class ExtensionAssetPublisher public function publishedPath(string $identifier): string { - return mb_rtrim(JsonValueGuard::string(config('extensions.assets_directory')), '/\\').DIRECTORY_SEPARATOR.$identifier; + return mb_rtrim(config()->string('extensions.assets_directory'), '/\\').DIRECTORY_SEPARATOR.$identifier; } public function watchDevelopment(string $identifier): void diff --git a/app/Services/Extensions/ExtensionCompatibility.php b/app/Services/Extensions/ExtensionCompatibility.php index ebb820bb6..b745520ce 100644 --- a/app/Services/Extensions/ExtensionCompatibility.php +++ b/app/Services/Extensions/ExtensionCompatibility.php @@ -7,7 +7,6 @@ namespace Pterodactyl\Services\Extensions; use Composer\Semver\Semver; use Illuminate\Support\Collection; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; -use Pterodactyl\Support\JsonValueGuard; final class ExtensionCompatibility { @@ -195,8 +194,8 @@ final class ExtensionCompatibility private function runtimeFailureReason(ExtensionManifest $manifest): ?string { $versions = [ - 'panel' => JsonValueGuard::string(config('extensions.panel_version')), - 'sdk' => JsonValueGuard::string(config('extensions.sdk_version')), + 'panel' => config()->string('extensions.panel_version'), + 'sdk' => config()->string('extensions.sdk_version'), 'php' => PHP_VERSION, ]; foreach ($manifest->requirements as $runtime => $constraint) { diff --git a/app/Services/Extensions/ExtensionHeadTags.php b/app/Services/Extensions/ExtensionHeadTags.php index 4589a959e..95ab6e228 100644 --- a/app/Services/Extensions/ExtensionHeadTags.php +++ b/app/Services/Extensions/ExtensionHeadTags.php @@ -146,7 +146,7 @@ final class ExtensionHeadTags implements Htmlable private function resolve(string $identifier, string $version, Closure $tags): array { $key = $this->cacheKey($identifier, $version); - $seconds = JsonValueGuard::integer(config('extensions.head_tags_cache_seconds')); + $seconds = config()->integer('extensions.head_tags_cache_seconds'); $cached = $seconds > 0 ? Cache::get($key) : null; if ($cached !== null) { return $this->parse(JsonValueGuard::jsonArray($cached)); diff --git a/app/Services/Extensions/ExtensionJobProgress.php b/app/Services/Extensions/ExtensionJobProgress.php index d2839c8c3..9c3ebecc3 100644 --- a/app/Services/Extensions/ExtensionJobProgress.php +++ b/app/Services/Extensions/ExtensionJobProgress.php @@ -10,7 +10,6 @@ use InvalidArgumentException; use Pterodactyl\Data\Extensions\ExtensionJobSnapshot; use Pterodactyl\Models\Server; use Pterodactyl\Models\User; -use Pterodactyl\Support\JsonValueGuard; /** Shared snapshots survive reconnects and worker boundaries for the configured retention period. */ final class ExtensionJobProgress @@ -70,7 +69,7 @@ final class ExtensionJobProgress private function store(ExtensionJobSnapshot $snapshot): void { - Cache::put($this->key($snapshot->extension, $snapshot->id), $snapshot, max(60, JsonValueGuard::integer(config('extensions.progress_retention_seconds')))); + Cache::put($this->key($snapshot->extension, $snapshot->id), $snapshot, max(60, config()->integer('extensions.progress_retention_seconds'))); } private function key(string $extension, string $id): string diff --git a/app/Services/Extensions/ExtensionLock.php b/app/Services/Extensions/ExtensionLock.php index 4cff8325e..ec16e7bba 100644 --- a/app/Services/Extensions/ExtensionLock.php +++ b/app/Services/Extensions/ExtensionLock.php @@ -7,7 +7,6 @@ namespace Pterodactyl\Services\Extensions; use Closure; use Illuminate\Support\Facades\File; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; -use Pterodactyl\Support\JsonValueGuard; final class ExtensionLock { @@ -41,7 +40,7 @@ final class ExtensionLock return; } - $directory = mb_rtrim(JsonValueGuard::string(config('extensions.directory')), '/\\').DIRECTORY_SEPARATOR.'.locks'; + $directory = mb_rtrim(config()->string('extensions.directory'), '/\\').DIRECTORY_SEPARATOR.'.locks'; File::ensureDirectoryExists($directory); $lock = fopen($directory.DIRECTORY_SEPARATOR.'packages', 'c'); throw_if($lock === false, InvalidExtensionException::class, 'Unable to lock extension package.'); diff --git a/app/Services/Extensions/ExtensionRepository.php b/app/Services/Extensions/ExtensionRepository.php index e7a0c74f3..49fd8628c 100644 --- a/app/Services/Extensions/ExtensionRepository.php +++ b/app/Services/Extensions/ExtensionRepository.php @@ -13,7 +13,6 @@ use Illuminate\Support\Facades\Schema; use Pterodactyl\Events\Extensions\ExtensionLoadFailed; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; use Pterodactyl\Models\Extension; -use Pterodactyl\Support\JsonValueGuard; use Symfony\Component\Finder\SplFileInfo; use Throwable; @@ -44,7 +43,7 @@ class ExtensionRepository public function directory(): string { - return mb_rtrim(JsonValueGuard::string(config('extensions.directory')), '/\\'); + return mb_rtrim(config()->string('extensions.directory'), '/\\'); } /** diff --git a/app/Services/Extensions/ExtensionSettingFiles.php b/app/Services/Extensions/ExtensionSettingFiles.php index 3ef781a39..6ebf00f16 100644 --- a/app/Services/Extensions/ExtensionSettingFiles.php +++ b/app/Services/Extensions/ExtensionSettingFiles.php @@ -10,10 +10,10 @@ use DOMElement; use DOMText; use Illuminate\Contracts\Filesystem\Filesystem; use Illuminate\Http\UploadedFile; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\Storage; use Illuminate\Validation\ValidationException; use Pterodactyl\Models\ExtensionSetting; -use Pterodactyl\Support\JsonValueGuard; use UnexpectedValueException; /** @@ -166,7 +166,7 @@ class ExtensionSettingFiles */ private function disk(): Filesystem { - $name = JsonValueGuard::string(config('extensions.files_disk')); + $name = config()->string('extensions.files_disk'); throw_if($this->servedDirectly($name), UnexpectedValueException::class, sprintf('The "%s" disk is served directly by the web server; extensions.files_disk must name a private disk so setting files are only served through /%s.', $name, self::ROUTE_PREFIX)); return Storage::disk($name); @@ -182,8 +182,9 @@ class ExtensionSettingFiles return false; } - $root = mb_rtrim(JsonValueGuard::string(config("filesystems.disks.{$disk}.root")), '/\\').'/'; - $links = JsonValueGuard::stringList(array_values(JsonValueGuard::jsonArray(config('filesystems.links', [])))); + $root = mb_rtrim(config()->string("filesystems.disks.{$disk}.root"), '/\\').'/'; + $configured = config()->array('filesystems.links', []); + $links = array_map(fn (int|string $link): string => Arr::string($configured, $link), array_keys($configured)); return array_any([public_path(), ...$links], fn (string $directory): bool => str_starts_with($root, mb_rtrim($directory, '/\\').'/')); } diff --git a/app/Services/Extensions/ExtensionUrlDownloader.php b/app/Services/Extensions/ExtensionUrlDownloader.php index 0d56803f3..c5a353020 100644 --- a/app/Services/Extensions/ExtensionUrlDownloader.php +++ b/app/Services/Extensions/ExtensionUrlDownloader.php @@ -21,6 +21,7 @@ use Psr\Http\Message\ResponseInterface; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; use Pterodactyl\Support\JsonValueGuard; use Throwable; +use UnexpectedValueException; /** * Downloads extension packages from signed install URLs. @@ -95,7 +96,9 @@ class ExtensionUrlDownloader if ($jwt !== '') { try { $token = (new Parser(new JoseEncoder))->parse($jwt); - $key = InMemory::base64Encoded(JsonValueGuard::nonEmptyString(config('extensions.signed_urls.public_key'))); + $publicKey = config()->string('extensions.signed_urls.public_key'); + throw_if($publicKey === '', UnexpectedValueException::class, 'Signed install URLs need a public key.'); + $key = InMemory::base64Encoded($publicKey); $signed = $token instanceof UnencryptedToken && (new Validator)->validate($token, new SignedWith(new Eddsa, $key)); } catch (Throwable) { $signed = false; @@ -110,8 +113,11 @@ class ExtensionUrlDownloader ); $claims = $token->claims(); + $issuer = config()->string('extensions.signed_urls.issuer'); + $audience = config()->string('extensions.signed_urls.audience'); + throw_if($issuer === '' || $audience === '', UnexpectedValueException::class, 'Signed install URLs need an issuer and an audience.'); throw_unless( - $token->hasBeenIssuedBy(JsonValueGuard::nonEmptyString(config('extensions.signed_urls.issuer'))) && $token->isPermittedFor(JsonValueGuard::nonEmptyString(config('extensions.signed_urls.audience'))), + $token->hasBeenIssuedBy($issuer) && $token->isPermittedFor($audience), InvalidExtensionException::class, 'This signed URL is not an extension install URL.', ); diff --git a/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php b/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php index b04276e50..dd14d784a 100644 --- a/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php +++ b/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php @@ -9,7 +9,6 @@ use Illuminate\Support\Str; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; use Pterodactyl\Services\Extensions\ExtensionManifest; use Pterodactyl\Services\Extensions\ExtensionManifestValidator; -use Pterodactyl\Support\JsonValueGuard; /** * Scaffolds a new extension package the way `php artisan make:*` scaffolds core @@ -48,7 +47,7 @@ class ExtensionScaffolder $prefix ??= ExtensionManifest::defaultUiPrefix($id); throw_unless(ExtensionManifest::isUsableUiPrefix($prefix), InvalidExtensionException::class, "Tailwind prefix \"{$prefix}\" must match ".ExtensionManifest::UI_PREFIX_REGEX.' and must not be a Tailwind variant, theme namespace or panel name.'); - $target = mb_rtrim($outDir ?? JsonValueGuard::string(config('extensions.directory')), '/\\').DIRECTORY_SEPARATOR.$id; + $target = mb_rtrim($outDir ?? config()->string('extensions.directory'), '/\\').DIRECTORY_SEPARATOR.$id; throw_if(is_dir($target) && ! $force, InvalidExtensionException::class, "{$target} already exists - pass --force to overwrite it."); File::deleteDirectory($target); diff --git a/app/Services/Helpers/SoftwareVersionService.php b/app/Services/Helpers/SoftwareVersionService.php index b67dbf792..965c7df5e 100644 --- a/app/Services/Helpers/SoftwareVersionService.php +++ b/app/Services/Helpers/SoftwareVersionService.php @@ -67,7 +67,7 @@ class SoftwareVersionService return true; } - return version_compare(JsonValueGuard::string(config('app.version')), $this->getPanel()) >= 0; + return version_compare(config()->string('app.version'), $this->getPanel()) >= 0; } /** @@ -87,9 +87,9 @@ class SoftwareVersionService */ protected function cacheVersionData(): array { - $cached = $this->cache->remember(self::VERSION_CACHE_KEY, CarbonImmutable::now()->addMinutes(JsonValueGuard::integer(config('pterodactyl.cdn.cache_time', 60))), function (): array { + $cached = $this->cache->remember(self::VERSION_CACHE_KEY, CarbonImmutable::now()->addMinutes(config()->integer('pterodactyl.cdn.cache_time', 60)), function (): array { try { - $response = $this->client->request('GET', JsonValueGuard::string(config('pterodactyl.cdn.url')), ['timeout' => 5, 'connect_timeout' => 2]); + $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()); diff --git a/app/Services/Nodes/NodeJWTService.php b/app/Services/Nodes/NodeJWTService.php index cb43c5bd6..58263cc61 100644 --- a/app/Services/Nodes/NodeJWTService.php +++ b/app/Services/Nodes/NodeJWTService.php @@ -16,7 +16,6 @@ use Pterodactyl\Enum\JwtScope; use Pterodactyl\Extensions\Lcobucci\JWT\Encoding\TimestampDates; use Pterodactyl\Models\Node; use Pterodactyl\Models\User; -use Pterodactyl\Support\JsonValueGuard; class NodeJWTService { @@ -93,10 +92,13 @@ class NodeJWTService $connectionAddress = $node->getConnectionAddress(); throw_if($connectionAddress === '', InvalidArgumentException::class, 'Cannot generate a JWT for a node with an empty connection address.'); + $issuer = config()->string('app.url'); + throw_if($issuer === '', InvalidArgumentException::class, 'Cannot generate a JWT without an application URL.'); + $config = Configuration::forSymmetricSigner(new Sha256, InMemory::plainText($nodeKey)); $builder = $config->builder(new TimestampDates) - ->issuedBy(JsonValueGuard::nonEmptyString(config('app.url'))) + ->issuedBy($issuer) ->permittedFor($connectionAddress) ->identifiedBy($identifier) ->withHeader('jti', $identifier) diff --git a/app/Services/Themes/ThemeService.php b/app/Services/Themes/ThemeService.php index 3ccc86a97..6d8ba082a 100644 --- a/app/Services/Themes/ThemeService.php +++ b/app/Services/Themes/ThemeService.php @@ -4,8 +4,6 @@ declare(strict_types=1); namespace Pterodactyl\Services\Themes; -use Pterodactyl\Support\JsonValueGuard; - /** * Installs theme.json + tokens.css themes and publishes the active one to public/assets/theme.css. */ @@ -15,7 +13,7 @@ class ThemeService public function directory(): string { - return mb_rtrim(JsonValueGuard::string(config('extensions.themes_directory', base_path('themes'))), '/\\'); + return mb_rtrim(config()->string('extensions.themes_directory', base_path('themes')), '/\\'); } public function publishedStylesheet(): string