From bc50a8bbeb96e370a7d049bc2ad77c2983977232 Mon Sep 17 00:00:00 2001 From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com> Date: Thu, 8 Oct 2026 17:22:14 -0400 Subject: [PATCH] backend cleanup --- app/Actions/Backups/DeleteBackup.php | 38 +++++++------- app/Actions/Databases/CreateDatabaseHost.php | 30 +++++------ app/Actions/Databases/UpdateDatabaseHost.php | 13 ++--- app/Actions/Extensions/InstallExtension.php | 4 +- .../Extensions/SetExtensionEnabled.php | 4 +- app/Actions/Servers/UpdateServerDetails.php | 6 ++- app/Actions/Servers/UpdateServerStartup.php | 9 ++-- .../Environment/DatabaseSettingsCommand.php | 8 +-- .../Environment/EmailSettingsCommand.php | 33 +++++------- app/Console/Commands/InfoCommand.php | 51 +++++++++---------- .../CleanServiceBackupFilesCommand.php | 24 +++------ app/Extensions/DynamicDatabaseConnection.php | 16 ++---- app/Helpers/Utilities.php | 13 ----- .../Api/Admin/ApiKeys/ApiKeyController.php | 6 +-- .../Api/Admin/Nodes/DeployTokenController.php | 6 +-- .../Api/Admin/Settings/MailController.php | 9 ++-- .../Api/Admin/Settings/SettingsController.php | 43 ++++++++-------- .../Api/Admin/Tags/TagController.php | 2 +- .../Api/Client/Servers/StartupController.php | 1 - .../Auth/LoginCheckpointController.php | 6 +-- .../Api/Daemon/DaemonAuthenticate.php | 9 +--- app/Http/Middleware/MaintenanceMiddleware.php | 8 +-- .../Middleware/RedirectIfAuthenticated.php | 9 +--- .../RequireTwoFactorAuthentication.php | 9 +--- app/Http/Middleware/VerifyReCaptcha.php | 17 ++----- app/Services/Activity/ActivityLogService.php | 12 ++--- .../Databases/DatabaseHostGateway.php | 6 +-- app/Services/Helpers/AssetHashService.php | 8 --- .../Helpers/SoftwareVersionService.php | 12 ----- .../AssignAvailableAllocationTest.php} | 2 +- .../Backups/DeleteBackupTest.php} | 2 +- .../GenerateBackupDownloadLinkTest.php} | 2 +- .../Databases/CreateDatabaseTest.php} | 2 +- .../Databases/DeployServerDatabaseTest.php} | 2 +- .../Databases/RotateDatabasePasswordTest.php} | 2 +- .../Schedules/ProcessScheduleTest.php} | 2 +- .../Servers/CreateServerTest.php} | 2 +- .../Servers/DeleteServerTest.php} | 2 +- .../Servers/ToggleServerSuspensionTest.php} | 2 +- .../Servers/UpdateServerBuildTest.php} | 2 +- .../Servers/UpdateServerStartupTest.php} | 2 +- .../Users/DeleteUserTest.php} | 2 +- .../Fakes/FakeSoftwareVersionService.php | 9 ---- tests/Unit/ArchTest.php | 39 +++++++++----- .../Middleware/MaintenanceMiddlewareTest.php | 2 +- .../RedirectIfAuthenticatedTest.php | 3 +- 46 files changed, 199 insertions(+), 292 deletions(-) rename tests/Integration/{Services/Allocations/FindAssignableAllocationServiceTest.php => Actions/Allocations/AssignAvailableAllocationTest.php} (98%) rename tests/Integration/{Services/Backups/DeleteBackupServiceTest.php => Actions/Backups/DeleteBackupTest.php} (97%) rename tests/Integration/{Services/Backups/DownloadLinkServiceTest.php => Actions/Backups/GenerateBackupDownloadLinkTest.php} (95%) rename tests/Integration/{Services/Databases/DatabaseManagementServiceTest.php => Actions/Databases/CreateDatabaseTest.php} (98%) rename tests/Integration/{Services/Databases/DeployServerDatabaseServiceTest.php => Actions/Databases/DeployServerDatabaseTest.php} (97%) rename tests/Integration/{Services/Databases/DatabasePasswordServiceTest.php => Actions/Databases/RotateDatabasePasswordTest.php} (96%) rename tests/Integration/{Services/Schedules/ProcessScheduleServiceTest.php => Actions/Schedules/ProcessScheduleTest.php} (98%) rename tests/Integration/{Services/Servers/ServerCreationServiceTest.php => Actions/Servers/CreateServerTest.php} (98%) rename tests/Integration/{Services/Servers/ServerDeletionServiceTest.php => Actions/Servers/DeleteServerTest.php} (98%) rename tests/Integration/{Services/Servers/SuspensionServiceTest.php => Actions/Servers/ToggleServerSuspensionTest.php} (97%) rename tests/Integration/{Services/Servers/BuildModificationServiceTest.php => Actions/Servers/UpdateServerBuildTest.php} (98%) rename tests/Integration/{Services/Servers/StartupModificationServiceTest.php => Actions/Servers/UpdateServerStartupTest.php} (98%) rename tests/Integration/{Services/Users/UserDeletionServiceTest.php => Actions/Users/DeleteUserTest.php} (95%) diff --git a/app/Actions/Backups/DeleteBackup.php b/app/Actions/Backups/DeleteBackup.php index 261f24e82..342a96170 100644 --- a/app/Actions/Backups/DeleteBackup.php +++ b/app/Actions/Backups/DeleteBackup.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Backups; use Illuminate\Http\Response; -use Illuminate\Support\Facades\DB; use LogicException; use Pterodactyl\Contracts\Backups\DeletesBackups; use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException; @@ -44,36 +43,33 @@ final readonly class DeleteBackup implements DeletesBackups return; } - DB::transaction(function () use ($backup): void { - try { - Daemon::server($backup->server)->backups()->delete($backup); - } catch (DaemonConnectionException $daemonConnectionException) { - // Don't fail the request if the Daemon responds with a 404, just assume the backup - // doesn't actually exist and remove its reference from the Panel as well. - throw_if($daemonConnectionException->getStatusCode() !== Response::HTTP_NOT_FOUND, $daemonConnectionException); - } + try { + Daemon::server($backup->server)->backups()->delete($backup); + } catch (DaemonConnectionException $daemonConnectionException) { + // Don't fail the request if the Daemon responds with a 404, just assume the backup + // doesn't actually exist and remove its reference from the Panel as well. + throw_if($daemonConnectionException->getStatusCode() !== Response::HTTP_NOT_FOUND, $daemonConnectionException); + } - $backup->delete(); - }); + $backup->delete(); } /** - * Deletes a backup from an S3 disk. + * Deletes a backup from an S3 disk. The object is removed first so the row is + * kept if S3 rejects the request. * * @throws Throwable */ private function deleteFromS3(Backup $backup): void { - DB::transaction(function () use ($backup): void { - $backup->delete(); + $adapter = $this->manager->adapter(Backup::ADAPTER_AWS_S3); + throw_unless($adapter instanceof S3Filesystem, LogicException::class, 'The S3 backup adapter is not configured correctly.'); - $adapter = $this->manager->adapter(Backup::ADAPTER_AWS_S3); - throw_unless($adapter instanceof S3Filesystem, LogicException::class, 'The S3 backup adapter is not configured correctly.'); + $adapter->getClient()->deleteObject([ + 'Bucket' => $adapter->getBucket(), + 'Key' => sprintf('%s/%s.tar.gz', $backup->server->uuid, $backup->uuid), + ]); - $adapter->getClient()->deleteObject([ - 'Bucket' => $adapter->getBucket(), - 'Key' => sprintf('%s/%s.tar.gz', $backup->server->uuid, $backup->uuid), - ]); - }); + $backup->delete(); } } diff --git a/app/Actions/Databases/CreateDatabaseHost.php b/app/Actions/Databases/CreateDatabaseHost.php index 873fae553..b07e823f5 100644 --- a/app/Actions/Databases/CreateDatabaseHost.php +++ b/app/Actions/Databases/CreateDatabaseHost.php @@ -26,22 +26,22 @@ final readonly class CreateDatabaseHost implements CreatesDatabaseHosts */ public function create(array $data): DatabaseHost { - return DB::transaction(function () use ($data): DatabaseHost { - $host = DatabaseHost::query()->create([ - 'password' => Crypt::encrypt(Arr::get($data, 'password')), - 'name' => JsonValueGuard::string(Arr::get($data, 'name')), - 'host' => JsonValueGuard::string(Arr::get($data, 'host')), - 'port' => JsonValueGuard::integer(Arr::get($data, 'port')), - 'username' => JsonValueGuard::string(Arr::get($data, 'username')), - 'max_databases' => null, - 'node_id' => JsonValueGuard::nullableInteger(Arr::get($data, 'node_id')), - ]); + $host = DatabaseHost::query()->make([ + 'password' => Crypt::encrypt(Arr::get($data, 'password')), + 'name' => JsonValueGuard::string(Arr::get($data, 'name')), + 'host' => JsonValueGuard::string(Arr::get($data, 'host')), + 'port' => JsonValueGuard::integer(Arr::get($data, 'port')), + 'username' => JsonValueGuard::string(Arr::get($data, 'username')), + 'max_databases' => null, + 'node_id' => JsonValueGuard::nullableInteger(Arr::get($data, 'node_id')), + ]); - // Confirm access using the provided credentials before saving data. - $this->dynamic->set('dynamic', $host); - DB::connection('dynamic')->select('SELECT 1 FROM dual'); + // Confirm access using the provided credentials before saving data. + $this->dynamic->set('dynamic', $host); + DB::connection('dynamic')->select('SELECT 1 FROM dual'); - return $host->refresh(); - }); + $host->save(); + + return $host->refresh(); } } diff --git a/app/Actions/Databases/UpdateDatabaseHost.php b/app/Actions/Databases/UpdateDatabaseHost.php index d4f72440c..d45462948 100644 --- a/app/Actions/Databases/UpdateDatabaseHost.php +++ b/app/Actions/Databases/UpdateDatabaseHost.php @@ -31,12 +31,13 @@ final readonly class UpdateDatabaseHost implements UpdatesDatabaseHosts unset($data['password']); } - return DB::transaction(function () use ($data, $host): DatabaseHost { - $host->update($data); - $this->dynamic->set('dynamic', $host); - DB::connection('dynamic')->select('SELECT 1 FROM dual'); + // Confirm access using the new credentials before saving them. + $host->fill($data); + $this->dynamic->set('dynamic', $host); + DB::connection('dynamic')->select('SELECT 1 FROM dual'); - return $host; - }); + $host->save(); + + return $host; } } diff --git a/app/Actions/Extensions/InstallExtension.php b/app/Actions/Extensions/InstallExtension.php index d24267122..37a847cb4 100644 --- a/app/Actions/Extensions/InstallExtension.php +++ b/app/Actions/Extensions/InstallExtension.php @@ -118,10 +118,10 @@ final readonly class InstallExtension implements InstallsExtensions return $manifest; } - DB::transaction(fn (): Extension => Extension::query()->updateOrCreate( + Extension::query()->updateOrCreate( ['identifier' => $manifest->id], ['version' => $manifest->version, 'error' => null], - )); + ); return $manifest; } diff --git a/app/Actions/Extensions/SetExtensionEnabled.php b/app/Actions/Extensions/SetExtensionEnabled.php index f50aeec88..96f6dd53c 100644 --- a/app/Actions/Extensions/SetExtensionEnabled.php +++ b/app/Actions/Extensions/SetExtensionEnabled.php @@ -79,10 +79,10 @@ final readonly class SetExtensionEnabled implements SetsExtensionEnabled private function persist(ExtensionManifest $manifest, bool $enabled): void { - DB::transaction(fn (): Extension => Extension::query()->updateOrCreate( + Extension::query()->updateOrCreate( ['identifier' => $manifest->id], ['version' => $manifest->version, 'enabled' => $enabled, 'error' => null], - )); + ); } private function runMigrations(ExtensionManifest $manifest): void diff --git a/app/Actions/Servers/UpdateServerDetails.php b/app/Actions/Servers/UpdateServerDetails.php index a00866aa2..9fa642fc6 100644 --- a/app/Actions/Servers/UpdateServerDetails.php +++ b/app/Actions/Servers/UpdateServerDetails.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Servers; +use Illuminate\Foundation\Bus\PendingDispatch; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Pterodactyl\Contracts\Servers\UpdatesServerDetails; @@ -30,8 +31,9 @@ final readonly class UpdateServerDetails implements UpdatesServerDetails ])->saveOrFail(); // Revoke the previous owner's Wings SFTP token after an ownership change. - if (! $server->refresh()->user->is($original)) { - dispatch(new RevokeSftpAccessJob($original->uuid, $server)); + if ($server->owner_id !== $original->id) { + $job = new RevokeSftpAccessJob($original->uuid, $server); + DB::afterCommit(fn (): PendingDispatch => dispatch($job)); } return $server->refresh(); diff --git a/app/Actions/Servers/UpdateServerStartup.php b/app/Actions/Servers/UpdateServerStartup.php index 77d22a75b..276ec9d2b 100644 --- a/app/Actions/Servers/UpdateServerStartup.php +++ b/app/Actions/Servers/UpdateServerStartup.php @@ -60,9 +60,12 @@ final readonly class UpdateServerStartup implements UpdatesServerStartup ])->save(); } - // Calling ->refresh() rather than ->fresh() here causes the - // variables as triplicates for some reason. Not entirely sure why, - // but this operation test covers the behavior and keeps it stable. + // Use fresh() rather than refresh(). refresh() reloads every loaded + // relation through an eager load, which rebuilds Server::variables() + // on a blank model. That relation captures $this->id in its join, so + // the rebuilt join loses the server filter and the reloaded variables + // come back wrong. fresh() returns a new instance and leaves the + // relation unloaded. $fresh = $server->fresh(); throw_if($fresh === null, LogicException::class, 'The modified server no longer exists.'); diff --git a/app/Console/Commands/Environment/DatabaseSettingsCommand.php b/app/Console/Commands/Environment/DatabaseSettingsCommand.php index 1c3f8f52a..a083ffe94 100644 --- a/app/Console/Commands/Environment/DatabaseSettingsCommand.php +++ b/app/Console/Commands/Environment/DatabaseSettingsCommand.php @@ -8,7 +8,7 @@ use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; use Illuminate\Contracts\Console\Kernel; -use Illuminate\Database\DatabaseManager; +use Illuminate\Support\Facades\DB; use PDOException; use Pterodactyl\Exceptions\PterodactylException; use Pterodactyl\Support\JsonValueGuard; @@ -31,7 +31,7 @@ class DatabaseSettingsCommand extends Command /** * DatabaseSettingsCommand constructor. */ - public function __construct(private DatabaseManager $database, private Kernel $console) + public function __construct(private Kernel $console) { parent::__construct(); } @@ -82,7 +82,7 @@ class DatabaseSettingsCommand extends Command $this->output->error('Your connection credentials have NOT been saved. You will need to provide valid connection information before proceeding.'); if ($this->confirm('Go back and try again?')) { - $this->database->disconnect('_pterodactyl_command_test'); + DB::disconnect('_pterodactyl_command_test'); return $this->handle(); } @@ -114,6 +114,6 @@ class DatabaseSettingsCommand extends Command 'strict' => true, ]); - $this->database->connection('_pterodactyl_command_test')->getPdo(); + DB::connection('_pterodactyl_command_test')->getPdo(); } } diff --git a/app/Console/Commands/Environment/EmailSettingsCommand.php b/app/Console/Commands/Environment/EmailSettingsCommand.php index e83ead17e..b6ffb4f6b 100644 --- a/app/Console/Commands/Environment/EmailSettingsCommand.php +++ b/app/Console/Commands/Environment/EmailSettingsCommand.php @@ -7,7 +7,6 @@ namespace Pterodactyl\Console\Commands\Environment; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; -use Illuminate\Contracts\Config\Repository as ConfigRepository; use Pterodactyl\Exceptions\PterodactylException; use Pterodactyl\Support\JsonValueGuard; use Pterodactyl\Traits\Commands\EnvironmentWriterTrait; @@ -30,14 +29,6 @@ class EmailSettingsCommand extends Command /** @var array */ protected array $variables = []; - /** - * EmailSettingsCommand constructor. - */ - public function __construct(private ConfigRepository $config) - { - parent::__construct(); - } - /** * Handle command execution. * @@ -54,7 +45,7 @@ class EmailSettingsCommand extends Command 'mandrill' => 'Mandrill Transactional Email', 'postmark' => 'Postmark Transactional Email', ], - JsonValueGuard::nullableScalarString($this->config->get('mail.default', 'smtp')) + JsonValueGuard::nullableScalarString(config('mail.default', 'smtp')) ); throw_unless(is_string($driver), PterodactylException::class, 'The mail driver selection must resolve to a single value.'); @@ -78,12 +69,12 @@ class EmailSettingsCommand extends Command $this->variables['MAIL_FROM_ADDRESS'] = JsonValueGuard::scalar($this->option('email') ?? $this->ask( trans('command/messages.environment.mail.ask_mail_from'), - JsonValueGuard::nullableScalarString($this->config->get('mail.from.address')) + JsonValueGuard::nullableScalarString(config('mail.from.address')) )); $this->variables['MAIL_FROM_NAME'] = JsonValueGuard::scalar($this->option('from') ?? $this->ask( trans('command/messages.environment.mail.ask_mail_name'), - JsonValueGuard::nullableScalarString($this->config->get('mail.from.name')) + JsonValueGuard::nullableScalarString(config('mail.from.name')) )); $this->writeToEnvironment($this->variables); @@ -99,17 +90,17 @@ class EmailSettingsCommand extends Command { $this->variables['MAIL_HOST'] = JsonValueGuard::scalar($this->option('host') ?? $this->ask( trans('command/messages.environment.mail.ask_smtp_host'), - JsonValueGuard::nullableScalarString($this->config->get('mail.mailers.smtp.host')) + JsonValueGuard::nullableScalarString(config('mail.mailers.smtp.host')) )); $this->variables['MAIL_PORT'] = JsonValueGuard::scalar($this->option('port') ?? $this->ask( trans('command/messages.environment.mail.ask_smtp_port'), - JsonValueGuard::nullableScalarString($this->config->get('mail.mailers.smtp.port')) + JsonValueGuard::nullableScalarString(config('mail.mailers.smtp.port')) )); $this->variables['MAIL_USERNAME'] = JsonValueGuard::scalar($this->option('username') ?? $this->ask( trans('command/messages.environment.mail.ask_smtp_username'), - JsonValueGuard::nullableScalarString($this->config->get('mail.mailers.smtp.username')) + JsonValueGuard::nullableScalarString(config('mail.mailers.smtp.username')) )); $this->variables['MAIL_PASSWORD'] = JsonValueGuard::scalar($this->option('password') ?? $this->secret( @@ -119,7 +110,7 @@ class EmailSettingsCommand extends Command $encryption = $this->option('encryption') ?? $this->choice( trans('command/messages.environment.mail.ask_encryption'), ['tls' => 'TLS', 'ssl' => 'SSL', '' => 'None'], - JsonValueGuard::nullableScalarString($this->config->get('mail.mailers.smtp.encryption', 'tls')) + JsonValueGuard::nullableScalarString(config('mail.mailers.smtp.encryption', 'tls')) ); throw_unless(is_string($encryption), PterodactylException::class, 'The mail encryption selection must resolve to a single value.'); @@ -134,17 +125,17 @@ class EmailSettingsCommand extends Command { $this->variables['MAILGUN_DOMAIN'] = JsonValueGuard::scalar($this->option('host') ?? $this->ask( trans('command/messages.environment.mail.ask_mailgun_domain'), - JsonValueGuard::nullableScalarString($this->config->get('services.mailgun.domain')) + JsonValueGuard::nullableScalarString(config('services.mailgun.domain')) )); $this->variables['MAILGUN_SECRET'] = JsonValueGuard::scalar($this->option('password') ?? $this->ask( trans('command/messages.environment.mail.ask_mailgun_secret'), - JsonValueGuard::nullableScalarString($this->config->get('services.mailgun.secret')) + JsonValueGuard::nullableScalarString(config('services.mailgun.secret')) )); $this->variables['MAILGUN_ENDPOINT'] = JsonValueGuard::scalar($this->option('endpoint') ?? $this->ask( trans('command/messages.environment.mail.ask_mailgun_endpoint'), - JsonValueGuard::nullableScalarString($this->config->get('services.mailgun.endpoint')) + JsonValueGuard::nullableScalarString(config('services.mailgun.endpoint')) )); } @@ -155,7 +146,7 @@ class EmailSettingsCommand extends Command { $this->variables['MANDRILL_SECRET'] = JsonValueGuard::scalar($this->option('password') ?? $this->ask( trans('command/messages.environment.mail.ask_mandrill_secret'), - JsonValueGuard::nullableScalarString($this->config->get('services.mandrill.secret')) + JsonValueGuard::nullableScalarString(config('services.mandrill.secret')) )); } @@ -169,7 +160,7 @@ class EmailSettingsCommand extends Command $this->variables['MAIL_PORT'] = '587'; $credentials = JsonValueGuard::scalar($this->option('username') ?? $this->ask( trans('command/messages.environment.mail.ask_postmark_username'), - JsonValueGuard::nullableScalarString($this->config->get('mail.username')) + JsonValueGuard::nullableScalarString(config('mail.username')) )); $this->variables['MAIL_USERNAME'] = $credentials; $this->variables['MAIL_PASSWORD'] = $credentials; diff --git a/app/Console/Commands/InfoCommand.php b/app/Console/Commands/InfoCommand.php index 546e04a0d..4b6aeecd0 100644 --- a/app/Console/Commands/InfoCommand.php +++ b/app/Console/Commands/InfoCommand.php @@ -7,7 +7,6 @@ namespace Pterodactyl\Console\Commands; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; -use Illuminate\Contracts\Config\Repository as ConfigRepository; use Pterodactyl\Services\Helpers\SoftwareVersionService; use Pterodactyl\Support\JsonValueGuard; @@ -15,7 +14,7 @@ use Pterodactyl\Support\JsonValueGuard; #[Signature('p:info')] class InfoCommand extends Command { - public function __construct(private readonly ConfigRepository $config, private readonly SoftwareVersionService $versionService) + public function __construct(private readonly SoftwareVersionService $versionService) { parent::__construct(); } @@ -27,47 +26,47 @@ class InfoCommand extends Command { $this->output->title('Version Information'); $this->table([], [ - ['Panel Version', $this->config->get('app.version')], + ['Panel Version', config('app.version')], ['Latest Version', $this->versionService->getPanel()], ['Up-to-Date', $this->versionService->isLatestPanel() ? 'Yes' : $this->formatText('No', 'bg=red')], - ['Unique Identifier', $this->config->get('pterodactyl.service.author')], + ['Unique Identifier', config('pterodactyl.service.author')], ], 'compact'); $this->output->title('Application Configuration'); $this->table([], [ - ['Environment', $this->formatText(JsonValueGuard::string($this->config->get('app.env')), $this->config->get('app.env') === 'production' ? '' : 'bg=red')], - ['Debug Mode', $this->formatText($this->config->get('app.debug') ? 'Yes' : 'No', $this->config->get('app.debug') ? 'bg=red' : '')], - ['Installation URL', $this->config->get('app.url')], + ['Environment', $this->formatText(JsonValueGuard::string(config('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()], - ['Timezone', $this->config->get('app.timezone')], - ['Cache Driver', $this->config->get('cache.default')], - ['Queue Driver', $this->config->get('queue.default')], - ['Session Driver', $this->config->get('session.driver')], - ['Filesystem Driver', $this->config->get('filesystems.default')], - ['Default Theme', $this->config->get('themes.active')], - ['Proxies', $this->config->get('trustedproxies.proxies')], + ['Timezone', config('app.timezone')], + ['Cache Driver', config('cache.default')], + ['Queue Driver', config('queue.default')], + ['Session Driver', config('session.driver')], + ['Filesystem Driver', config('filesystems.default')], + ['Default Theme', config('themes.active')], + ['Proxies', config('trustedproxies.proxies')], ], 'compact'); $this->output->title('Database Configuration'); - $driver = JsonValueGuard::string($this->config->get('database.default')); + $driver = JsonValueGuard::string(config('database.default')); $this->table([], [ ['Driver', $driver], - ['Host', $this->config->get("database.connections.$driver.host")], - ['Port', $this->config->get("database.connections.$driver.port")], - ['Database', $this->config->get("database.connections.$driver.database")], - ['Username', $this->config->get("database.connections.$driver.username")], + ['Host', config("database.connections.$driver.host")], + ['Port', config("database.connections.$driver.port")], + ['Database', config("database.connections.$driver.database")], + ['Username', config("database.connections.$driver.username")], ], 'compact'); // TODO: Update this to handle other mail drivers $this->output->title('Email Configuration'); $this->table([], [ - ['Driver', $this->config->get('mail.default')], - ['Host', $this->config->get('mail.mailers.smtp.host')], - ['Port', $this->config->get('mail.mailers.smtp.port')], - ['Username', $this->config->get('mail.mailers.smtp.username')], - ['From Address', $this->config->get('mail.from.address')], - ['From Name', $this->config->get('mail.from.name')], - ['Encryption', $this->config->get('mail.mailers.smtp.encryption')], + ['Driver', config('mail.default')], + ['Host', config('mail.mailers.smtp.host')], + ['Port', config('mail.mailers.smtp.port')], + ['Username', config('mail.mailers.smtp.username')], + ['From Address', config('mail.from.address')], + ['From Name', config('mail.from.name')], + ['Encryption', config('mail.mailers.smtp.encryption')], ], 'compact'); } diff --git a/app/Console/Commands/Maintenance/CleanServiceBackupFilesCommand.php b/app/Console/Commands/Maintenance/CleanServiceBackupFilesCommand.php index 5dd279b1a..f2656bec7 100644 --- a/app/Console/Commands/Maintenance/CleanServiceBackupFilesCommand.php +++ b/app/Console/Commands/Maintenance/CleanServiceBackupFilesCommand.php @@ -7,9 +7,8 @@ namespace Pterodactyl\Console\Commands\Maintenance; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; -use Illuminate\Contracts\Filesystem\Factory as FilesystemFactory; -use Illuminate\Contracts\Filesystem\Filesystem; use Illuminate\Support\Facades\Date; +use Illuminate\Support\Facades\Storage; #[Description('Clean orphaned .bak files created when modifying services.')] #[Signature('p:maintenance:clean-service-backups')] @@ -17,29 +16,18 @@ class CleanServiceBackupFilesCommand extends Command { public const int BACKUP_THRESHOLD_MINUTES = 5; - protected Filesystem $disk; - - /** - * CleanServiceBackupFilesCommand constructor. - */ - public function __construct(FilesystemFactory $filesystem) - { - parent::__construct(); - - $this->disk = $filesystem->disk(); - } - /** * Handle command execution. */ public function handle(): void { - $files = $this->disk->files('services/.bak'); + $disk = Storage::disk(); + $files = $disk->files('services/.bak'); - collect($files)->each(function (string $file): void { - $lastModified = Date::createFromTimestamp($this->disk->lastModified($file)); + collect($files)->each(function (string $file) use ($disk): void { + $lastModified = Date::createFromTimestamp($disk->lastModified($file)); if ($lastModified->diffInMinutes(now()) > self::BACKUP_THRESHOLD_MINUTES) { - $this->disk->delete($file); + $disk->delete($file); $this->info(trans('command/messages.maintenance.deleting_service_backup', ['file' => basename($file)])); } }); diff --git a/app/Extensions/DynamicDatabaseConnection.php b/app/Extensions/DynamicDatabaseConnection.php index f1fdaf8a4..331dc259f 100644 --- a/app/Extensions/DynamicDatabaseConnection.php +++ b/app/Extensions/DynamicDatabaseConnection.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace Pterodactyl\Extensions; -use Illuminate\Config\Repository as ConfigRepository; -use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Support\Facades\Config; +use Illuminate\Support\Facades\Crypt; use Pterodactyl\Models\DatabaseHost; class DynamicDatabaseConnection @@ -17,14 +17,6 @@ class DynamicDatabaseConnection public const string DB_DRIVER = 'mysql'; - /** - * DynamicDatabaseConnection constructor. - */ - public function __construct( - protected ConfigRepository $config, - protected Encrypter $encrypter, - ) {} - /** * Adds a dynamic database connection entry to the runtime config. * @@ -36,13 +28,13 @@ class DynamicDatabaseConnection $host = DatabaseHost::query()->findOrFail($host); } - $this->config->set('database.connections.'.$connection, [ + Config::set('database.connections.'.$connection, [ 'driver' => self::DB_DRIVER, 'host' => $host->host, 'port' => $host->port, 'database' => $database, 'username' => $host->username, - 'password' => $this->encrypter->decrypt($host->password), + 'password' => Crypt::decrypt($host->password), 'charset' => self::DB_CHARSET, 'collation' => self::DB_COLLATION, ]); diff --git a/app/Helpers/Utilities.php b/app/Helpers/Utilities.php index 73d66dec3..89ed1d9db 100644 --- a/app/Helpers/Utilities.php +++ b/app/Helpers/Utilities.php @@ -10,7 +10,6 @@ use Exception; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; -use Illuminate\Support\ViewErrorBag; class Utilities { @@ -48,16 +47,4 @@ class Utilities sprintf('%s %s %s %s %s', $minute, $hour, $dayOfMonth, $month, $dayOfWeek) ))->getNextRunDate()); } - - /** @param bool|int $default */ - public static function checked(string $name, mixed $default): string - { - $errors = session('errors'); - - if (isset($errors) && $errors instanceof ViewErrorBag && $errors->any()) { - return old($name) ? 'checked' : ''; - } - - return ($default) ? 'checked' : ''; - } } diff --git a/app/Http/Controllers/Api/Admin/ApiKeys/ApiKeyController.php b/app/Http/Controllers/Api/Admin/ApiKeys/ApiKeyController.php index f121b0720..c586baa61 100644 --- a/app/Http/Controllers/Api/Admin/ApiKeys/ApiKeyController.php +++ b/app/Http/Controllers/Api/Admin/ApiKeys/ApiKeyController.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace Pterodactyl\Http\Controllers\Api\Admin\ApiKeys; -use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Http\JsonResponse; use Illuminate\Http\Response; +use Illuminate\Support\Facades\Crypt; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\QueryParam; @@ -60,7 +60,7 @@ class ApiKeyController extends AdminApiController */ #[Endpoint('Create API key', 'Creates a new application API key and returns the plaintext secret token once.')] #[ResponseFromTransformer(ApiKeyTransformer::class, ApiKey::class, status: 201, description: 'API key created.', resourceKey: 'api_key', meta: ['secret_token' => 'ptla_1234567890abcdef'])] - public function store(StoreApiKeyRequest $request, Encrypter $encrypter, CreatesApiKeys $keyCreator): JsonResponse + public function store(StoreApiKeyRequest $request, CreatesApiKeys $keyCreator): JsonResponse { $key = $keyCreator->create(ApiKey::TYPE_APPLICATION, [ 'memo' => $request->string('memo')->toString(), @@ -76,7 +76,7 @@ class ApiKeyController extends AdminApiController return Fractal::item($key) ->transformWith($this->getTransformer(ApiKeyTransformer::class)) ->addMeta([ - 'secret_token' => $key->identifier.JsonValueGuard::string($encrypter->decrypt($key->token)), + 'secret_token' => $key->identifier.JsonValueGuard::string(Crypt::decrypt($key->token)), ]) ->respond(Response::HTTP_CREATED); } diff --git a/app/Http/Controllers/Api/Admin/Nodes/DeployTokenController.php b/app/Http/Controllers/Api/Admin/Nodes/DeployTokenController.php index fcbda8a3e..dcfba5d0d 100644 --- a/app/Http/Controllers/Api/Admin/Nodes/DeployTokenController.php +++ b/app/Http/Controllers/Api/Admin/Nodes/DeployTokenController.php @@ -4,8 +4,8 @@ declare(strict_types=1); namespace Pterodactyl\Http\Controllers\Api\Admin\Nodes; -use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Http\JsonResponse; +use Illuminate\Support\Facades\Crypt; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response as ScribeResponse; @@ -35,7 +35,7 @@ class DeployTokenController extends AdminApiController */ #[Endpoint('Create node deploy token', 'Creates or reuses an application API key that can deploy the specified node.')] #[ScribeResponse(self::DEPLOY_TOKEN_EXAMPLE, description: 'Deploy token returned.')] - public function __invoke(DeployTokenRequest $request, CreatesApiKeys $keyCreator, Encrypter $encrypter, Node $node): JsonResponse + public function __invoke(DeployTokenRequest $request, CreatesApiKeys $keyCreator, Node $node): JsonResponse { $permissions = []; foreach (AdminAcl::getResourceList() as $resource) { @@ -63,7 +63,7 @@ class DeployTokenController extends AdminApiController return new JsonResponse([ 'node' => $node->id, - 'token' => $key->identifier.JsonValueGuard::string($encrypter->decrypt($key->token)), + 'token' => $key->identifier.JsonValueGuard::string(Crypt::decrypt($key->token)), 'panel_url' => config('app.url'), 'allow_insecure' => config('app.debug'), ]); diff --git a/app/Http/Controllers/Api/Admin/Settings/MailController.php b/app/Http/Controllers/Api/Admin/Settings/MailController.php index 28d92b125..916c9f503 100644 --- a/app/Http/Controllers/Api/Admin/Settings/MailController.php +++ b/app/Http/Controllers/Api/Admin/Settings/MailController.php @@ -4,11 +4,10 @@ declare(strict_types=1); namespace Pterodactyl\Http\Controllers\Api\Admin\Settings; -use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Contracts\Console\Kernel; -use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Http\Response; use Illuminate\Support\Arr; +use Illuminate\Support\Facades\Crypt; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response as ScribeResponse; @@ -39,9 +38,9 @@ class MailController extends AdminApiController #[Endpoint('Update mail settings', 'Updates SMTP mail settings and restarts queued workers so they reload configuration.')] #[ScribeResponse(status: 204, description: 'Mail settings updated.')] #[ScribeResponse(self::SMTP_DRIVER_ERROR, status: 400, description: 'The panel is not configured to use SMTP mail.')] - public function __invoke(UpdateMailSettingsRequest $request, Kernel $kernel, Encrypter $encrypter, ConfigRepository $config): Response + public function __invoke(UpdateMailSettingsRequest $request, Kernel $kernel): Response { - throw_if($config->get('mail.default') !== 'smtp', DisplayException::class, 'This feature is only available if SMTP is the selected email driver for the Panel.'); + throw_if(config('mail.default') !== 'smtp', DisplayException::class, 'This feature is only available if SMTP is the selected email driver for the Panel.'); $values = $request->normalize(); if (Arr::get($values, 'mail:mailers:smtp:password') === '!e') { @@ -50,7 +49,7 @@ class MailController extends AdminApiController foreach ($values as $key => $value) { if (in_array($key, SettingsServiceProvider::getEncryptedKeys()) && ! empty($value)) { - $value = $encrypter->encrypt($value); + $value = Crypt::encrypt($value); } // SAFETY: settings are persisted in the environment store as strings; null retains its deletion semantics. diff --git a/app/Http/Controllers/Api/Admin/Settings/SettingsController.php b/app/Http/Controllers/Api/Admin/Settings/SettingsController.php index a6978149c..8f52d2868 100644 --- a/app/Http/Controllers/Api/Admin/Settings/SettingsController.php +++ b/app/Http/Controllers/Api/Admin/Settings/SettingsController.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace Pterodactyl\Http\Controllers\Api\Admin\Settings; -use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Http\JsonResponse; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; @@ -55,39 +54,39 @@ class SettingsController extends AdminApiController */ #[Endpoint('Get settings', 'Returns current general, mail, advanced, and metadata settings.')] #[ScribeResponse(self::SETTINGS_EXAMPLE, description: 'Settings returned.')] - public function index(GetSettingsRequest $request, ConfigRepository $config): JsonResponse + public function index(GetSettingsRequest $request): JsonResponse { return new JsonResponse([ 'general' => [ - 'app:name' => $config->get('app.name'), - 'pterodactyl:auth:2fa_required' => JsonValueGuard::integer($config->get('pterodactyl.auth.2fa_required')), - 'app:locale' => $config->get('app.locale'), + 'app:name' => config('app.name'), + 'pterodactyl:auth:2fa_required' => JsonValueGuard::integer(config('pterodactyl.auth.2fa_required')), + 'app:locale' => config('app.locale'), ], 'mail' => [ - 'mail:default' => $config->get('mail.default'), - 'mail:mailers:smtp:host' => $config->get('mail.mailers.smtp.host'), - 'mail:mailers:smtp:port' => JsonValueGuard::integer($config->get('mail.mailers.smtp.port')), - 'mail:mailers:smtp:encryption' => $config->get('mail.mailers.smtp.encryption'), - 'mail:mailers:smtp:username' => $config->get('mail.mailers.smtp.username'), + '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:encryption' => config('mail.mailers.smtp.encryption'), + 'mail:mailers:smtp:username' => config('mail.mailers.smtp.username'), // Never return the SMTP password to the client. 'mail:mailers:smtp:password' => '', - 'mail:from:address' => $config->get('mail.from.address'), - 'mail:from:name' => $config->get('mail.from.name'), + 'mail:from:address' => config('mail.from.address'), + 'mail:from:name' => config('mail.from.name'), ], 'advanced' => [ - 'recaptcha:enabled' => JsonValueGuard::boolean($config->get('recaptcha.enabled')), + 'recaptcha:enabled' => JsonValueGuard::boolean(config('recaptcha.enabled')), 'recaptcha:secret_key' => '', - 'recaptcha:website_key' => $config->get('recaptcha.website_key'), - 'pterodactyl:guzzle:timeout' => JsonValueGuard::integer($config->get('pterodactyl.guzzle.timeout')), - 'pterodactyl:guzzle:connect_timeout' => JsonValueGuard::integer($config->get('pterodactyl.guzzle.connect_timeout')), - 'pterodactyl:client_features:allocations:enabled' => JsonValueGuard::boolean($config->get('pterodactyl.client_features.allocations.enabled')), - 'pterodactyl:client_features:allocations:range_start' => $config->get('pterodactyl.client_features.allocations.range_start'), - 'pterodactyl:client_features:allocations:range_end' => $config->get('pterodactyl.client_features.allocations.range_end'), + '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: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->get('pterodactyl.load_environment_only', false)), - 'show_recaptcha_warning' => $config->get('recaptcha._shipped_secret_key') === $config->get('recaptcha.secret_key') - || $config->get('recaptcha._shipped_website_key') === $config->get('recaptcha.website_key'), + 'load_environment_only' => JsonValueGuard::boolean(config('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/Api/Admin/Tags/TagController.php b/app/Http/Controllers/Api/Admin/Tags/TagController.php index ead1313f2..bb4f723fd 100644 --- a/app/Http/Controllers/Api/Admin/Tags/TagController.php +++ b/app/Http/Controllers/Api/Admin/Tags/TagController.php @@ -134,7 +134,7 @@ class TagController extends AdminApiController ->property('slug', $tag->slug) ->log(); - return Fractal::item($tag->refresh()) + return Fractal::item($tag) ->transformWith($this->getTransformer(TagTransformer::class)) ->toResponseArray(); } diff --git a/app/Http/Controllers/Api/Client/Servers/StartupController.php b/app/Http/Controllers/Api/Client/Servers/StartupController.php index bf79cf8e0..e74949c23 100644 --- a/app/Http/Controllers/Api/Client/Servers/StartupController.php +++ b/app/Http/Controllers/Api/Client/Servers/StartupController.php @@ -83,7 +83,6 @@ class StartupController extends ClientApiController ['variable_value' => $value ?? ''], ); - $variable->refresh(); $variable->server_value = $value; $startup = $startupCommand->handle($server); diff --git a/app/Http/Controllers/Auth/LoginCheckpointController.php b/app/Http/Controllers/Auth/LoginCheckpointController.php index 9e5a0d28e..e56164c74 100644 --- a/app/Http/Controllers/Auth/LoginCheckpointController.php +++ b/app/Http/Controllers/Auth/LoginCheckpointController.php @@ -5,9 +5,9 @@ declare(strict_types=1); namespace Pterodactyl\Http\Controllers\Auth; use Exception; -use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Http\JsonResponse; +use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\ValidationException; @@ -80,7 +80,7 @@ class LoginCheckpointController extends AbstractLoginController #[BodyParam('recovery_token', 'string', 'A recovery token. Required when authentication_code is not provided.', required: false, example: 'r1a2b3c4d5', nullable: true)] #[ScribeResponse(self::LOGIN_COMPLETE_EXAMPLE, description: 'Login completed and a browser session was created.')] #[ScribeResponse(self::CHECKPOINT_FAILED_ERROR, status: 400, description: 'The checkpoint token, TOTP code, or recovery token is invalid.')] - public function __invoke(LoginCheckpointRequest $request, CompletesLogins $logins, Google2FA $google2FA, Encrypter $encrypter): JsonResponse + public function __invoke(LoginCheckpointRequest $request, CompletesLogins $logins, Google2FA $google2FA): JsonResponse { if ($this->hasTooManyLoginAttempts($request)) { $this->sendLockoutResponse($request); @@ -114,7 +114,7 @@ class LoginCheckpointController extends AbstractLoginController $this->sendFailedLoginResponse($request, $user, self::TOKEN_EXPIRED_MESSAGE); } - $decrypted = JsonValueGuard::string($encrypter->decrypt($totpSecret)); + $decrypted = JsonValueGuard::string(Crypt::decrypt($totpSecret)); // SAFETY: TOTP counters are discrete intervals, so flooring and converting the quotient to an integer is required. $oldTimestamp = $user->totp_authenticated_at ? (int) floor($user->totp_authenticated_at->unix() / $google2FA->getKeyRegeneration()) diff --git a/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php b/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php index afb775350..1c72d3191 100644 --- a/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php +++ b/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php @@ -5,8 +5,8 @@ declare(strict_types=1); namespace Pterodactyl\Http\Middleware\Api\Daemon; use Closure; -use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Crypt; use Pterodactyl\Http\Concerns\ResolvesRequestContext; use Pterodactyl\Models\Node; use Symfony\Component\HttpFoundation\Response; @@ -27,11 +27,6 @@ class DaemonAuthenticate 'daemon.configuration', ]; - /** - * DaemonAuthenticate constructor. - */ - public function __construct(private readonly Encrypter $encrypter) {} - /** * Check if a request from the daemon can be properly attributed back to a single node instance. * @@ -56,7 +51,7 @@ class DaemonAuthenticate // Unknown token ids and wrong tokens fail identically. $node = Node::query()->where('daemon_token_id', $parts[0])->first(); if ($node !== null) { - $token = $this->encrypter->decrypt($node->daemon_token); + $token = Crypt::decrypt($node->daemon_token); throw_unless(is_string($token), AccessDeniedHttpException::class, 'The authentication token provided is not valid.'); if (hash_equals($token, $parts[1])) { diff --git a/app/Http/Middleware/MaintenanceMiddleware.php b/app/Http/Middleware/MaintenanceMiddleware.php index 4f7e3958b..6a7c11ee0 100644 --- a/app/Http/Middleware/MaintenanceMiddleware.php +++ b/app/Http/Middleware/MaintenanceMiddleware.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Pterodactyl\Http\Middleware; use Closure; -use Illuminate\Contracts\Routing\ResponseFactory; use Illuminate\Http\Request; use InvalidArgumentException; use Pterodactyl\Models\Node; @@ -14,11 +13,6 @@ use Symfony\Component\HttpFoundation\Response; class MaintenanceMiddleware { - /** - * MaintenanceMiddleware constructor. - */ - public function __construct(private readonly ResponseFactory $response) {} - /** * Handle an incoming request. */ @@ -35,7 +29,7 @@ class MaintenanceMiddleware throw_unless($node instanceof Node, InvalidArgumentException::class, 'The maintenance middleware requires the server node relation.'); if ($node->maintenance_mode) { - return $this->response->view('errors.maintenance'); + return response()->view('errors.maintenance'); } return $next($request); diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index 9fbcc4ff7..5531ef626 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -5,17 +5,12 @@ declare(strict_types=1); namespace Pterodactyl\Http\Middleware; use Closure; -use Illuminate\Auth\AuthManager; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Auth; use Symfony\Component\HttpFoundation\Response; class RedirectIfAuthenticated { - /** - * RedirectIfAuthenticated constructor. - */ - public function __construct(private readonly AuthManager $authManager) {} - /** * Handle an incoming request. */ @@ -25,7 +20,7 @@ class RedirectIfAuthenticated */ public function handle(Request $request, Closure $next, ?string $guard = null): mixed { - if ($this->authManager->guard($guard)->check()) { + if (Auth::guard($guard)->check()) { return to_route('index'); } diff --git a/app/Http/Middleware/RequireTwoFactorAuthentication.php b/app/Http/Middleware/RequireTwoFactorAuthentication.php index 12afab9c4..9cab49a9e 100644 --- a/app/Http/Middleware/RequireTwoFactorAuthentication.php +++ b/app/Http/Middleware/RequireTwoFactorAuthentication.php @@ -8,8 +8,8 @@ use Closure; use Illuminate\Http\Request; use Illuminate\Support\Str; use Pterodactyl\Exceptions\Http\TwoFactorAuthRequiredException; +use Pterodactyl\Facades\Alert; use Pterodactyl\Http\Concerns\ResolvesRequestContext; -use Pterodactyl\Support\Alerts\AlertsMessageBag; use Symfony\Component\HttpFoundation\Response; class RequireTwoFactorAuthentication @@ -27,11 +27,6 @@ class RequireTwoFactorAuthentication */ protected string $redirectRoute = '/account'; - /** - * RequireTwoFactorAuthentication constructor. - */ - public function __construct(private readonly AlertsMessageBag $alert) {} - /** * Check the user state on the incoming request to determine if they should be allowed to * proceed or not. This checks if the Panel is configured to require 2FA on an account in @@ -71,7 +66,7 @@ class RequireTwoFactorAuthentication // For API calls return an exception which gets rendered nicely in the API response. throw_if($request->isJson() || Str::startsWith($uri, '/api/'), TwoFactorAuthRequiredException::class); - $this->alert->danger(trans('auth.2fa_must_be_enabled'))->flash(); + Alert::danger(trans('auth.2fa_must_be_enabled'))->flash(); return redirect()->to($this->redirectRoute); } diff --git a/app/Http/Middleware/VerifyReCaptcha.php b/app/Http/Middleware/VerifyReCaptcha.php index 0a0dd3848..547b30073 100644 --- a/app/Http/Middleware/VerifyReCaptcha.php +++ b/app/Http/Middleware/VerifyReCaptcha.php @@ -7,8 +7,6 @@ namespace Pterodactyl\Http\Middleware; use Closure; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; -use Illuminate\Contracts\Config\Repository; -use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Arr; @@ -18,11 +16,6 @@ use Symfony\Component\HttpKernel\Exception\HttpException; class VerifyReCaptcha { - /** - * VerifyReCaptcha constructor. - */ - public function __construct(private readonly Dispatcher $dispatcher, private readonly Repository $config) {} - /** * Handle an incoming request. */ @@ -32,19 +25,19 @@ class VerifyReCaptcha */ public function handle(Request $request, Closure $next): mixed { - if (! $this->config->get('recaptcha.enabled')) { + if (! config('recaptcha.enabled')) { return $next($request); } $result = $this->verifyCaptcha($request); - $domainValid = ! $this->config->get('recaptcha.verify_domain') || $this->isResponseVerified($result, $request); + $domainValid = ! config('recaptcha.verify_domain') || $this->isResponseVerified($result, $request); if ($result['success'] && $domainValid) { return $next($request); } - $this->dispatcher->dispatch( + event( new FailedCaptcha( $request->ip() ?? 'unknown', $result['hostname'] ?? 'unknown' @@ -65,9 +58,9 @@ class VerifyReCaptcha try { $client = new Client(['timeout' => 5, 'connect_timeout' => 2]); - $res = $client->post(JsonValueGuard::string($this->config->get('recaptcha.domain')), [ + $res = $client->post(JsonValueGuard::string(config('recaptcha.domain')), [ 'form_params' => [ - 'secret' => $this->config->get('recaptcha.secret_key'), + 'secret' => config('recaptcha.secret_key'), 'response' => $request->input('g-recaptcha-response'), ], ]); diff --git a/app/Services/Activity/ActivityLogService.php b/app/Services/Activity/ActivityLogService.php index 4faa5bc28..ce5ffa68e 100644 --- a/app/Services/Activity/ActivityLogService.php +++ b/app/Services/Activity/ActivityLogService.php @@ -6,11 +6,11 @@ namespace Pterodactyl\Services\Activity; use Closure; use Illuminate\Contracts\Auth\Authenticatable; -use Illuminate\Contracts\Auth\Factory as AuthFactory; -use Illuminate\Database\ConnectionInterface; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Request; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use InvalidArgumentException; use Pterodactyl\Models\ActivityLog; @@ -27,10 +27,8 @@ class ActivityLogService protected array $subjects = []; public function __construct( - protected AuthFactory $manager, protected ActivityLogBatchService $batch, protected ActivityLogTargetableService $targetable, - protected ConnectionInterface $connection, protected Request $request, ) {} @@ -191,7 +189,7 @@ class ActivityLogService */ public function transaction(Closure $callback): array|bool|float|int|object|string|null { - return $this->connection->transaction(function () use ($callback) { + return DB::transaction(function () use ($callback) { $response = $callback($this); $this->save(); @@ -231,7 +229,7 @@ class ActivityLogService if (($actor = $this->targetable->actor()) instanceof Model) { $this->actor($actor); - } elseif (($user = $this->manager->guard()->user()) !== null) { + } elseif (($user = Auth::guard()->user()) !== null) { $this->actor($user); } @@ -248,7 +246,7 @@ class ActivityLogService throw_unless($this->activity instanceof ActivityLog, InvalidArgumentException::class, 'Cannot save an activity log before one has been initialized.'); $activity = $this->activity; - $response = $this->connection->transaction(function () use ($activity): ActivityLog { + $response = DB::transaction(function () use ($activity): ActivityLog { $activity->save(); $subjects = Collection::make($this->subjects) diff --git a/app/Services/Databases/DatabaseHostGateway.php b/app/Services/Databases/DatabaseHostGateway.php index 3827fcbed..6ca818c8c 100644 --- a/app/Services/Databases/DatabaseHostGateway.php +++ b/app/Services/Databases/DatabaseHostGateway.php @@ -4,7 +4,7 @@ declare(strict_types=1); namespace Pterodactyl\Services\Databases; -use Illuminate\Database\DatabaseManager; +use Illuminate\Support\Facades\DB; /** * Runs the administrative statements (databases, users, grants) against a @@ -16,8 +16,6 @@ class DatabaseHostGateway private string $connection = self::DEFAULT_CONNECTION_NAME; - public function __construct(private readonly DatabaseManager $database) {} - /** * Set the connection name to execute statements against. */ @@ -99,6 +97,6 @@ class DatabaseHostGateway private function run(string $statement): bool { - return $this->database->connection($this->getConnection())->statement($statement); + return DB::connection($this->getConnection())->statement($statement); } } diff --git a/app/Services/Helpers/AssetHashService.php b/app/Services/Helpers/AssetHashService.php index fcffe3216..d4589d462 100644 --- a/app/Services/Helpers/AssetHashService.php +++ b/app/Services/Helpers/AssetHashService.php @@ -64,14 +64,6 @@ class AssetHashService return $this->entry($resource)['integrity'] ?? ''; } - /** - * Return a built CSS import using the provided URL. - */ - public function css(string $resource): string - { - return $this->stylesheetTag($this->url($resource), $this->integrity($resource)); - } - /** * Return stylesheet tags for CSS emitted with a JS entry. */ diff --git a/app/Services/Helpers/SoftwareVersionService.php b/app/Services/Helpers/SoftwareVersionService.php index 03b506986..b67dbf792 100644 --- a/app/Services/Helpers/SoftwareVersionService.php +++ b/app/Services/Helpers/SoftwareVersionService.php @@ -70,18 +70,6 @@ class SoftwareVersionService return version_compare(JsonValueGuard::string(config('app.version')), $this->getPanel()) >= 0; } - /** - * Determine if a passed daemon version string is the latest. - */ - public function isLatestDaemon(string $version): bool - { - if ($version === 'develop') { - return true; - } - - return version_compare($version, $this->getDaemon()) >= 0; - } - /** * Keeps the versioning cache up-to-date with the latest results from the CDN. * diff --git a/tests/Integration/Services/Allocations/FindAssignableAllocationServiceTest.php b/tests/Integration/Actions/Allocations/AssignAvailableAllocationTest.php similarity index 98% rename from tests/Integration/Services/Allocations/FindAssignableAllocationServiceTest.php rename to tests/Integration/Actions/Allocations/AssignAvailableAllocationTest.php index d8935b1af..6ec7ca40f 100644 --- a/tests/Integration/Services/Allocations/FindAssignableAllocationServiceTest.php +++ b/tests/Integration/Actions/Allocations/AssignAvailableAllocationTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Allocations\FindAssignableAllocationServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Allocations\AssignAvailableAllocationTest; use Exception; use Illuminate\Foundation\Testing\DatabaseTransactions; diff --git a/tests/Integration/Services/Backups/DeleteBackupServiceTest.php b/tests/Integration/Actions/Backups/DeleteBackupTest.php similarity index 97% rename from tests/Integration/Services/Backups/DeleteBackupServiceTest.php rename to tests/Integration/Actions/Backups/DeleteBackupTest.php index 09b698ef2..aad61b2ab 100644 --- a/tests/Integration/Services/Backups/DeleteBackupServiceTest.php +++ b/tests/Integration/Actions/Backups/DeleteBackupTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Backups\DeleteBackupServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Backups\DeleteBackupTest; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\Http; diff --git a/tests/Integration/Services/Backups/DownloadLinkServiceTest.php b/tests/Integration/Actions/Backups/GenerateBackupDownloadLinkTest.php similarity index 95% rename from tests/Integration/Services/Backups/DownloadLinkServiceTest.php rename to tests/Integration/Actions/Backups/GenerateBackupDownloadLinkTest.php index 8c1e4d59a..2ef738df0 100644 --- a/tests/Integration/Services/Backups/DownloadLinkServiceTest.php +++ b/tests/Integration/Actions/Backups/GenerateBackupDownloadLinkTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Backups\DownloadLinkServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Backups\GenerateBackupDownloadLinkTest; use Carbon\CarbonImmutable; use Illuminate\Foundation\Testing\DatabaseTransactions; diff --git a/tests/Integration/Services/Databases/DatabaseManagementServiceTest.php b/tests/Integration/Actions/Databases/CreateDatabaseTest.php similarity index 98% rename from tests/Integration/Services/Databases/DatabaseManagementServiceTest.php rename to tests/Integration/Actions/Databases/CreateDatabaseTest.php index 4508068fc..ba914c6c3 100644 --- a/tests/Integration/Services/Databases/DatabaseManagementServiceTest.php +++ b/tests/Integration/Actions/Databases/CreateDatabaseTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Databases\DatabaseManagementServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Databases\CreateDatabaseTest; use BadMethodCallException; use Illuminate\Foundation\Testing\DatabaseTransactions; diff --git a/tests/Integration/Services/Databases/DeployServerDatabaseServiceTest.php b/tests/Integration/Actions/Databases/DeployServerDatabaseTest.php similarity index 97% rename from tests/Integration/Services/Databases/DeployServerDatabaseServiceTest.php rename to tests/Integration/Actions/Databases/DeployServerDatabaseTest.php index c0bea2d36..386386161 100644 --- a/tests/Integration/Services/Databases/DeployServerDatabaseServiceTest.php +++ b/tests/Integration/Actions/Databases/DeployServerDatabaseTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Databases\DeployServerDatabaseServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Databases\DeployServerDatabaseTest; use Illuminate\Foundation\Testing\DatabaseTransactions; use InvalidArgumentException; diff --git a/tests/Integration/Services/Databases/DatabasePasswordServiceTest.php b/tests/Integration/Actions/Databases/RotateDatabasePasswordTest.php similarity index 96% rename from tests/Integration/Services/Databases/DatabasePasswordServiceTest.php rename to tests/Integration/Actions/Databases/RotateDatabasePasswordTest.php index 6e6f7a643..b984cc6f2 100644 --- a/tests/Integration/Services/Databases/DatabasePasswordServiceTest.php +++ b/tests/Integration/Actions/Databases/RotateDatabasePasswordTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Databases\DatabasePasswordServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Databases\RotateDatabasePasswordTest; use Illuminate\Foundation\Testing\DatabaseTransactions; use Pterodactyl\Contracts\Databases\RotatesDatabasePasswords; diff --git a/tests/Integration/Services/Schedules/ProcessScheduleServiceTest.php b/tests/Integration/Actions/Schedules/ProcessScheduleTest.php similarity index 98% rename from tests/Integration/Services/Schedules/ProcessScheduleServiceTest.php rename to tests/Integration/Actions/Schedules/ProcessScheduleTest.php index 854121e97..d95a60a4d 100644 --- a/tests/Integration/Services/Schedules/ProcessScheduleServiceTest.php +++ b/tests/Integration/Actions/Schedules/ProcessScheduleTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Schedules\ProcessScheduleServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Schedules\ProcessScheduleTest; use Carbon\CarbonImmutable; use Exception; diff --git a/tests/Integration/Services/Servers/ServerCreationServiceTest.php b/tests/Integration/Actions/Servers/CreateServerTest.php similarity index 98% rename from tests/Integration/Services/Servers/ServerCreationServiceTest.php rename to tests/Integration/Actions/Servers/CreateServerTest.php index fe1522c03..a5e75c6ab 100644 --- a/tests/Integration/Services/Servers/ServerCreationServiceTest.php +++ b/tests/Integration/Actions/Servers/CreateServerTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Servers\ServerCreationServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Servers\CreateServerTest; use Illuminate\Database\Eloquent\Collection; use Illuminate\Foundation\Testing\DatabaseTransactions; diff --git a/tests/Integration/Services/Servers/ServerDeletionServiceTest.php b/tests/Integration/Actions/Servers/DeleteServerTest.php similarity index 98% rename from tests/Integration/Services/Servers/ServerDeletionServiceTest.php rename to tests/Integration/Actions/Servers/DeleteServerTest.php index f3c21a1fd..b5a43b3fd 100644 --- a/tests/Integration/Services/Servers/ServerDeletionServiceTest.php +++ b/tests/Integration/Actions/Servers/DeleteServerTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Servers\ServerDeletionServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Servers\DeleteServerTest; use Exception; use Illuminate\Foundation\Testing\DatabaseTransactions; diff --git a/tests/Integration/Services/Servers/SuspensionServiceTest.php b/tests/Integration/Actions/Servers/ToggleServerSuspensionTest.php similarity index 97% rename from tests/Integration/Services/Servers/SuspensionServiceTest.php rename to tests/Integration/Actions/Servers/ToggleServerSuspensionTest.php index 0e2d8831e..650c1fb43 100644 --- a/tests/Integration/Services/Servers/SuspensionServiceTest.php +++ b/tests/Integration/Actions/Servers/ToggleServerSuspensionTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Servers\SuspensionServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Servers\ToggleServerSuspensionTest; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\Event; diff --git a/tests/Integration/Services/Servers/BuildModificationServiceTest.php b/tests/Integration/Actions/Servers/UpdateServerBuildTest.php similarity index 98% rename from tests/Integration/Services/Servers/BuildModificationServiceTest.php rename to tests/Integration/Actions/Servers/UpdateServerBuildTest.php index 2cb88fe3b..13609b13e 100644 --- a/tests/Integration/Services/Servers/BuildModificationServiceTest.php +++ b/tests/Integration/Actions/Servers/UpdateServerBuildTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Servers\BuildModificationServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Servers\UpdateServerBuildTest; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\Http; diff --git a/tests/Integration/Services/Servers/StartupModificationServiceTest.php b/tests/Integration/Actions/Servers/UpdateServerStartupTest.php similarity index 98% rename from tests/Integration/Services/Servers/StartupModificationServiceTest.php rename to tests/Integration/Actions/Servers/UpdateServerStartupTest.php index 5976e6f43..5bdf6c344 100644 --- a/tests/Integration/Services/Servers/StartupModificationServiceTest.php +++ b/tests/Integration/Actions/Servers/UpdateServerStartupTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Servers\StartupModificationServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Servers\UpdateServerStartupTest; use Exception; use Illuminate\Database\Eloquent\ModelNotFoundException; diff --git a/tests/Integration/Services/Users/UserDeletionServiceTest.php b/tests/Integration/Actions/Users/DeleteUserTest.php similarity index 95% rename from tests/Integration/Services/Users/UserDeletionServiceTest.php rename to tests/Integration/Actions/Users/DeleteUserTest.php index 48feba3f9..c63786bc3 100644 --- a/tests/Integration/Services/Users/UserDeletionServiceTest.php +++ b/tests/Integration/Actions/Users/DeleteUserTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Pterodactyl\Tests\Pest\Integration\Services\Users\UserDeletionServiceTest; +namespace Pterodactyl\Tests\Pest\Integration\Actions\Users\DeleteUserTest; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\Bus; diff --git a/tests/Support/Fakes/FakeSoftwareVersionService.php b/tests/Support/Fakes/FakeSoftwareVersionService.php index 45911afe1..aadf0e403 100644 --- a/tests/Support/Fakes/FakeSoftwareVersionService.php +++ b/tests/Support/Fakes/FakeSoftwareVersionService.php @@ -50,13 +50,4 @@ class FakeSoftwareVersionService extends SoftwareVersionService { return $this->isLatestPanel; } - - public function isLatestDaemon(string $version): bool - { - if ($version === 'develop') { - return true; - } - - return version_compare($version, $this->daemon) >= 0; - } } diff --git a/tests/Unit/ArchTest.php b/tests/Unit/ArchTest.php index 86c30426f..1f2788481 100644 --- a/tests/Unit/ArchTest.php +++ b/tests/Unit/ArchTest.php @@ -22,6 +22,8 @@ use Illuminate\Support\ServiceProvider; use Pterodactyl\Exceptions\ApiErrorResponse; use Pterodactyl\Extensions\ExtensionProvider; use Pterodactyl\Http\Requests\Api\Remote\RemoteRequestNode; +use Pterodactyl\Services\Extensions\ExtensionRepository; +use Pterodactyl\Services\Tags\TagBackfiller; use Pterodactyl\Transformers\Api\Admin\UserTransformer as AdminUserTransformer; use Pterodactyl\Transformers\Api\Client\UserTransformer as ClientUserTransformer; use Pterodactyl\Transformers\Concerns\FormatsActivityLogs; @@ -48,19 +50,30 @@ arch('no sleeping, debugging, or environment reads outside config') ->not->toBeUsed() ->ignoring('Pterodactyl\Tests'); -arch('actions use facades for framework services') - ->expect('Pterodactyl\Actions') - ->not->toUse([ - AuthManager::class, - PasswordBroker::class, - Dispatcher::class, - Repository::class, - Encrypter::class, - EventDispatcher::class, - Connection::class, - ConnectionInterface::class, - DatabaseManager::class, - ]); +// One rule per namespace: Pest silently passes multi-target expect([...]) here. +foreach ([ + 'Pterodactyl\Actions' => [], + 'Pterodactyl\Console' => [], + 'Pterodactyl\Http' => [], + // Deliberate seams: the tags migration hands the backfiller the connection it + // runs on, and the extension repository resolves during provider boot. + 'Pterodactyl\Services' => [TagBackfiller::class, ExtensionRepository::class], +] as $namespace => $seams) { + arch("{$namespace} uses facades for framework services") + ->expect($namespace) + ->not->toUse([ + AuthManager::class, + PasswordBroker::class, + Dispatcher::class, + Repository::class, + Encrypter::class, + EventDispatcher::class, + Connection::class, + ConnectionInterface::class, + DatabaseManager::class, + ]) + ->ignoring($seams); +} arch('controllers') ->expect('Pterodactyl\Http\Controllers') diff --git a/tests/Unit/Http/Middleware/MaintenanceMiddlewareTest.php b/tests/Unit/Http/Middleware/MaintenanceMiddlewareTest.php index 88f96028a..a591c6e25 100644 --- a/tests/Unit/Http/Middleware/MaintenanceMiddlewareTest.php +++ b/tests/Unit/Http/Middleware/MaintenanceMiddlewareTest.php @@ -56,6 +56,6 @@ test('rejects servers with an invalid node relation', function () { function getMiddleware(): MaintenanceMiddleware { return (function () { - return new MaintenanceMiddleware($this->app->make(ResponseFactory::class)); + return new MaintenanceMiddleware(); })->call(pterodactylTestCase()); } diff --git a/tests/Unit/Http/Middleware/RedirectIfAuthenticatedTest.php b/tests/Unit/Http/Middleware/RedirectIfAuthenticatedTest.php index 09eb72dfc..44affa59f 100644 --- a/tests/Unit/Http/Middleware/RedirectIfAuthenticatedTest.php +++ b/tests/Unit/Http/Middleware/RedirectIfAuthenticatedTest.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace Pterodactyl\Tests\Pest\Unit\Http\Middleware\RedirectIfAuthenticatedTest; -use Illuminate\Auth\AuthManager; use Illuminate\Http\RedirectResponse; use Pterodactyl\Http\Middleware\RedirectIfAuthenticated; use Pterodactyl\Models\User; @@ -24,5 +23,5 @@ test('non authenticated user is not redirected', function () { */ function getMiddleware(): RedirectIfAuthenticated { - return new RedirectIfAuthenticated(app(AuthManager::class)); + return new RedirectIfAuthenticated; }