diff --git a/src/Console/Commands/InstallCommand.php b/src/Console/Commands/InstallCommand.php index 70a32eb..d834d76 100644 --- a/src/Console/Commands/InstallCommand.php +++ b/src/Console/Commands/InstallCommand.php @@ -29,6 +29,9 @@ class InstallCommand extends Command {--domain= : Hostname the app is served on (e.g. myapp.test) — prompted if omitted} {--app-name= : What the app is called (defaults to its directory name)} {--demo : Load demo content and demo users} + {--template= : A Saucebase template (vendor/name): installs it, the modules it requires, and its starting data} + {--make-template= : Build a template (vendor/name) in the new app, on the modules it installs} + {--state= : A template state to seed; --demo seeds its default} {--fresh : Run migrate:fresh instead of migrate (destructive)} {--all-modules : Enable and migrate all available modules without prompting} {--modules= : Comma-separated list of modules to enable (e.g. Auth,Settings), or "none"} @@ -250,7 +253,16 @@ public function coreInstallSteps(): array return []; } + // `saucebase-dev` (dev-tools) sets this to the local registry: core, modules and + // templates then come from there at their dev branches. Unset: the published ones. + $registry = getenv('SAUCEBASE_REGISTRY') ?: null; + return [ + ...($registry === null ? [] : [ + ['composer', 'config', 'repositories.saucebase', 'composer', $registry], + ['composer', 'config', 'minimum-stability', 'dev'], + ['composer', 'config', 'prefer-stable', 'true'], + ]), // Composer refuses an unlisted plugin outright when it cannot ask. ['composer', 'config', 'allow-plugins.saucebase/module-installer', 'true'], ['composer', 'require', 'saucebase/core', '--no-interaction'], @@ -290,7 +302,8 @@ public function runStack(): void public function promptForModules(): void { - if ($this->option('all-modules') || $this->option('modules') !== null || $this->option('dev') || $this->isCI()) { + // A template requires its own modules. + if ($this->option('template') || $this->option('all-modules') || $this->option('modules') !== null || $this->option('dev') || $this->isCI()) { return; } @@ -339,6 +352,10 @@ public function install(): int return self::FAILURE; } + if ($this->optionOrNull('make-template') && ! $this->makeTemplate()) { + return self::FAILURE; + } + $this->createStorageLink(); $this->clearCaches(); @@ -567,6 +584,11 @@ protected function setupDatabase(): bool /** False when a selected module could not be wired into the application. */ protected function setupModules(): bool { + // Its composer.json requires the modules; doInstallModules adds the template itself. + if ($this->option('template')) { + return $this->doInstallModules([]); + } + $opt = $this->option('modules'); if ($opt === 'none') { @@ -614,27 +636,88 @@ public function doInstallModules(array $selected, ?\Closure $run = null): bool { $run ??= fn (array $command, int $timeout): bool => $this->runArtisan(array_slice($command, 2), $timeout); - if ($this->option('demo')) { + $this->newLine(); + + // Core's template-install requires the template with its modules and copies its + // stubs over the app. Its demo is its default state, seeded only when asked for + // (--demo), like any demo; --state names another. + if ($template = $this->optionOrNull('template')) { + $state = $this->optionOrNull('state') ?: ($this->optionOrNull('demo') ? 'default' : null); + + // Only a seeded state creates accounts that need it. + if ($state !== null) { + $this->demoPassword(); + } + + $command = ['php', 'artisan', 'saucebase:template-install', $template, '--no-interaction', + ...($state !== null ? ['--state='.$state] : [])]; + + return $this->runInstallTask('Installing the template', $command, $run); + } + + $state = $this->option('demo') ? 'showcase' : null; + + if ($state !== null) { $this->demoPassword(); } - $this->newLine(); + return $this->runInstallTask('Installing modules', [ + 'php', + 'artisan', + 'saucebase:module-install', + ...array_map(fn (string $package) => Str::after($package, '/'), $selected), + '--no-interaction', + ...($state !== null ? ['--state='.$state] : []), + ], $run); + } + + /** + * The app builds a template: core's template recipe makes it in modules/, on the + * modules the app has, and Composer installs it there. + * + * @param (\Closure(string[] $command, int $timeout): bool)|null $run + */ + public function makeTemplate(?\Closure $run = null): bool + { + $package = (string) $this->optionOrNull('make-template'); + + if ($this->optionOrNull('template')) { + $this->components->warn('An app takes one template: use --template or --make-template, not both.'); + + return false; + } + + [$vendor, $name] = str_contains($package, '/') ? explode('/', $package, 2) : ['', '']; + // The name becomes the template's folder (kebab case) and its PHP namespace (Studly). + if (! preg_match('#^[a-z0-9_.-]+$#', $vendor) || ! preg_match('#^[a-z][a-z0-9]*(-[a-z0-9]+)*$#', $name) || Str::kebab(Str::studly($name)) !== $name) { + $this->components->warn('--make-template takes the template\'s package name, vendor/name in lowercase with dashes (acme/notes).'); + + return false; + } + $run ??= fn (array $command, int $timeout): bool => $this->runProcess($command, $timeout); + + // A resumed install: the recipe already made it, so only Composer runs again. + $existing = json_decode((string) @file_get_contents($this->path("modules/{$name}/composer.json")), true) ?? []; + $made = ($existing['name'] ?? null) === $package && ($existing['type'] ?? null) === 'saucebase-template'; + + return ($made || $this->runInstallTask('Creating the template', ['php', 'artisan', 'saucebase:recipe', Str::studly($name), 'template', '--vendor='.$vendor, '--no-interaction'], $run)) + && $this->runInstallTask('Installing the template', ['composer', 'update', $package, '--no-interaction'], $run); + } + + /** + * @param string[] $command + * @param \Closure(string[] $command, int $timeout): bool $run + */ + private function runInstallTask(string $label, array $command, \Closure $run): bool + { $ok = false; - $this->task('Installing modules', function () use ($selected, $run, &$ok) { - return $ok = $run([ - 'php', - 'artisan', - 'saucebase:module-install', - ...array_map(fn (string $package) => Str::after($package, '/'), $selected), - '--no-interaction', - ...($this->option('demo') ? ['--demo'] : []), - ], 900); + $this->task($label, function () use ($command, $run, &$ok) { + return $ok = $run($command, 900); }); if (! $ok) { - $this->components->warn('Installing modules failed. Run it again to see why: php artisan saucebase:module-install ' - .implode(' ', array_map(fn (string $package) => Str::after($package, '/'), $selected))); + $this->components->warn("{$label} failed. Run it again to see why: ".implode(' ', array_diff($command, ['--no-interaction']))); } return $ok; @@ -783,6 +866,18 @@ public function resumeCommand(array $resumeOptions = []): string $command .= ' --modules='.$modules; } + if ($template = $this->optionOrNull('template')) { + $command .= ' --template='.$template; + } + + if ($state = $this->optionOrNull('state')) { + $command .= ' --state='.$state; + } + + if ($make = $this->optionOrNull('make-template')) { + $command .= ' --make-template='.$make; + } + foreach (['all-modules', 'dev', 'fresh', 'force', 'demo'] as $flag) { if ($this->optionOrNull($flag)) { $command .= ' --'.$flag; diff --git a/src/Console/Commands/NewCommand.php b/src/Console/Commands/NewCommand.php index 452360c..846102c 100644 --- a/src/Console/Commands/NewCommand.php +++ b/src/Console/Commands/NewCommand.php @@ -31,7 +31,10 @@ class NewCommand extends Command {--ssl= : Enable HTTPS with mkcert for docker (yes/no) — prompted if omitted} {--domain= : Hostname the app is served on (e.g. myapp.test) — prompted if omitted} {--app-name= : What the app is called (defaults to its directory name), prompted if omitted} - {--using= : A Saucebase template to start from, instead of a plain Laravel application} + {--using= : A starter kit to start from, instead of a plain Laravel application} + {--template= : A Saucebase template (vendor/name): installs it, the modules it requires, and its starting data} + {--state= : A template state to seed; --demo seeds its default} + {--make-template= : Build a template (vendor/name) in the new app, on the modules it installs} {--dev : Dev environment} {--demo : Load demo content and demo users} {--fresh : Run migrate:fresh instead of migrate (destructive)} @@ -211,6 +214,11 @@ protected function resolveDomain(string $name, Environment $driver): string */ protected function resolveModulesUpfront(?string $stack): ?array { + // A template requires its own modules. + if ($this->option('template')) { + return []; + } + if ($stack === null || $this->option('all-modules') || $this->option('dev') || $this->option('modules') !== null) { return null; @@ -223,7 +231,8 @@ protected function resolveModulesUpfront(?string $stack): ?array } /** - * Demo content comes from the modules, so there is nothing to offer without them. + * Demo content comes from the modules or the template, so there is nothing to offer + * without them. * Declined by default: a real app would have to delete it, demo users included. * * @param string[]|null $modules Null when the install decides which modules come @@ -234,6 +243,15 @@ protected function wantsDemo(?array $modules): bool return true; } + // A template brings its own demo (its default state); --state already chose one. + if ($this->option('template')) { + return ! $this->option('state') && confirm( + label: 'Load the template\'s demo?', + default: false, + hint: 'Sample data and an account to sign in with', + ); + } + if ($modules === [] || $this->option('modules') === 'none') { return false; } @@ -330,6 +348,18 @@ protected function installArguments( $arguments['--demo'] = true; } + if ($template = $this->option('template')) { + $arguments['--template'] = $template; + } + + if ($state = $this->option('state')) { + $arguments['--state'] = $state; + } + + if ($make = $this->option('make-template')) { + $arguments['--make-template'] = $make; + } + foreach (['all-modules', 'dev', 'fresh', 'force'] as $flag) { if ($this->option($flag)) { $arguments['--'.$flag] = true; diff --git a/src/Environments/DockerEnvironment.php b/src/Environments/DockerEnvironment.php index a1c4496..974e204 100644 --- a/src/Environments/DockerEnvironment.php +++ b/src/Environments/DockerEnvironment.php @@ -799,11 +799,11 @@ protected function runStack(InstallCommand $command): void protected function installModules(InstallCommand $command): bool { $modules = $this->resolveModules($command); + $run = fn (array $args, int $timeout): bool => $this->execInContainer($command, $args, $timeout, quiet: true); - return $modules === [] || $command->doInstallModules( - $modules, - fn (array $args, int $timeout): bool => $this->execInContainer($command, $args, $timeout, quiet: true), - ); + $installed = ($modules === [] && ! $command->optionOrNull('template')) || $command->doInstallModules($modules, $run); + + return $installed && (! $command->optionOrNull('make-template') || $command->makeTemplate($run)); } protected function nextSteps(InstallCommand $command): array diff --git a/src/Environments/Environment.php b/src/Environments/Environment.php index 29f0556..d73afdb 100644 --- a/src/Environments/Environment.php +++ b/src/Environments/Environment.php @@ -3,6 +3,7 @@ namespace Saucebase\Installer\Environments; use Illuminate\Support\Facades\Process; +use Illuminate\Support\Str; use Saucebase\Installer\Console\Commands\InstallCommand; abstract class Environment @@ -133,15 +134,27 @@ private function normalizePath(string $path): string /** @return string[] The demo password, once, when demo content was loaded. */ protected function demoStep(InstallCommand $command): array { - $password = $command->optionOrNull('demo') ? $this->readEnvValue($command, 'DEMO_PASSWORD') : null; + $password = ($command->optionOrNull('demo') || $command->optionOrNull('template')) ? $this->readEnvValue($command, 'DEMO_PASSWORD') : null; if ($password === null) { return []; } - // Auth's demo data has the one account that sees everything. - return [is_dir($command->path('modules/auth')) - ? "Sign in as `chef@saucebase.dev` (admin) with the password `{$password}`. Every demo account uses it; it is saved in .env as DEMO_PASSWORD" + // A template's demo seeds its own accounts, and may name the one to sign in with + // (`extra.saucebase.demo_account`). Without a template, auth's demo admin sees everything. + $template = $command->optionOrNull('template'); + $account = match (true) { + $template !== null => json_decode((string) @file_get_contents($command->path('modules/'.Str::afterLast($template, '/').'/composer.json')), true)['extra']['saucebase']['demo_account'] ?? null, + $command->optionOrNull('demo') && is_dir($command->path('modules/auth')) => '`chef@saucebase.dev` (admin)', + default => null, + }; + + if (is_string($account) && $account !== '' && $template !== null) { + $account = "`{$account}`"; + } + + return [is_string($account) && $account !== '' + ? "Sign in as {$account} with the password `{$password}`. Every demo account uses it; it is saved in .env as DEMO_PASSWORD" : "Demo accounts use the password `{$password}`, saved in .env as DEMO_PASSWORD"]; } diff --git a/stubs/docker/docker/nginx-no-ssl.conf b/stubs/docker/docker/nginx-no-ssl.conf index 51d8cf3..c3d4f4f 100644 --- a/stubs/docker/docker/nginx-no-ssl.conf +++ b/stubs/docker/docker/nginx-no-ssl.conf @@ -6,6 +6,9 @@ server { charset utf-8; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + # Gzip compression gzip on; gzip_vary on; @@ -43,11 +46,15 @@ server { try_files $uri /index.php?$query_string; expires 1y; add_header Cache-Control "public, immutable"; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; } location ~* \.(js|css|ico|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; try_files $uri /index.php?$query_string; } @@ -82,5 +89,7 @@ server { access_log off; return 200 "healthy\n"; add_header Content-Type text/plain; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; } } diff --git a/stubs/docker/docker/nginx.conf b/stubs/docker/docker/nginx.conf index 68a352e..0ed28c1 100644 --- a/stubs/docker/docker/nginx.conf +++ b/stubs/docker/docker/nginx.conf @@ -15,6 +15,9 @@ server { charset utf-8; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + # SSL Configuration (mkcert certificates) ssl_certificate /etc/nginx/ssl/app.pem; ssl_certificate_key /etc/nginx/ssl/app.key.pem; @@ -61,12 +64,16 @@ server { try_files $uri /index.php?$query_string; expires 1y; add_header Cache-Control "public, immutable"; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; } # Handle static assets location ~* \.(js|css|ico|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; try_files $uri /index.php?$query_string; } @@ -108,5 +115,7 @@ server { access_log off; return 200 "healthy\n"; add_header Content-Type text/plain; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; } } diff --git a/tests/Feature/Environments/DockerEnvironmentTest.php b/tests/Feature/Environments/DockerEnvironmentTest.php index 78f0b8e..f6765b3 100644 --- a/tests/Feature/Environments/DockerEnvironmentTest.php +++ b/tests/Feature/Environments/DockerEnvironmentTest.php @@ -463,6 +463,42 @@ public function displaySuccess(array $steps = []): void {} $this->assertSame(Command::FAILURE, $result); } + /** Docker installs on its own path: --make-template runs there too, in the container. */ + public function test_make_template_runs_in_the_container(): void + { + $env = new class extends DockerEnvironment + { + /** @var list */ + public array $ran = []; + + public function exposedInstallModules(InstallCommand $command): bool + { + return $this->installModules($command); + } + + protected function execInContainer(InstallCommand $command, array $args, int $timeout = 120, bool $quiet = false): bool + { + $this->ran[] = implode(' ', $args); + + return true; + } + }; + + $command = new class(null, [], ['modules' => 'none', 'make-template' => 'acme/notes']) extends FakeInstallCommand + { + protected function task(string $label, callable $step): bool + { + return (bool) $step(); + } + }; + + $this->assertTrue($env->exposedInstallModules($command)); + $this->assertSame([ + 'php artisan saucebase:recipe Notes template --vendor=acme --no-interaction', + 'composer update acme/notes --no-interaction', + ], $env->ran); + } + public function test_boot_installs_saucebase_in_the_container_and_fails_when_it_cannot(): void { $env = new class extends DockerEnvironment diff --git a/tests/Feature/Environments/EnvironmentHelpersTest.php b/tests/Feature/Environments/EnvironmentHelpersTest.php index 8d127f1..df1b775 100644 --- a/tests/Feature/Environments/EnvironmentHelpersTest.php +++ b/tests/Feature/Environments/EnvironmentHelpersTest.php @@ -108,6 +108,40 @@ public function test_with_auth_it_names_the_admin_account_to_sign_in_with(): voi $this->assertSame(['Sign in as `chef@saucebase.dev` (admin) with the password `s3cret`. Every demo account uses it; it is saved in .env as DEMO_PASSWORD'], $steps); } + /** A template seeds its own accounts; auth's demo admin is only there with --demo. */ + public function test_a_template_without_demo_content_names_no_admin_account(): void + { + file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); + mkdir($this->tmp.'/modules/auth', recursive: true); + + $steps = $this->environment()->exposedDemoStep($this->command(template: 'saucebase/uptime')); + + $this->assertSame(['Demo accounts use the password `s3cret`, saved in .env as DEMO_PASSWORD'], $steps); + } + + /** A template's demo seeds its own accounts: auth's admin is not among them. */ + public function test_a_template_demo_names_the_templates_own_account(): void + { + file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); + mkdir($this->tmp.'/modules/auth', recursive: true); + mkdir($this->tmp.'/modules/uptime', recursive: true); + file_put_contents($this->tmp.'/modules/uptime/composer.json', json_encode(['extra' => ['saucebase' => ['demo_account' => 'uptime@saucebase.dev']]])); + + $steps = $this->environment()->exposedDemoStep($this->command(demo: true, template: 'saucebase/uptime')); + + $this->assertSame(['Sign in as `uptime@saucebase.dev` with the password `s3cret`. Every demo account uses it; it is saved in .env as DEMO_PASSWORD'], $steps); + } + + public function test_a_template_demo_without_a_named_account_gives_the_password_only(): void + { + file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); + mkdir($this->tmp.'/modules/auth', recursive: true); + + $steps = $this->environment()->exposedDemoStep($this->command(demo: true, template: 'saucebase/uptime')); + + $this->assertSame(['Demo accounts use the password `s3cret`, saved in .env as DEMO_PASSWORD'], $steps); + } + public function test_without_demo_content_no_password_is_shown(): void { file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); @@ -115,11 +149,11 @@ public function test_without_demo_content_no_password_is_shown(): void $this->assertSame([], $this->environment()->exposedDemoStep($this->command())); } - private function command(?string $modules = null, ?string $target = null, bool $demo = false): InstallCommand + private function command(?string $modules = null, ?string $target = null, bool $demo = false, ?string $template = null): InstallCommand { - return new class($target ?? $this->tmp, $modules, $demo) extends InstallCommand + return new class($target ?? $this->tmp, $modules, $demo, $template) extends InstallCommand { - public function __construct(private string $target, private ?string $modules, private bool $demo) + public function __construct(private string $target, private ?string $modules, private bool $demo, private ?string $template) { parent::__construct(); } @@ -134,6 +168,7 @@ public function option($key = null): string|array|bool|null return match ($key) { 'modules' => $this->modules, 'demo' => $this->demo ?: null, + 'template' => $this->template, default => null, }; } diff --git a/tests/Feature/InstallCommandCoreTest.php b/tests/Feature/InstallCommandCoreTest.php index b35ca57..60f3371 100644 --- a/tests/Feature/InstallCommandCoreTest.php +++ b/tests/Feature/InstallCommandCoreTest.php @@ -47,6 +47,33 @@ public function test_it_installs_core_into_a_plain_laravel_application(): void ], $command->ran); } + /** + * `saucebase-dev` sets SAUCEBASE_REGISTRY to the local registry: the app then takes + * core, its modules and templates from there, at their dev branches, before anything + * is required. Unset, the install is the published one. + */ + public function test_a_local_registry_is_added_before_core_is_required(): void + { + putenv('SAUCEBASE_REGISTRY=https://saucebase-packages.test/composer'); + + try { + $command = $this->command(); + + $this->assertTrue($command->installCore()); + $this->assertSame([ + 'composer config repositories.saucebase composer https://saucebase-packages.test/composer', + 'composer config minimum-stability dev', + 'composer config prefer-stable true', + 'composer config allow-plugins.saucebase/module-installer true', + 'composer require saucebase/core --no-interaction', + 'composer require --dev saucebase/laravel-playwright --no-interaction', + 'php artisan saucebase:install react --force --no-interaction', + ], $command->ran); + } finally { + putenv('SAUCEBASE_REGISTRY'); + } + } + public function test_it_names_the_project_after_its_directory(): void { $this->files->put($this->dir.'/composer.json', "{\n \"\$schema\": \"https://getcomposer.org/schema.json\",\n \"name\": \"laravel/laravel\",\n \"type\": \"project\"\n}\n"); diff --git a/tests/Feature/InstallCommandResumeTest.php b/tests/Feature/InstallCommandResumeTest.php index 12eb7bb..1f5d1f0 100644 --- a/tests/Feature/InstallCommandResumeTest.php +++ b/tests/Feature/InstallCommandResumeTest.php @@ -63,6 +63,13 @@ public function test_resume_command_carries_the_flags_through(): void $this->assertStringContainsString('--force', $resume); } + public function test_resume_command_keeps_the_template_and_its_state(): void + { + $resume = $this->command(['path' => '/tmp/app', 'template' => 'saucebase/uptime', 'state' => 'agency'])->resumeCommand(); + + $this->assertStringContainsString('--template=saucebase/uptime --state=agency', $resume); + } + public function test_resume_command_drops_the_cd_when_the_target_is_the_current_directory(): void { $resume = $this->command(['path' => getcwd()])->resumeCommand(['--driver' => 'native']); diff --git a/tests/Feature/InstallModulesRunnerTest.php b/tests/Feature/InstallModulesRunnerTest.php index 9ead205..52e86ec 100644 --- a/tests/Feature/InstallModulesRunnerTest.php +++ b/tests/Feature/InstallModulesRunnerTest.php @@ -44,6 +44,21 @@ public function warn(string $message): void {} return InstallCommand::doInstallModules($selected, $run); } + public function makeWith(\Closure $run): bool + { + $this->components = new class + { + public function task(string $label, callable $task): void + { + $task(); + } + + public function warn(string $message): void {} + }; + + return InstallCommand::makeTemplate($run); + } + public function newLine($count = 1): static { return $this; @@ -67,10 +82,178 @@ public function test_every_step_runs_through_the_given_runner(): void // Core's saucebase:module-install does the rest: require, patches, migrate, seed. $this->assertTrue($ok); - $this->assertSame(['php artisan saucebase:module-install blog roadmap --no-interaction --demo'], $ran); + $this->assertSame(['php artisan saucebase:module-install blog roadmap --no-interaction --state=showcase'], $ran); $this->assertStringContainsString('DEMO_PASSWORD=', (string) file_get_contents($this->tmp.'/.env')); } + /** Core's template-install requires the template with its modules and copies its stubs; no demo unless asked. */ + public function test_a_template_installs_clean_through_template_install(): void + { + $command = $this->command(); + $command->fakeOptions = ['path' => $this->tmp, 'template' => 'saucebase/uptime']; + + $ran = []; + $command->installWith([], function (array $args) use (&$ran): bool { + $ran[] = implode(' ', $args); + + return true; + }); + + $this->assertSame(['php artisan saucebase:template-install saucebase/uptime --no-interaction'], $ran); + // No accounts are seeded, so there is no password to set. + $this->assertStringNotContainsString('DEMO_PASSWORD=', (string) @file_get_contents($this->tmp.'/.env')); + } + + /** A template requires its own modules: nothing to look up or ask. */ + public function test_a_template_install_does_not_ask_for_modules(): void + { + $command = new class extends TestableInstallCommand + { + public bool $fetched = false; + + public function fetchAvailableModules(): array + { + $this->fetched = true; + + return []; + } + + protected function isCI(): bool + { + return false; + } + + // --modules not given is null, which fakeOptions can't hold. + public function option($key = null): string|array|bool|null + { + return $key === 'modules' ? null : parent::option($key); + } + }; + $command->fakeOptions = ['path' => $this->tmp, 'template' => 'saucebase/uptime']; + + $command->promptForModules(); + + $this->assertFalse($command->fetched); + } + + /** --demo is the template's demo: its default state, with the password its accounts use. */ + public function test_a_template_with_demo_seeds_its_default_state(): void + { + $command = $this->command(); + $command->fakeOptions = ['path' => $this->tmp, 'template' => 'saucebase/uptime', 'demo' => true]; + + $ran = []; + $command->installWith([], function (array $args) use (&$ran): bool { + $ran[] = implode(' ', $args); + + return true; + }); + + $this->assertSame(['php artisan saucebase:template-install saucebase/uptime --no-interaction --state=default'], $ran); + $this->assertStringContainsString('DEMO_PASSWORD=', (string) file_get_contents($this->tmp.'/.env')); + } + + public function test_a_template_state_is_passed_through(): void + { + $command = $this->command(); + $command->fakeOptions = ['path' => $this->tmp, 'template' => 'saucebase/uptime', 'state' => 'agency']; + + $ran = []; + $command->installWith([], function (array $args) use (&$ran): bool { + $ran[] = implode(' ', $args); + + return true; + }); + + $this->assertSame(['php artisan saucebase:template-install saucebase/uptime --no-interaction --state=agency'], $ran); + } + + /** The app builds a template: core's recipe makes it in modules/, Composer installs it. */ + public function test_make_template_creates_the_template_in_the_app(): void + { + $command = $this->command(); + $command->fakeOptions = ['path' => $this->tmp, 'make-template' => 'acme/notes']; + + $ran = []; + $ok = $command->makeWith(function (array $args) use (&$ran): bool { + $ran[] = implode(' ', $args); + + return true; + }); + + $this->assertTrue($ok); + $this->assertSame([ + 'php artisan saucebase:recipe Notes template --vendor=acme --no-interaction', + 'composer update acme/notes --no-interaction', + ], $ran); + } + + /** A resumed install: the template is already there, so only Composer runs again. */ + public function test_make_template_resumes_after_the_recipe_ran(): void + { + mkdir($this->tmp.'/modules/notes', 0777, true); + file_put_contents($this->tmp.'/modules/notes/composer.json', '{"name": "acme/notes", "type": "saucebase-template"}'); + $command = $this->command(); + $command->fakeOptions = ['path' => $this->tmp, 'make-template' => 'acme/notes']; + + $ran = []; + $this->assertTrue($command->makeWith(function (array $args) use (&$ran): bool { + $ran[] = implode(' ', $args); + + return true; + })); + $this->assertSame(['composer update acme/notes --no-interaction'], $ran); + } + + /** A module of that name is not a template made earlier: the recipe runs (and refuses the folder). */ + public function test_make_template_does_not_take_a_module_for_the_template(): void + { + mkdir($this->tmp.'/modules/auth', 0777, true); + file_put_contents($this->tmp.'/modules/auth/composer.json', '{"name": "saucebase/auth", "type": "saucebase-module"}'); + $command = $this->command(); + $command->fakeOptions = ['path' => $this->tmp, 'make-template' => 'saucebase/auth']; + + $ran = []; + $command->makeWith(function (array $args) use (&$ran): bool { + $ran[] = implode(' ', $args); + + return false; + }); + $this->assertSame(['php artisan saucebase:recipe Auth template --vendor=saucebase --no-interaction'], $ran); + } + + public function test_make_template_needs_a_vendor_and_name(): void + { + $command = $this->command(); + $command->fakeOptions = ['path' => $this->tmp, 'make-template' => 'notes']; + $this->assertFalse($command->makeWith(fn (array $args): bool => true)); + + // The name becomes a folder in kebab case and a PHP namespace: anything else is refused. + foreach (['acme/notes.v2', 'acme/123', 'acme/foo/bar', 'acme/Notes', 'acme/notes--x', 'acme/notes-2'] as $name) { + $command->fakeOptions = ['path' => $this->tmp, 'make-template' => $name]; + $this->assertFalse($command->makeWith(fn (array $args): bool => true), $name); + } + + $command->fakeOptions = ['path' => $this->tmp, 'make-template' => 'acme/my_notes']; + + $ran = []; + $this->assertFalse($command->makeWith(function (array $args) use (&$ran): bool { + $ran[] = $args; + + return true; + })); + $this->assertSame([], $ran); + } + + /** An app takes one template: installed from one, or building one. */ + public function test_make_template_refuses_alongside_a_template(): void + { + $command = $this->command(); + $command->fakeOptions = ['path' => $this->tmp, 'make-template' => 'acme/notes', 'template' => 'saucebase/uptime']; + + $this->assertFalse($command->makeWith(fn (array $args): bool => true)); + } + public function test_a_failed_module_install_fails_the_step(): void { $ok = $this->command()->installWith(['saucebase/blog'], fn (array $args): bool => false); diff --git a/tests/Feature/NewCommandTest.php b/tests/Feature/NewCommandTest.php index a722c38..d3c9794 100644 --- a/tests/Feature/NewCommandTest.php +++ b/tests/Feature/NewCommandTest.php @@ -114,6 +114,54 @@ public function test_demo_reaches_the_install(): void $this->assertTrue($command->exposedInstallArguments('acme', 'vue')['--demo']); } + /** The template brings its modules; its demo is offered like any demo, declined by default. */ + public function test_a_saucebase_template_reaches_the_install_without_asking_for_modules(): void + { + $command = $this->command(['template' => 'saucebase/uptime', 'force' => true]); + Prompt::fake([Key::ENTER]); + + $this->assertSame([], $command->exposedResolveModulesUpfront('vue')); + $this->assertFalse($command->exposedWantsDemo([])); + $this->assertSame('saucebase/uptime', $command->exposedInstallArguments('acme', 'vue')['--template']); + } + + public function test_a_template_demo_is_offered(): void + { + $command = $this->command(['template' => 'saucebase/uptime', 'force' => true]); + Prompt::fake(['y', Key::ENTER]); + + $this->assertTrue($command->exposedWantsDemo([])); + } + + /** --state already chose what to seed: nothing to ask. */ + public function test_a_template_state_skips_the_demo_question(): void + { + $command = $this->command(['template' => 'saucebase/uptime', 'state' => 'agency', 'force' => true]); + + $this->assertFalse($command->exposedWantsDemo([])); + } + + public function test_a_template_with_demo_passes_it_on(): void + { + $command = $this->command(['template' => 'saucebase/uptime', 'demo' => true, 'force' => true]); + + $this->assertTrue($command->exposedWantsDemo([])); + } + + public function test_a_template_state_reaches_the_install(): void + { + $command = $this->command(['template' => 'saucebase/uptime', 'state' => 'agency', 'force' => true]); + + $this->assertSame('agency', $command->exposedInstallArguments('acme', 'vue')['--state']); + } + + public function test_make_template_reaches_the_install(): void + { + $command = $this->command(['make-template' => 'acme/notes', 'force' => true]); + + $this->assertSame('acme/notes', $command->exposedInstallArguments('acme', 'vue')['--make-template']); + } + public function test_a_template_leaves_the_framework_and_modules_to_the_install(): void { $command = $this->command(['using' => 'vendor/template']); diff --git a/tests/Feature/PublishDockerCommandTest.php b/tests/Feature/PublishDockerCommandTest.php index 5051044..a598a89 100644 --- a/tests/Feature/PublishDockerCommandTest.php +++ b/tests/Feature/PublishDockerCommandTest.php @@ -89,6 +89,25 @@ public function test_a_script_the_application_serves_itself_reaches_it(): void } } + /** + * The headers Laravel's documented nginx config sends. A location with an add_header + * of its own drops the server's, so each such location repeats them. + */ + public function test_responses_carry_the_security_headers(): void + { + foreach (['nginx.conf', 'nginx-no-ssl.conf'] as $file) { + $config = (string) file_get_contents(dirname(__DIR__, 2).'/stubs/docker/docker/'.$file); + $server = (string) preg_replace('/location [^{]*\{[^}]*\}/', '', $config); + + preg_match_all('/location [^{]*\{[^}]*add_header[^}]*\}/', $config, $locations); + + foreach ([$server, ...$locations[0]] as $block) { + $this->assertStringContainsString('add_header X-Frame-Options "SAMEORIGIN" always;', $block, $file); + $this->assertStringContainsString('add_header X-Content-Type-Options "nosniff" always;', $block, $file); + } + } + } + public function test_it_keeps_existing_files_when_not_forced(): void { file_put_contents($this->tmp.'/docker-compose.yml', 'mine');