From fb08b51ae83ac34f7b471f5f007ea10e2ee6b042 Mon Sep 17 00:00:00 2001 From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com> Date: Wed, 7 Oct 2026 16:22:56 -0400 Subject: [PATCH] composer package checks --- .../Commands/Extensions/DoctorCommand.php | 7 +- .../Commands/Extensions/PackCommand.php | 12 +- .../Extensions/ExtensionComposerInspector.php | 142 ++++++++++++++++++ .../Extensions/ExtensionManifestValidator.php | 45 +++++- .../Scaffolding/ExtensionScaffolder.php | 21 ++- .../Scaffolding/stubs/gitignore.stub | 1 + .../Extensions/Scaffolding/stubs/readme.stub | 19 ++- packages/sdk/README.md | 13 +- packages/sdk/manifest.schema.json | 2 +- .../Extensions/ExtensionManifestTest.php | 25 +++ .../Extensions/ExtensionScaffolderTest.php | 8 + .../Extensions/ExtensionToolingTest.php | 43 ++++++ tools/phpstan/rules/extension.neon | 1 + 13 files changed, 321 insertions(+), 18 deletions(-) diff --git a/app/Console/Commands/Extensions/DoctorCommand.php b/app/Console/Commands/Extensions/DoctorCommand.php index 85397f3d7..937ca9e4a 100644 --- a/app/Console/Commands/Extensions/DoctorCommand.php +++ b/app/Console/Commands/Extensions/DoctorCommand.php @@ -10,6 +10,7 @@ use Illuminate\Console\Command; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; use Pterodactyl\Services\Extensions\ExtensionAssetPublisher; use Pterodactyl\Services\Extensions\ExtensionCompatibility; +use Pterodactyl\Services\Extensions\ExtensionComposerInspector; use Pterodactyl\Services\Extensions\ExtensionIconCatalog; use Pterodactyl\Services\Extensions\ExtensionManifestValidator; use Pterodactyl\Services\Extensions\ExtensionRepository; @@ -18,7 +19,7 @@ use Pterodactyl\Services\Extensions\ExtensionRepository; #[Signature('p:extension:doctor {path : Path to an unpacked extension package.}')] class DoctorCommand extends Command { - public function handle(ExtensionManifestValidator $validator, ExtensionCompatibility $compatibility, ExtensionRepository $extensions, ExtensionAssetPublisher $assets, ExtensionIconCatalog $icons): int + public function handle(ExtensionManifestValidator $validator, ExtensionCompatibility $compatibility, ExtensionRepository $extensions, ExtensionAssetPublisher $assets, ExtensionIconCatalog $icons, ExtensionComposerInspector $composer): int { try { $manifest = $validator->fromDirectory($this->argument('path')); @@ -41,6 +42,10 @@ class DoctorCommand extends Command $this->components->warn($problem.' The extension list shows its initials instead.'); } + foreach ($composer->warnings($manifest) as $warning) { + $this->components->warn($warning); + } + $this->components->info("{$manifest->id} v{$manifest->version}: manifest, compatibility, autoload directories, and build passed."); return self::SUCCESS; diff --git a/app/Console/Commands/Extensions/PackCommand.php b/app/Console/Commands/Extensions/PackCommand.php index 9920b6cae..eaa973d2e 100644 --- a/app/Console/Commands/Extensions/PackCommand.php +++ b/app/Console/Commands/Extensions/PackCommand.php @@ -11,6 +11,7 @@ use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; use Pterodactyl\Services\Extensions\ExtensionAssetPublisher; +use Pterodactyl\Services\Extensions\ExtensionComposerInspector; use Pterodactyl\Services\Extensions\ExtensionManifest; use Pterodactyl\Services\Extensions\ExtensionManifestValidator; use ZipArchive; @@ -19,11 +20,15 @@ use ZipArchive; #[Signature('p:extension:pack {path : Path to the unpacked extension.} {--output= : Archive filename.} {--force : Overwrite an existing archive.}')] class PackCommand extends Command { - public function handle(ExtensionManifestValidator $validator, ExtensionAssetPublisher $assets): int + public function handle(ExtensionManifestValidator $validator, ExtensionAssetPublisher $assets, ExtensionComposerInspector $composer): int { try { $manifest = $validator->fromDirectory($this->argument('path')); throw_if($reason = $assets->unusableBuildReason($manifest), InvalidExtensionException::class, $reason); + foreach ($composer->warnings($manifest) as $warning) { + $this->components->warn($warning); + } + $output = $this->option('output') ?: getcwd().DIRECTORY_SEPARATOR.$manifest->id.'-'.$manifest->version.'.pteroext'; throw_if(is_file($output) && ! $this->option('force'), InvalidExtensionException::class, 'Archive exists; pass --force to overwrite it.'); File::ensureDirectoryExists(dirname($output)); @@ -34,6 +39,11 @@ class PackCommand extends Command throw_unless($zip->open($temporary, ZipArchive::CREATE | ZipArchive::EXCL) === true, InvalidExtensionException::class, 'Unable to open archive.'); $opened = true; throw_unless($zip->addFile($manifest->path(ExtensionManifest::FILENAME), ExtensionManifest::FILENAME), InvalidExtensionException::class, 'Unable to add extension manifest to archive.'); + // The panel reads the PSR-4 map from composer.json when the manifest has none. + if (is_file($manifest->path('composer.json'))) { + throw_unless($zip->addFile($manifest->path('composer.json'), 'composer.json'), InvalidExtensionException::class, 'Unable to add composer.json to archive.'); + } + $directories = array_unique(['routes', 'database', 'resources', 'dist', 'vendor', ...array_values($manifest->autoload)]); foreach ($directories as $directory) { if (! is_dir($manifest->path($directory))) { diff --git a/app/Services/Extensions/ExtensionComposerInspector.php b/app/Services/Extensions/ExtensionComposerInspector.php index e2ce8f353..ee5bdde99 100644 --- a/app/Services/Extensions/ExtensionComposerInspector.php +++ b/app/Services/Extensions/ExtensionComposerInspector.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace Pterodactyl\Services\Extensions; +use Composer\Semver\Semver; +use Composer\Semver\VersionParser; use Illuminate\Support\Facades\File; /** @@ -13,6 +15,9 @@ use Illuminate\Support\Facades\File; */ final class ExtensionComposerInspector { + /** @var array|null version of each package the panel loads, by name */ + private ?array $panelPackages = null; + /** * The suffix of the autoloader class a package's vendor/autoload.php declares * (`ComposerAutoloaderInit`), or null when it has none. Composer derives the @@ -34,4 +39,141 @@ final class ExtensionComposerInspector { return class_exists('ComposerAutoloaderInit'.$suffix, false); } + + /** + * What Composer would object to in the dependencies a package bundles, none of which + * stops it from loading: development packages an install without --no-dev left in + * vendor/, composer.json requirements the panel's copy of a package does not satisfy, + * and bundled packages the panel loads at another version. A class the panel can load + * always comes from the panel, so the extension runs with the panel's copy of those. + * + * @return list + */ + public function warnings(ExtensionManifest $manifest): array + { + $warnings = []; + $installed = $this->installed($manifest->path('vendor', 'composer', 'installed.json')); + if ($installed['dev'] !== []) { + $warnings[] = sprintf('vendor/ includes development packages (%s). Run composer install --no-dev --optimize-autoloader before packing.', $this->summarize($installed['dev'])); + } + + $panel = $this->panelPackages(); + $unmet = []; + foreach ($this->requirements($manifest->path('composer.json')) as $package => $constraint) { + $version = $panel[$package] ?? null; + if ($version !== null && ! rescue(fn (): bool => Semver::satisfies($version, $constraint), false, false)) { + $unmet[$package] = sprintf('%s %s (the panel loads %s)', $package, $constraint, $version); + } + } + + if ($unmet !== []) { + $warnings[] = sprintf("composer.json requires packages the panel already loads at versions it does not have, and the panel's copies are used: %s.", implode(', ', $unmet)); + } + + $shadowed = []; + foreach ($installed['packages'] as $package => $version) { + if (isset($panel[$package]) && ! isset($unmet[$package]) && $this->normalize($panel[$package]) !== $this->normalize($version)) { + $shadowed[] = sprintf('%s (bundled %s, panel %s)', $package, $version, $panel[$package]); + } + } + + if ($shadowed !== []) { + $warnings[] = sprintf("vendor/ bundles other versions of packages the panel already loads, and the panel's copies are used: %s.", implode(', ', $shadowed)); + } + + return $warnings; + } + + /** + * The packages Composer installed into a vendor/ directory, by name, and the + * development packages among them when it installed those too. + * + * @return array{packages: array, dev: list} + */ + private function installed(string $path): array + { + $installed = is_file($path) ? json_decode(File::get($path), true) : null; + if (! is_array($installed)) { + return ['packages' => [], 'dev' => []]; + } + + // Composer 1 wrote the package list itself; Composer 2 nests it under "packages". + $list = array_is_list($installed) ? $installed : $installed['packages'] ?? []; + $packages = []; + foreach (is_array($list) ? $list : [] as $package) { + if (is_array($package) && is_string($package['name'] ?? null) && is_string($package['version'] ?? null)) { + $packages[$package['name']] = $package['version']; + } + } + + $dev = ($installed['dev'] ?? false) === true && is_array($installed['dev-package-names'] ?? null) ? $installed['dev-package-names'] : []; + + return ['packages' => $packages, 'dev' => array_values(array_filter($dev, is_string(...)))]; + } + + /** + * The package requirements of a composer.json, leaving out PHP, its extensions and + * Composer itself. + * + * @return array + */ + private function requirements(string $path): array + { + $composer = is_file($path) ? json_decode(File::get($path), true) : null; + $require = is_array($composer) ? $composer['require'] ?? [] : []; + + $requirements = []; + foreach (is_array($require) ? $require : [] as $package => $constraint) { + if (is_string($package) && is_string($constraint) && str_contains($package, '/')) { + $requirements[$package] = $constraint; + } + } + + return $requirements; + } + + /** + * The version of every package the panel loads in production: the ones it installed and + * the ones those replace, such as the illuminate/* components of laravel/framework. + * + * @return array + */ + private function panelPackages(): array + { + if ($this->panelPackages !== null) { + return $this->panelPackages; + } + + $path = base_path('vendor/composer/installed.php'); + $installed = is_file($path) ? File::getRequire($path) : null; + $versions = is_array($installed) ? $installed['versions'] ?? [] : []; + + $packages = []; + foreach (is_array($versions) ? $versions : [] as $name => $package) { + if (! is_string($name) || ! is_array($package) || ($package['dev_requirement'] ?? false) === true) { + continue; + } + + $replaced = is_array($package['replaced'] ?? null) ? reset($package['replaced']) : null; + $version = $package['pretty_version'] ?? $replaced; + if (is_string($version)) { + $packages[$name] = $version; + } + } + + return $this->panelPackages = $packages; + } + + private function normalize(string $version): string + { + return rescue(fn (): string => (new VersionParser)->normalize($version), $version, false); + } + + /** @param list $names */ + private function summarize(array $names): string + { + $shown = implode(', ', array_slice($names, 0, 3)); + + return count($names) > 3 ? sprintf('%s and %d more', $shown, count($names) - 3) : $shown; + } } diff --git a/app/Services/Extensions/ExtensionManifestValidator.php b/app/Services/Extensions/ExtensionManifestValidator.php index 3e6d2bd0c..e356e3a19 100644 --- a/app/Services/Extensions/ExtensionManifestValidator.php +++ b/app/Services/Extensions/ExtensionManifestValidator.php @@ -12,6 +12,7 @@ use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; use JsonException; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; +use Pterodactyl\Support\JsonValueGuard; use ReflectionClass; use UnexpectedValueException; @@ -71,7 +72,9 @@ class ExtensionManifestValidator throw_if(in_array($id, ExtensionManifest::RESERVED_IDS, true), InvalidExtensionException::class, "Extension id \"{$id}\" is reserved."); - $autoload = $this->normalizeAutoload($data['autoload'] ?? []); + $autoload = isset($data['autoload']) + ? $this->normalizeAutoload($data['autoload'], 'Manifest "autoload"') + : $this->normalizeAutoload($this->composerAutoload($directory), 'composer.json "autoload.psr-4"'); [$uiEntry, $uiMode] = $this->normalizeUi($data['ui'] ?? null); $provider = $data['provider'] ?? null; @@ -228,19 +231,49 @@ class ExtensionManifestValidator } /** - * @param array $autoload + * The PSR-4 map of the package's composer.json, which Composer and editors read. It is + * used when extension.json declares no `autoload` of its own. + * + * @return array + */ + private function composerAutoload(string $directory): array + { + $path = mb_rtrim($directory, '/\\').DIRECTORY_SEPARATOR.'composer.json'; + if (! is_file($path)) { + return []; + } + + try { + $composer = JsonValueGuard::decodeArray8(File::get($path)); + } catch (JsonException|UnexpectedValueException) { + throw new InvalidExtensionException("{$path} is not valid JSON."); + } + + $psr4 = is_array($composer['autoload'] ?? null) ? $composer['autoload']['psr-4'] ?? [] : []; + throw_unless(is_array($psr4), InvalidExtensionException::class, 'composer.json "autoload.psr-4" must map "Vendor\\\\Prefix\\\\" to a source directory.'); + + return $psr4; + } + + /** + * @param array $autoload * @return array */ - private function normalizeAutoload(mixed $autoload): array + private function normalizeAutoload(array $autoload, string $field): array { $normalized = []; foreach ($autoload as $prefix => $src) { - throw_if(! is_string($prefix) || ! is_string($src) || preg_match(ExtensionManifest::NAMESPACE_REGEX, $prefix) !== 1, InvalidExtensionException::class, 'Manifest "autoload" must map "Vendor\\\\Prefix\\\\" to a source directory.'); + // Composer also maps a prefix to a list of directories; a list of one is the same map. + if (is_array($src) && count($src) === 1 && array_is_list($src)) { + $src = $src[0]; + } + + throw_if(! is_string($prefix) || ! is_string($src) || preg_match(ExtensionManifest::NAMESPACE_REGEX, $prefix) !== 1, InvalidExtensionException::class, $field.' must map "Vendor\\\\Prefix\\\\" to a source directory.'); $reserved = array_find($this->panelNamespaces(), fn (string $namespace): bool => ExtensionManifest::namespacesOverlap($prefix, $namespace)); - throw_if($reserved !== null, InvalidExtensionException::class, "Manifest \"autoload\" namespace \"{$prefix}\" overlaps \"{$reserved}\", which the panel already autoloads."); + throw_if($reserved !== null, InvalidExtensionException::class, "{$field} namespace \"{$prefix}\" overlaps \"{$reserved}\", which the panel already autoloads."); - throw_if(str_starts_with($src, '/') || str_contains($src, '..'), InvalidExtensionException::class, 'Manifest "autoload" directories must be relative paths inside the package.'); + throw_if(str_starts_with($src, '/') || str_contains($src, '..'), InvalidExtensionException::class, $field.' directories must be relative paths inside the package.'); $normalized[$prefix] = mb_trim(str_replace('\\', '/', $src), '/'); } diff --git a/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php b/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php index 77f89b187..b04276e50 100644 --- a/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php +++ b/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php @@ -67,6 +67,7 @@ class ExtensionScaffolder ]; $this->writeManifest($target, $id, $namespace, $replacements, $ui); + $this->writeComposerJson($target, $namespace, $replacements); $this->stub($target, 'provider.stub', 'src/'.$namespace.'Provider.php', $replacements); $this->stub($target, 'controller.stub', 'src/Http/Controllers/StatusController.php', $replacements); @@ -121,7 +122,6 @@ class ExtensionScaffolder 'description' => $replacements['{{description}}'] ?: null, 'author' => $replacements['{{author}}'] ?: null, 'provider' => $namespace.'\\'.$namespace.'Provider', - 'autoload' => [$namespace.'\\' => 'src'], 'ui' => $ui ? ['entry' => ExtensionManifest::UI_ENTRY, 'mode' => 'native', 'prefix' => $replacements['{{prefix}}'], 'screens' => [['id' => 'main', 'area' => 'server', 'path' => $id, 'nav' => ['label' => $replacements['{{name}}']]]]] : null, ], fn (array|string|null $value): bool => $value !== null); @@ -132,6 +132,25 @@ class ExtensionScaffolder $this->files[] = ExtensionManifest::FILENAME; } + /** + * The PSR-4 map lives in composer.json, where Composer, editors and static analysis read + * it, and the panel reads it from there too. The autoloader suffix keeps the class a + * bundled vendor/autoload.php declares apart from every other package's. + * + * @param array $replacements stub placeholder => literal substitution + */ + private function writeComposerJson(string $target, string $namespace, array $replacements): void + { + $composer = array_filter([ + 'description' => $replacements['{{description}}'] ?: null, + 'autoload' => ['psr-4' => [$namespace.'\\' => 'src/']], + 'config' => ['autoloader-suffix' => $namespace.'Extension'], + ], fn (array|string|null $value): bool => $value !== null); + + File::put($target.DIRECTORY_SEPARATOR.'composer.json', json_encode($composer, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n"); + $this->files[] = 'composer.json'; + } + /** * @param array $replacements stub placeholder => literal substitution */ diff --git a/app/Services/Extensions/Scaffolding/stubs/gitignore.stub b/app/Services/Extensions/Scaffolding/stubs/gitignore.stub index 3d2bc6269..5d21401c5 100644 --- a/app/Services/Extensions/Scaffolding/stubs/gitignore.stub +++ b/app/Services/Extensions/Scaffolding/stubs/gitignore.stub @@ -1,2 +1,3 @@ /dist/ /node_modules/ +/vendor/ diff --git a/app/Services/Extensions/Scaffolding/stubs/readme.stub b/app/Services/Extensions/Scaffolding/stubs/readme.stub index e3762f505..ce613762f 100644 --- a/app/Services/Extensions/Scaffolding/stubs/readme.stub +++ b/app/Services/Extensions/Scaffolding/stubs/readme.stub @@ -4,12 +4,14 @@ A Pterodactyl panel extension, scaffolded by `p:extension:make`. ## Layout -- `extension.json` — the manifest; `provider` is the boot entry point. -- `src/` — PSR-4 PHP (`{{namespace}}\`), booted through `src/{{provider}}.php`. +- `extension.json`: the manifest; `provider` is the boot entry point. +- `src/`: PSR-4 PHP (`{{namespace}}\`), booted through `src/{{provider}}.php`. Runs fully trusted, in-process, with the same middleware stacks core uses. -- `routes/client.php` — mounted at `/api/client/extensions/{{id}}`. Add +- `composer.json`: the PSR-4 map the panel and your editor read. Composer + dependencies go here too; the panel loads `vendor/autoload.php` when it exists. +- `routes/client.php`: mounted at `/api/client/extensions/{{id}}`. Add `routes/admin.php` / `routes/application.php` for the other API surfaces. -- `database/migrations/` — extension-owned migrations. Prefix tables with +- `database/migrations/`: extension-owned migrations. Prefix tables with `ext_{{id}}_` by convention. {{frontend}}## Install @@ -18,5 +20,10 @@ A Pterodactyl panel extension, scaffolded by `p:extension:make`. php artisan p:extension:install /path/to/{{id}} --enable ``` -Package for distribution by zipping the directory as `{{id}}.pteroext` -(exclude `node_modules/`; include `dist/`). +Package for distribution with `p:extension:pack`, after building `dist/` and, if +the extension has Composer dependencies, running +`composer install --no-dev --optimize-autoloader`: + +```sh +php artisan p:extension:pack /path/to/{{id}} +``` diff --git a/packages/sdk/README.md b/packages/sdk/README.md index 6ce025517..1c8227c04 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -322,8 +322,10 @@ not a durable job audit log. ## Backend provider API -The manifest's `provider` class is loaded through its `autoload` map of PSR-4 prefixes to -package directories, such as `{ "Acme\\Billing\\": "src" }`. A prefix cannot equal, contain +The manifest's `provider` class is loaded through a map of PSR-4 prefixes to package +directories, such as `{ "Acme\\Billing\\": "src" }`. Scaffolds keep it in `composer.json` +under `autoload.psr-4`, where Composer, editors and static analysis read it too; an +`autoload` map in `extension.json` takes its place when present. A prefix cannot equal, contain or sit inside `Pterodactyl\`, `Illuminate\`, `Laravel\`, `Symfony\` or a namespace of the panel's Composer packages, and enabling fails while another enabled extension autoloads an overlapping prefix. Extension class loaders are registered behind the panel's, so once an @@ -340,6 +342,13 @@ uses. Give each extension a suffix of its own in its `composer.json`: { "config": { "autoloader-suffix": "AcmeBillingExtension" } } ``` +Build `vendor/` with `composer install --no-dev --optimize-autoloader` before packing. +`p:extension:doctor` and `p:extension:pack` read `vendor/composer/installed.json` and warn +about development packages left in `vendor/`, about `composer.json` requirements the +panel's copy of a package does not satisfy, and about bundled packages the panel loads at +another version. None of these stop the extension from loading, but its code runs with the +panel's copy of any package both ship. + Providers can use `listenToServerOperations` for immutable `provision`, `install`, `reinstall`, `backup`, `delete`, `suspend`, `unsuspend`, and `transfer` results. Results dispatch after commit and carry identifiers only (`serverUuid`, `operation`, `successful`, diff --git a/packages/sdk/manifest.schema.json b/packages/sdk/manifest.schema.json index 965e05877..42f880cd2 100644 --- a/packages/sdk/manifest.schema.json +++ b/packages/sdk/manifest.schema.json @@ -68,7 +68,7 @@ }, "autoload": { "type": "object", - "description": "PSR-4 namespace prefixes mapped to source directories inside the package. A prefix cannot equal, contain or sit inside Pterodactyl\\, Illuminate\\, Laravel\\, Symfony\\ or a namespace of the panel's Composer packages, and enabling fails while another enabled extension autoloads an overlapping one.", + "description": "PSR-4 namespace prefixes mapped to source directories inside the package. Without it, the panel reads autoload.psr-4 from the package's composer.json. A prefix cannot equal, contain or sit inside Pterodactyl\\, Illuminate\\, Laravel\\, Symfony\\ or a namespace of the panel's Composer packages, and enabling fails while another enabled extension autoloads an overlapping one.", "propertyNames": { "pattern": "^(?:[A-Za-z_\\u0080-\\uffff][A-Za-z0-9_\\u0080-\\uffff]*\\\\)+$" }, diff --git a/tests/Unit/Services/Extensions/ExtensionManifestTest.php b/tests/Unit/Services/Extensions/ExtensionManifestTest.php index 182fb1458..1ea498b85 100644 --- a/tests/Unit/Services/Extensions/ExtensionManifestTest.php +++ b/tests/Unit/Services/Extensions/ExtensionManifestTest.php @@ -104,6 +104,31 @@ test('accepts autoload namespaces that only share a name start with the panel', expect((new ExtensionManifestValidator)->fromDirectory($this->directory)->autoload)->toBe(['PterodactylBilling\\' => 'src', 'Acme\\Pterodactyl\\' => 'lib']); }); +test('reads the PSR-4 map from composer.json when the manifest declares no autoload', function (): void { + writeManifest(['id' => 'valid-id', 'name' => 'Valid', 'version' => '1.0.0']); + File::put($this->directory.'/composer.json', json_encode(['autoload' => ['psr-4' => ['Acme\\Billing\\' => 'src/', 'Acme\\Invoices\\' => ['lib/']]]], JSON_THROW_ON_ERROR)); + + expect((new ExtensionManifestValidator)->fromDirectory($this->directory)->autoload)->toBe(['Acme\\Billing\\' => 'src', 'Acme\\Invoices\\' => 'lib']); + + // A manifest map of its own takes the place of composer.json's, as it always has. + writeManifest(['id' => 'valid-id', 'name' => 'Valid', 'version' => '1.0.0', 'autoload' => ['Acme\\Status\\' => 'status']]); + expect((new ExtensionManifestValidator)->fromDirectory($this->directory)->autoload)->toBe(['Acme\\Status\\' => 'status']); +}); + +test('holds the composer.json PSR-4 map to the manifest rules', function (string $psr4, string $message): void { + writeManifest(['id' => 'valid-id', 'name' => 'Valid', 'version' => '1.0.0']); + File::put($this->directory.'/composer.json', $psr4); + + expect(fn (): ExtensionManifest => (new ExtensionManifestValidator)->fromDirectory($this->directory))->toThrow(InvalidExtensionException::class, $message); +})->with([ + 'the panel namespace' => ['{"autoload": {"psr-4": {"Pterodactyl\\\\Billing\\\\": "src/"}}}', 'composer.json "autoload.psr-4" namespace "Pterodactyl\\Billing\\" overlaps "Pterodactyl\\"'], + 'a fallback directory' => ['{"autoload": {"psr-4": {"": "src/"}}}', 'composer.json "autoload.psr-4" must map'], + 'several directories' => ['{"autoload": {"psr-4": {"Acme\\\\": ["src/", "lib/"]}}}', 'composer.json "autoload.psr-4" must map'], + 'a directory outside the package' => ['{"autoload": {"psr-4": {"Acme\\\\": "../src/"}}}', 'composer.json "autoload.psr-4" directories must be relative paths'], + 'not a map' => ['{"autoload": {"psr-4": "src/"}}', 'composer.json "autoload.psr-4" must map'], + 'invalid JSON' => ['{"autoload":', 'composer.json is not valid JSON'], +]); + test('missing and malformed files', function (string $subdirectory, ?string $contents): void { $directory = $this->directory.DIRECTORY_SEPARATOR.$subdirectory; if ($contents !== null) { diff --git a/tests/Unit/Services/Extensions/ExtensionScaffolderTest.php b/tests/Unit/Services/Extensions/ExtensionScaffolderTest.php index 10aa09d66..81c9b0b8b 100644 --- a/tests/Unit/Services/Extensions/ExtensionScaffolderTest.php +++ b/tests/Unit/Services/Extensions/ExtensionScaffolderTest.php @@ -29,6 +29,14 @@ test('scaffolds an installable package', function (): void { expect($manifest->author)->toBe('Tester'); expect($manifest->provider)->toBe('MyWidget\MyWidgetProvider'); expect($manifest->autoload)->toBe(['MyWidget\\' => 'src']); + // The PSR-4 map lives where Composer and editors read it, with an autoloader of its own. + expect(File::json($target.'/extension.json'))->not->toHaveKey('autoload'); + expect(File::json($target.'/composer.json'))->toBe([ + 'description' => 'A test widget.', + 'autoload' => ['psr-4' => ['MyWidget\\' => 'src/']], + 'config' => ['autoloader-suffix' => 'MyWidgetExtension'], + ]); + expect(File::get($target.'/.gitignore'))->toContain('/vendor/'); expect($manifest->hasUi())->toBeTrue(); expect($manifest->screens)->toBe([['id' => 'main', 'area' => 'server', 'path' => 'my-widget', 'nav' => ['label' => 'My Widget']]]); diff --git a/tests/Unit/Services/Extensions/ExtensionToolingTest.php b/tests/Unit/Services/Extensions/ExtensionToolingTest.php index 08438ff7d..90f01da04 100644 --- a/tests/Unit/Services/Extensions/ExtensionToolingTest.php +++ b/tests/Unit/Services/Extensions/ExtensionToolingTest.php @@ -138,6 +138,49 @@ test('doctor accepts a readable image icon', function (): void { ->assertSuccessful(); }); +test('doctor and pack warn about the Composer packages an extension bundles without failing it', function (): void { + $guzzle = (require base_path('vendor/composer/installed.php'))['versions']['guzzlehttp/guzzle']['pretty_version']; + File::put($this->directory.'/composer.json', json_encode(['require' => ['php' => '^8.3', 'laravel/framework' => '^99.0', 'acme/ledger' => '^1.0']], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)); + File::ensureDirectoryExists($this->directory.'/vendor/composer'); + File::put($this->directory.'/vendor/composer/installed.json', json_encode([ + 'packages' => [ + ['name' => 'acme/ledger', 'version' => '1.4.0'], + ['name' => 'guzzlehttp/guzzle', 'version' => '1.0.0'], + ['name' => 'phpunit/phpunit', 'version' => '12.0.0'], + ], + 'dev' => true, + 'dev-package-names' => ['phpunit/phpunit'], + ], JSON_THROW_ON_ERROR)); + + $this->artisan('p:extension:doctor', ['path' => $this->directory]) + ->expectsOutputToContain('vendor/ includes development packages (phpunit/phpunit)') + ->expectsOutputToContain('laravel/framework ^99.0 (the panel loads') + ->expectsOutputToContain("guzzlehttp/guzzle (bundled 1.0.0, panel {$guzzle})") + ->doesntExpectOutputToContain('acme/ledger') + ->assertSuccessful(); + + $archive = $this->directory.'/probe.pteroext'; + $this->artisan('p:extension:pack', ['path' => $this->directory, '--output' => $archive]) + ->expectsOutputToContain('vendor/ includes development packages (phpunit/phpunit)') + ->assertSuccessful(); + $zip = new ZipArchive; + expect($zip->open($archive))->toBeTrue(); + try { + expect($zip->getFromName('composer.json'))->toContain('acme/ledger'); + expect($zip->locateName('vendor/composer/installed.json'))->not->toBeFalse(); + } finally { + $zip->close(); + } + + // A production install of packages the panel does not ship has nothing to report. + File::put($this->directory.'/composer.json', json_encode(['require' => ['acme/ledger' => '^1.0']], JSON_THROW_ON_ERROR)); + File::put($this->directory.'/vendor/composer/installed.json', json_encode(['packages' => [['name' => 'acme/ledger', 'version' => '1.4.0']], 'dev' => false, 'dev-package-names' => []], JSON_THROW_ON_ERROR)); + $this->artisan('p:extension:doctor', ['path' => $this->directory]) + ->doesntExpectOutputToContain('vendor/') + ->doesntExpectOutputToContain('composer.json') + ->assertSuccessful(); +}); + function toolingPng(): string { return (string) base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', true); diff --git a/tools/phpstan/rules/extension.neon b/tools/phpstan/rules/extension.neon index fd1ac729f..69ee83db8 100644 --- a/tools/phpstan/rules/extension.neon +++ b/tools/phpstan/rules/extension.neon @@ -46,6 +46,7 @@ parameters: - app/Data/** - app/Extensions/Scribe/** - app/Services/Extensions/ExtensionManifestValidator.php + - app/Services/Extensions/ExtensionComposerInspector.php - app/Services/Extensions/ExtensionSettingValueGuard.php - app/Services/Extensions/ExtensionSettings.php - app/Services/Extensions/Scaffolding/ExtensionScaffolder.php