diff --git a/.agents/skills/configuring-horizon/SKILL.md b/.agents/skills/configuring-horizon/SKILL.md
new file mode 100644
index 000000000..bed1e74c0
--- /dev/null
+++ b/.agents/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/.agents/skills/configuring-horizon/references/metrics.md b/.agents/skills/configuring-horizon/references/metrics.md
new file mode 100644
index 000000000..312f79ee7
--- /dev/null
+++ b/.agents/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/.agents/skills/configuring-horizon/references/notifications.md b/.agents/skills/configuring-horizon/references/notifications.md
new file mode 100644
index 000000000..943d1a26a
--- /dev/null
+++ b/.agents/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/.agents/skills/configuring-horizon/references/supervisors.md b/.agents/skills/configuring-horizon/references/supervisors.md
new file mode 100644
index 000000000..9da0c1769
--- /dev/null
+++ b/.agents/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/.agents/skills/configuring-horizon/references/tags.md b/.agents/skills/configuring-horizon/references/tags.md
new file mode 100644
index 000000000..263c955c1
--- /dev/null
+++ b/.agents/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/.agents/skills/developing-with-fortify/SKILL.md b/.agents/skills/fortify-development/SKILL.md
similarity index 72%
rename from .agents/skills/developing-with-fortify/SKILL.md
rename to .agents/skills/fortify-development/SKILL.md
index 2ff71a4b4..86322d9c0 100644
--- a/.agents/skills/developing-with-fortify/SKILL.md
+++ b/.agents/skills/fortify-development/SKILL.md
@@ -1,6 +1,9 @@
---
-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.
+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
@@ -39,7 +42,7 @@ ### Two-Factor Authentication Setup
```
- [ ] Add TwoFactorAuthenticatable trait to User model
- [ ] Enable feature in config/fortify.php
-- [ ] Run migrations for 2FA columns
+- [ ] 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
@@ -75,14 +78,26 @@ ### SPA Authentication Setup
```
- [ ] Set 'views' => false in config/fortify.php
-- [ ] Install and configure Laravel Sanctum
-- [ ] Use 'web' guard in fortify config
+- [ ] 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
diff --git a/.agents/skills/laravel-actions/SKILL.md b/.agents/skills/laravel-actions/SKILL.md
new file mode 100644
index 000000000..862dd55b5
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-actions/references/command.md b/.agents/skills/laravel-actions/references/command.md
new file mode 100644
index 000000000..a7b255daf
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-actions/references/controller.md b/.agents/skills/laravel-actions/references/controller.md
new file mode 100644
index 000000000..d48c34df8
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-actions/references/job.md b/.agents/skills/laravel-actions/references/job.md
new file mode 100644
index 000000000..b4c7cbea0
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-actions/references/listener.md b/.agents/skills/laravel-actions/references/listener.md
new file mode 100644
index 000000000..c5233001d
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-actions/references/object.md b/.agents/skills/laravel-actions/references/object.md
new file mode 100644
index 000000000..6a90be4d5
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-actions/references/testing-fakes.md b/.agents/skills/laravel-actions/references/testing-fakes.md
new file mode 100644
index 000000000..97766e6ce
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-actions/references/troubleshooting.md b/.agents/skills/laravel-actions/references/troubleshooting.md
new file mode 100644
index 000000000..cf6a5800f
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-actions/references/with-attributes.md b/.agents/skills/laravel-actions/references/with-attributes.md
new file mode 100644
index 000000000..1b28cf2cb
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-best-practices/SKILL.md b/.agents/skills/laravel-best-practices/SKILL.md
new file mode 100644
index 000000000..99018f3ae
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-best-practices/rules/advanced-queries.md b/.agents/skills/laravel-best-practices/rules/advanced-queries.md
new file mode 100644
index 000000000..920714a14
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-best-practices/rules/architecture.md b/.agents/skills/laravel-best-practices/rules/architecture.md
new file mode 100644
index 000000000..165056422
--- /dev/null
+++ b/.agents/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/.agents/skills/laravel-best-practices/rules/blade-views.md b/.agents/skills/laravel-best-practices/rules/blade-views.md
new file mode 100644
index 000000000..c6f8aaf1e
--- /dev/null
+++ b/.agents/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/.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 000000000..db689bf77
Binary files /dev/null and b/.agents/skills/laravel-best-practices/rules/style.md differ
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/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/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/.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/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/developing-with-fortify/SKILL.md b/.claude/skills/fortify-development/SKILL.md
similarity index 72%
rename from .claude/skills/developing-with-fortify/SKILL.md
rename to .claude/skills/fortify-development/SKILL.md
index 2ff71a4b4..86322d9c0 100644
--- a/.claude/skills/developing-with-fortify/SKILL.md
+++ b/.claude/skills/fortify-development/SKILL.md
@@ -1,6 +1,9 @@
---
-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.
+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
@@ -39,7 +42,7 @@ ### Two-Factor Authentication Setup
```
- [ ] Add TwoFactorAuthenticatable trait to User model
- [ ] Enable feature in config/fortify.php
-- [ ] Run migrations for 2FA columns
+- [ ] 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
@@ -75,14 +78,26 @@ ### SPA Authentication Setup
```
- [ ] Set 'views' => false in config/fortify.php
-- [ ] Install and configure Laravel Sanctum
-- [ ] Use 'web' guard in fortify config
+- [ ] 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
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 000000000..db689bf77
Binary files /dev/null and b/.claude/skills/laravel-best-practices/rules/style.md differ
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/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/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/.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/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/developing-with-fortify/SKILL.md b/.cursor/skills/fortify-development/SKILL.md
similarity index 72%
rename from .cursor/skills/developing-with-fortify/SKILL.md
rename to .cursor/skills/fortify-development/SKILL.md
index 2ff71a4b4..86322d9c0 100644
--- a/.cursor/skills/developing-with-fortify/SKILL.md
+++ b/.cursor/skills/fortify-development/SKILL.md
@@ -1,6 +1,9 @@
---
-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.
+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
@@ -39,7 +42,7 @@ ### Two-Factor Authentication Setup
```
- [ ] Add TwoFactorAuthenticatable trait to User model
- [ ] Enable feature in config/fortify.php
-- [ ] Run migrations for 2FA columns
+- [ ] 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
@@ -75,14 +78,26 @@ ### SPA Authentication Setup
```
- [ ] Set 'views' => false in config/fortify.php
-- [ ] Install and configure Laravel Sanctum
-- [ ] Use 'web' guard in fortify config
+- [ ] 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
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 000000000..db689bf77
Binary files /dev/null and b/.cursor/skills/laravel-best-practices/rules/style.md differ
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/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/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
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
-
+```
## Common Pitfalls
diff --git a/AGENTS.md b/AGENTS.md
index 162c23842..3fff0074e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -9,14 +9,17 @@ ## Foundational Context
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
-- php - 8.4.1
+- php - 8.5
- laravel/fortify (FORTIFY) - v1
- laravel/framework (LARAVEL) - v12
- laravel/horizon (HORIZON) - v5
+- laravel/nightwatch (NIGHTWATCH) - v1
+- laravel/pail (PAIL) - v1
- laravel/prompts (PROMPTS) - v0
- laravel/sanctum (SANCTUM) - v4
- laravel/socialite (SOCIALITE) - v5
- livewire/livewire (LIVEWIRE) - v3
+- laravel/boost (BOOST) - v2
- laravel/dusk (DUSK) - v8
- laravel/mcp (MCP) - v0
- laravel/pint (PINT) - v1
@@ -32,11 +35,15 @@ ## Skills Activation
This project has domain-specific skills available. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
-- `livewire-development` — 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.
-- `pest-testing` — 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.
-- `tailwindcss-development` — 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.
-- `developing-with-fortify` — 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.
-- `debugging-output-and-previewing-html-using-ray` — Use when user says "send to Ray," "show in Ray," "debug in Ray," "log to Ray," "display in Ray," or wants to visualize data, debug output, or show diagrams in the Ray desktop application.
+- `laravel-best-practices` — 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.
+- `configuring-horizon` — 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.
+- `socialite-development` — 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.
+- `livewire-development` — 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.
+- `pest-testing` — 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.
+- `tailwindcss-development` — 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.
+- `fortify-development` — 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.
+- `laravel-actions` — 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.
+- `debugging-output-and-previewing-html-using-ray` — Use when user says "send to Ray," "show in Ray," "debug in Ray," "log to Ray," "display in Ray," or wants to visualize data, debug output, or show diagrams in the Ray desktop application.
## Conventions
@@ -69,76 +76,51 @@ ## Replies
# Laravel Boost
-- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.
+## Tools
+
+- Laravel Boost is an MCP server with tools designed specifically for this application. Prefer Boost tools over manual alternatives like shell commands or file reads.
+- Use `database-query` to run read-only queries against the database instead of writing raw SQL in tinker.
+- Use `database-schema` to inspect table structure before writing migrations or models.
+- Use `get-absolute-url` to resolve the correct scheme, domain, and port for project URLs. Always use this before sharing a URL with the user.
+- Use `browser-logs` to read browser logs, errors, and exceptions. Only recent logs are useful, ignore old entries.
+
+## Searching Documentation (IMPORTANT)
+
+- Always use `search-docs` before making code changes. Do not skip this step. It returns version-specific docs based on installed packages automatically.
+- Pass a `packages` array to scope results when you know which packages are relevant.
+- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first.
+- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`.
+
+### Search Syntax
+
+1. Use words for auto-stemmed AND logic: `rate limit` matches both "rate" AND "limit".
+2. Use `"quoted phrases"` for exact position matching: `"infinite scroll"` requires adjacent words in order.
+3. Combine words and phrases for mixed queries: `middleware "rate limit"`.
+4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`.
## Artisan
-- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters.
+- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters.
+- Inspect routes with `php artisan route:list`. Filter with: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`.
+- Read configuration values using dot notation: `php artisan config:show app.name`, `php artisan config:show database.default`. Or read config files directly from the `config/` directory.
+- To check environment variables, read the `.env` file directly.
-## URLs
+## Tinker
-- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port.
-
-## Tinker / Debugging
-
-- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.
-- Use the `database-query` tool when you only need to read from the database.
-
-## Reading Browser Logs With the `browser-logs` Tool
-
-- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.
-- Only recent browser logs will be useful - ignore old logs.
-
-## Searching Documentation (Critically Important)
-
-- Boost comes with a powerful `search-docs` tool you should use before trying other approaches when working with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
-- Search the documentation before making code changes to ensure we are taking the correct approach.
-- Use multiple, broad, simple, topic-based queries at once. For example: `['rate limiting', 'routing rate limiting', 'routing']`. The most relevant results will be returned first.
-- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.
-
-### Available Search Syntax
-
-1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'.
-2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit".
-3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order.
-4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit".
-5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms.
+- Execute PHP in app context for debugging and testing code. Do not create models without user approval, prefer tests with factories instead. Prefer existing Artisan commands over custom tinker code.
+- Always use single quotes to prevent shell expansion: `php artisan tinker --execute 'Your::code();'`
+ - Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'`
=== php rules ===
# PHP
- Always use curly braces for control structures, even for single-line bodies.
-
-## Constructors
-
-- Use PHP 8 constructor property promotion in `__construct()`.
- - public function __construct(public GitHub $github) { }
-- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private.
-
-## Type Declarations
-
-- Always use explicit return type declarations for methods and functions.
-- Use appropriate PHP type hints for method parameters.
-
-
-protected function isAccessible(User $user, ?string $path = null): bool
-{
- ...
-}
-
-
-## Enums
-
-- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
-
-## Comments
-
-- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless the logic is exceptionally complex.
-
-## PHPDoc Blocks
-
-- Add useful array shape type definitions when appropriate.
+- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private.
+- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool`
+- Use TitleCase for Enum keys: `FavoritePerson`, `BestLake`, `Monthly`.
+- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic.
+- Use array shape type definitions in PHPDoc blocks.
=== tests rules ===
@@ -151,47 +133,22 @@ # Test Enforcement
# Do Things the Laravel Way
-- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
+- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using `php artisan list` and check their parameters with `php artisan [command] --help`.
- If you're creating a generic PHP class, use `php artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
-## Database
-
-- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.
-- Use Eloquent models and relationships before suggesting raw database queries.
-- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.
-- Generate code that prevents N+1 query problems by using eager loading.
-- Use Laravel's query builder for very complex database operations.
-
### Model Creation
-- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `php artisan make:model`.
+- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `php artisan make:model --help` to check the available options.
-### APIs & Eloquent Resources
+## APIs & Eloquent Resources
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
-## Controllers & Validation
-
-- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.
-- Check sibling Form Requests to see if the application uses array or string based validation rules.
-
-## Authentication & Authorization
-
-- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
-
## URL Generation
- When generating links to other pages, prefer named routes and the `route()` function.
-## Queues
-
-- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.
-
-## Configuration
-
-- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.
-
## Testing
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
@@ -232,16 +189,15 @@ ### Models
# Livewire
-- Livewire allows you to build dynamic, reactive interfaces using only PHP — no JavaScript required.
-- Instead of writing frontend code in JavaScript frameworks, you use Alpine.js to build the UI when client-side interactions are required.
-- State lives on the server; the UI reflects it. Validate and authorize in actions (they're like HTTP requests).
-- IMPORTANT: Activate `livewire-development` every time you're working with Livewire-related tasks.
+- Livewire allow to build dynamic, reactive interfaces in PHP without writing JavaScript.
+- You can use Alpine.js for client-side interactions instead of JavaScript frameworks.
+- Keep state server-side so the UI reflects it. Validate and authorize in actions as you would in HTTP requests.
=== pint/core rules ===
# Laravel Pint Code Formatter
-- You must run `vendor/bin/pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
+- If you have modified any PHP files, you must run `vendor/bin/pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
- Do not run `vendor/bin/pint --test --format agent`, simply run `vendor/bin/pint --format agent` to fix any formatting issues.
=== pest/core rules ===
@@ -251,22 +207,5 @@ ## Pest
- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`.
- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`.
- Do NOT delete tests without approval.
-- CRITICAL: ALWAYS use `search-docs` tool for version-specific Pest documentation and updated code examples.
-- IMPORTANT: Activate `pest-testing` every time you're working with a Pest or testing-related task.
-=== tailwindcss/core rules ===
-
-# Tailwind CSS
-
-- Always use existing Tailwind conventions; check project patterns before adding new ones.
-- IMPORTANT: Always use `search-docs` tool for version-specific Tailwind CSS documentation and updated code examples. Never rely on training data.
-- IMPORTANT: Activate `tailwindcss-development` every time you're working with a Tailwind CSS or styling-related task.
-
-=== laravel/fortify rules ===
-
-# Laravel Fortify
-
-- Fortify is a headless authentication backend that provides authentication routes and controllers for Laravel applications.
-- IMPORTANT: Always use the `search-docs` tool for detailed Laravel Fortify patterns and documentation.
-- IMPORTANT: Activate `developing-with-fortify` skill when working with Fortify authentication features.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 87e8ae806..8cd7287f3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1190,7 +1190,118 @@ ### 🚀 Features
- *(service)* Update autobase to version 2.5 (#7923)
- *(service)* Add chibisafe template (#5808)
- *(ui)* Improve sidebar menu items styling (#7928)
-- *(service)* Improve open-archiver
+- *(template)* Add open archiver template (#6593)
+- *(service)* Add linkding template (#6651)
+- *(service)* Add glip template (#7937)
+- *(templates)* Add Sessy docker compose template (#7951)
+- *(api)* Add update urls support to services api
+- *(api)* Improve service urls update
+- *(api)* Add url update support to services api (#7929)
+- *(api)* Improve docker_compose_domains
+- *(api)* Add more allowed fields
+- *(notifications)* Add mattermost notifications (#7963)
+- *(templates)* Add ElectricSQL docker compose template
+- *(service)* Add back soketi-app-manager
+- *(service)* Upgrade checkmate to v3 (#7995)
+- *(service)* Update pterodactyl version (#7981)
+- *(service)* Add langflow template (#8006)
+- *(service)* Upgrade listmonk to v6
+- *(service)* Add alexandrie template (#8021)
+- *(service)* Upgrade formbricks to v4 (#8022)
+- *(service)* Add goatcounter template (#8029)
+- *(installer)* Add tencentos as a supported os
+- *(installer)* Update nightly install script
+- Update pr template to remove unnecessary quote blocks
+- *(service)* Add satisfactory game server (#8056)
+- *(service)* Disable mautic (#8088)
+- *(service)* Add bento-pdf (#8095)
+- *(ui)* Add official postgres 18 support
+- *(database)* Add official postgres 18 support
+- *(ui)* Use 2 column layout
+- *(database)* Add official postgres 18 and pgvector 18 support (#8143)
+- *(ui)* Improve global search with uuid and pr support (#7901)
+- *(openclaw)* Add Openclaw service with environment variables and health checks
+- *(service)* Disable maybe
+- *(service)* Disable maybe (#8167)
+- *(service)* Add sure
+- *(service)* Add sure (#8157)
+- *(docker)* Install PHP sockets extension in development environment
+- *(services)* Add Spacebot service with custom logo support (#8427)
+- Expose scheduled tasks to API
+- *(api)* Add OpenAPI for managing scheduled tasks for applications and services
+- *(api)* Add delete endpoints for scheduled tasks in applications and services
+- *(api)* Add update endpoints for scheduled tasks in applications and services
+- *(api)* Add scheduled tasks CRUD API with auth and validation (#8428)
+- *(monitoring)* Add scheduled job monitoring dashboard (#8433)
+- *(service)* Disable plane
+- *(service)* Disable plane (#8580)
+- *(service)* Disable pterodactyl panel and pterodactyl wings
+- *(service)* Disable pterodactyl panel and pterodactyl wings (#8512)
+- *(service)* Upgrade beszel and beszel-agent to v0.18
+- *(service)* Upgrade beszel and beszel-agent to v0.18 (#8513)
+- Add command healthcheck type
+- Require health check command for 'cmd' type with backend validation and frontend update
+- *(healthchecks)* Add command health checks with input validation
+- *(healthcheck)* Add command-based health check support (#8612)
+- *(jobs)* Optimize async job dispatches and enhance Stripe subscription sync
+- *(jobs)* Add queue delay resilience to scheduled job execution
+- *(scheduler)* Add pagination to skipped jobs and filter manager start events
+- Add comment field to environment variables
+- Limit comment field to 256 characters for environment variables
+- Enhance environment variable handling to support mixed formats and add comprehensive tests
+- Add comment field to shared environment variables
+- Show comment field for locked environment variables
+- Add function to extract inline comments from docker-compose YAML environment variables
+- Add magic variable detection and update UI behavior accordingly
+- Add comprehensive environment variable parsing with nested resolution and hardcoded variable detection
+- *(models)* Add is_required to EnvironmentVariable fillable array
+- Add comment field to environment variables (#7269)
+- *(service)* Pydio-cells.yml
+- Pydio cells svg
+- Pydio-cells.yml pin to stable version
+- *(service)* Add Pydio cells (#8323)
+- *(service)* Disable minio community edition
+- *(service)* Disable minio community edition (#8686)
+- *(subscription)* Add Stripe server limit quantity adjustment flow
+- *(subscription)* Add refunds and cancellation management (#8637)
+- Add configurable timeout for public database TCP proxy
+- Add configurable proxy timeout for public database TCP proxy (#8673)
+- *(jobs)* Implement encrypted queue jobs
+- *(proxy)* Add database-backed config storage with disk backups
+- *(proxy)* Add database-backed config storage with disk backups (#8905)
+- *(livewire)* Add selectedActions parameter and error handling to delete methods
+- *(gitlab)* Add GitLab source integration with SSH and HTTP basic auth
+- *(git-sources)* Add GitLab integration and URL encode credentials (#8910)
+- *(server)* Add server metadata collection and display
+- *(git-import)* Support custom ssh command for fetch, submodule, and lfs
+- *(ui)* Add log filter based on log level
+- *(ui)* Add log filter based on log level (#8784)
+- *(seeders)* Add GitHub deploy key example application
+- *(service)* Update n8n-with-postgres-and-worker to 2.10.4 (#8807)
+- *(service)* Add container label escape control to services API
+- *(server)* Allow force deletion of servers with resources
+- *(server)* Allow force deletion of servers with resources (#8962)
+- *(compose-preview)* Populate fqdn from docker_compose_domains
+- *(compose-preview)* Populate fqdn from docker_compose_domains (#8963)
+- *(server)* Auto-fetch server metadata after validation
+- *(server)* Auto-fetch server metadata after validation (#8964)
+- *(templates)* Add imgcompress service, for offline image processing (#8763)
+- *(service)* Add librespeed (#8626)
+- *(service)* Update databasus to v3.16.2 (#8586)
+- *(preview)* Add configurable PR suffix toggle for volumes
+- *(api)* Add storages endpoints for applications
+- *(api)* Expand update_storage to support name, mount_path, host_path, content fields
+- *(environment-variable)* Add placeholder hint for magic variables
+- *(subscription)* Display next billing date and billing interval
+- *(api)* Support comments in bulk environment variable endpoints
+- *(api)* Add database environment variable management endpoints
+- *(storage)* Add resources tab and improve S3 deletion handling
+- *(storage)* Group backups by database and filter by s3 status
+- *(storage)* Add storage management for backup schedules
+- *(jobs)* Add cache-based deduplication for delayed cron execution
+- *(storage)* Add storage endpoints and UUID support for databases and services
+- *(monitoring)* Add Laravel Nightwatch monitoring support
+- *(validation)* Make hostname validation case-insensitive and expand allowed characters
### 🐛 Bug Fixes
@@ -3773,6 +3884,7 @@ ### 🐛 Bug Fixes
- *(scheduling)* Change redis cleanup command frequency from hourly to weekly for better resource management
- *(versions)* Update coolify version numbers in versions.json and constants.php to 4.0.0-beta.420.5 and 4.0.0-beta.420.6
- *(database)* Ensure internal port defaults correctly for unsupported database types in StartDatabaseProxy
+- *(git)* Tracking issue due to case sensitivity
- *(versions)* Update coolify version numbers in versions.json and constants.php to 4.0.0-beta.420.6 and 4.0.0-beta.420.7
- *(scheduling)* Remove unnecessary padding from scheduled task form layout for improved UI consistency
- *(horizon)* Update queue configuration to use environment variable for dynamic queue management
@@ -3798,7 +3910,6 @@ ### 🐛 Bug Fixes
- *(application)* Add option to suppress toast notifications when loading compose file
- *(git)* Tracking issue due to case sensitivity
- *(git)* Tracking issue due to case sensitivity
-- *(git)* Tracking issue due to case sensitivity
- *(ui)* Delete button width on small screens (#6308)
- *(service)* Matrix entrypoint
- *(ui)* Add flex-wrap to prevent overflow on small screens (#6307)
@@ -4422,6 +4533,197 @@ ### 🐛 Bug Fixes
- *(api)* Deprecate applications compose endpoint
- *(api)* Applications post and patch endpoints
- *(api)* Applications create and patch endpoints (#7917)
+- *(service)* Sftpgo port
+- *(env)* Only cat .env file in dev
+- *(api)* Encoding checks (#7944)
+- *(env)* Only show nixpacks plan variables section in dev
+- Switch custom labels check to UTF-8
+- *(api)* One click service name and description cannot be set during creation
+- *(ui)* Improve volume mount warning for compose applications (#7947)
+- *(api)* Show an error if the same 2 urls are provided
+- *(preview)* Docker compose preview URLs (#7959)
+- *(api)* Check domain conflicts within the request
+- *(api)* Include docker_compose_domains in domain conflict check
+- *(api)* Is_static and docker network missing
+- *(api)* If domains field is empty clear the fqdn column
+- *(api)* Application endpoint issues part 2 (#7948)
+- Optimize queries and caching for projects and environments
+- *(perf)* Eliminate N+1 queries from InstanceSettings and Server lookups (#7966)
+- Update version numbers to 4.0.0-beta.462 and 4.0.0-beta.463
+- *(service)* Update seaweedfs logo (#7971)
+- *(service)* Soju svg
+- *(service)* Autobase database is not persisted correctly (#7978)
+- *(ui)* Make tooltips a bit wider
+- *(ui)* Modal issues
+- *(validation)* Add @, / and & support to names and descriptions
+- *(backup)* Postgres restore arithmetic syntax error (#7997)
+- *(service)* Users unable to create their first ente account without SMTP (#7986)
+- *(ui)* Horizontal overflow on application and service headings (#7970)
+- *(service)* Supabase studio settings redirect loop (#7828)
+- *(env)* Skip escaping for valid JSON in environment variables (#6160)
+- *(service)* Disable kong response buffering and increase timeouts (#7864)
+- *(service)* Rocketchat fails to start due to database version incompatibility (#7999)
+- *(service)* N8n v2 with worker timeout error
+- *(service)* Elasticsearch-with-kibana not generating account token
+- *(service)* Elasticsearch-with-kibana not generating account token (#8067)
+- *(service)* Kimai fails to start (#8027)
+- *(service)* Reactive-resume template (#8048)
+- *(api)* Infinite loop with github app with many repos (#8052)
+- *(env)* Skip escaping for valid JSON in environment variables (#8080)
+- *(docker)* Update PostgreSQL version to 16 in Dockerfile
+- *(validation)* Enforce url validation for instance domain (#8078)
+- *(service)* Bluesky pds invite code doesn't generate (#8081)
+- *(service)* Bugsink login fails due to cors (#8083)
+- *(service)* Strapi doesn't start (#8084)
+- *(service)* Activepieces postgres 18 volume mount (#8098)
+- *(service)* Forgejo login failure (#8145)
+- *(database)* Pgvector 18 version is not parsed properly
+- *(labels)* Make sure name is slugified
+- *(parser)* Replace dashes and dots in auto generated envs
+- Stop database proxy when is_public changes to false (#8138)
+- *(docs)* Update documentation link for Openclaw service
+- *(api-docs)* Use proper schema references for environment variable endpoints (#8239)
+- *(ui)* Fix datalist border color and add repository selection watcher (#8240)
+- *(server)* Improve IP uniqueness validation with team-specific error messages
+- *(jobs)* Initialize status variable in checkHetznerStatus (#8359)
+- *(jobs)* Handle queue timeouts gracefully in Horizon (#8360)
+- *(push-server-job)* Skip containers with empty service subId (#8361)
+- *(database)* Disable proxy on port allocation failure (#8362)
+- *(sentry)* Use withScope for SSH retry event tracking (#8363)
+- *(api)* Add a newline to openapi.json
+- *(server)* Improve IP uniqueness validation with team-specific error messages
+- *(service)* Glitchtip webdashboard doesn't load
+- *(service)* Glitchtip webdashboard doesn't load (#8249)
+- *(api)* Improve scheduled tasks API with auth, validation, and execution endpoints
+- *(api)* Improve scheduled tasks validation and delete logic
+- *(security)* Harden deployment paths and deploy abilities (#8549)
+- *(service)* Always enable force https labels
+- *(traefik)* Respect force https in service labels (#8550)
+- *(team)* Include webhook notifications in enabled check (#8557)
+- *(service)* Resolve team lookup via service relationship
+- *(service)* Resolve team lookup via service relationship (#8559)
+- *(database)* Chown redis/keydb configs when custom conf set (#8561)
+- *(version)* Update coolify version to 4.0.0-beta.464 and nightly version to 4.0.0-beta.465
+- *(applications)* Treat zero private_key_id as deploy key (#8563)
+- *(deploy)* Split BuildKit and secrets detection (#8565)
+- *(auth)* Prevent CSRF redirect loop during 2FA challenge (#8596)
+- *(input)* Prevent eye icon flash on password fields before Alpine.js loads (#8599)
+- *(api)* Correct permission requirements for POST endpoints (#8600)
+- *(health-checks)* Prevent command injection in health check commands (#8611)
+- *(auth)* Prevent cross-tenant IDOR in resource cloning (#8613)
+- *(docker)* Centralize command escaping in executeInDocker helper (#8615)
+- *(api)* Add team authorization to domains_by_server endpoint (#8616)
+- *(ca-cert)* Prevent command injection via base64 encoding (#8617)
+- *(scheduler)* Add self-healing for stale Redis locks and detection in UI (#8618)
+- *(health-checks)* Sanitize and validate CMD healthcheck commands
+- *(healthchecks)* Remove redundant newline sanitization from CMD healthcheck
+- *(soketi)* Make host binding configurable for IPv6 support (#8619)
+- *(ssh)* Automatically fix SSH directory permissions during upgrade (#8635)
+- *(jobs)* Prevent non-due jobs firing on restart and enrich skip logs with resource links
+- *(database)* Close confirmation modal after import/restore
+- Application rollback uses correct commit sha
+- *(rollback)* Escape commit SHA to prevent shell injection
+- Save comment field when creating application environment variables
+- Allow editing comments on locked environment variables
+- Add Update button for locked environment variable comments
+- Remove duplicate delete button from locked environment variable view
+- Position Update button next to comment field for locked variables
+- Preserve existing comments in bulk update and always show save notification
+- Update success message logic to only show when changes are made
+- *(bootstrap)* Add bounds check to extractBalancedBraceContent
+- Pydio-cells svg path typo
+- *(database)* Handle PDO constant name change for PGSQL_ATTR_DISABLE_PREPARES
+- *(proxy)* Handle IPv6 CIDR notation in Docker network gateways (#8703)
+- *(ssh)* Prevent RCE via SSH command injection (#8748)
+- *(service)* Cloudreve doesn't persist data across restarts
+- *(service)* Cloudreve doesn't persist data across restarts (#8740)
+- Join link should be set correctly in the env variables
+- *(service)* Ente photos join link doesn't work (#8727)
+- *(subscription)* Harden quantity updates and proxy trust behavior
+- *(auth)* Resolve 419 session errors with domain-based access and Cloudflare Tunnels (#8749)
+- *(server)* Handle limit edge case and IPv6 allowlist dedupe
+- *(server-limit)* Re-enable force-disabled servers at limit
+- *(ip-allowlist)* Add IPv6 CIDR support for API access restrictions (#8750)
+- *(proxy)* Remove ipv6 cidr network remediation
+- Address review feedback on proxy timeout
+- *(proxy)* Add validation and normalization for database proxy timeout
+- *(proxy)* Mounting error for nginx.conf in dev
+- Enable preview deployment page for deploy key applications
+- *(application-source)* Support localhost key with id=0
+- Enable preview deployment page for deploy key applications (#8579)
+- *(docker-compose)* Respect preserveRepository setting when executing start command (#8848)
+- *(proxy)* Mounting error for nginx.conf in dev (#8662)
+- *(database)* Close confirmation modal after database import/restore (#8697)
+- *(subscription)* Use optional chaining for preview object access
+- *(parser)* Use firstOrCreate instead of updateOrCreate for environment variables
+- *(env-parser)* Capture clean variable names without trailing braces in bash-style defaults (#8855)
+- *(terminal)* Resolve WebSocket connection and host authorization issues (#8862)
+- *(docker-cleanup)* Respect keep for rollback setting for Nixpacks build images (#8859)
+- *(push-server)* Track last_online_at and reset database restart state
+- *(docker)* Prevent false container exits on failed docker queries (#8860)
+- *(api)* Require write permission for validation endpoints
+- *(sentinel)* Add token validation to prevent command injection
+- *(log-drain)* Prevent command injection by base64-encoding environment variables
+- *(git-ref-validation)* Prevent command injection via git references
+- *(docker)* Add path validation to prevent command injection in file locations
+- Prevent command injection and fix developer view shared variables error (#8889)
+- Build-time environment variables break Next.js (#8890)
+- *(modal)* Make confirmation modal close after dispatching Livewire actions (#8892)
+- *(parser)* Preserve user-saved env vars on Docker Compose redeploy (#8894)
+- *(security)* Sanitize newlines in health check commands to prevent RCE (#8898)
+- Prevent scheduled task input fields from losing focus
+- Prevent scheduled task input fields from losing focus (#8654)
+- *(api)* Add docker_cleanup parameter to stop endpoints
+- *(api)* Add docker_cleanup parameter to stop endpoints (#8899)
+- *(deployment)* Filter null and empty environment variables from nixpacks plan
+- *(deployment)* Filter null and empty environment variables from nixpacks plan (#8902)
+- *(livewire)* Add error handling and selectedActions to delete methods (#8909)
+- *(parsers)* Use firstOrCreate instead of updateOrCreate for environment variables
+- *(parsers)* Use firstOrCreate instead of updateOrCreate for environment variables (#8915)
+- *(ssh)* Remove undefined trackSshRetryEvent() method call (#8927)
+- *(validation)* Support scoped packages in file path validation (#8928)
+- *(parsers)* Resolve shared variables in compose environment
+- *(parsers)* Resolve shared variables in compose environment (#8930)
+- *(api)* Cast teamId to int in deployment authorization check
+- *(api)* Cast teamId to int in deployment authorization check (#8931)
+- *(git-import)* Ensure ssh key is used for fetch, submodule, and lfs operations (#8933)
+- *(ui)* Info logs were not highlighted with blue color
+- *(application)* Clarify deployment type precedence logic
+- *(git-import)* Explicitly specify ssh key and remove duplicate validation rules
+- *(application)* Clarify deployment type precedence logic (#8934)
+- *(git)* GitHub App webhook endpoint defaults to IPv4 instead of the instance domain
+- *(git)* GitHub App webhook endpoint defaults to IPv4 instead of the instance domain (#8948)
+- *(service)* Hoppscotch fails to start due to db unhealthy
+- *(service)* Hoppscotch fails to start due to db unhealthy (#8949)
+- *(api)* Allow is_container_label_escape_enabled in service operations (#8955)
+- *(docker-compose)* Respect preserveRepository when injecting --project-directory
+- *(docker-compose)* Respect preserveRepository when injecting --project-directory (#8956)
+- *(compose)* Include git branch in compose file not found error
+- *(template)* Fix heyform template
+- *(template)* Fix heyform template (#8747)
+- *(preview)* Exclude bind mounts from preview deployment suffix
+- *(preview)* Sync isPreviewSuffixEnabled property on file storage save
+- *(storages)* Hide PR suffix for services and fix instantSave logic
+- *(preview)* Enable per-volume control of PR suffix in preview deployments (#9006)
+- Prevent sporadic SSH permission denied by validating key content
+- *(ssh)* Handle chmod failures gracefully and simplify key management
+- Prevent sporadic SSH permission denied on key rotation (#8990)
+- *(stripe)* Add error handling and resilience to subscription operations
+- *(stripe)* Add error handling and resilience to subscription operations (#9030)
+- *(api)* Extract resource UUIDs from route parameters
+- *(backup)* Throw explicit error when S3 storage missing or deleted (#9038)
+- *(docker)* Skip cleanup stale warning on cloud instances
+- *(deployment)* Disable build server during restart operations
+- *(deployment)* Disable build server during restart operations (#9045)
+- *(docker)* Log failed cleanup attempts when server is not functional
+- *(environment-variable)* Guard refresh against missing or stale variables
+- *(github-webhook)* Handle unsupported event types gracefully
+- *(github-webhook)* Handle unsupported event types gracefully (#9119)
+- *(deployment)* Properly escape shell arguments in nixpacks commands
+- *(deployment)* Properly escape shell arguments in nixpacks commands (#9122)
+- *(validation)* Make hostname validation case-insensitive and expand allowed name characters (#9134)
+- *(team)* Resolve server limit checks for API token authentication (#9123)
+- *(subscription)* Prevent duplicate subscriptions with updateOrCreate
### 💼 Other
@@ -4886,6 +5188,12 @@ ### 💼 Other
- CVE-2025-55182 React2shell infected supabase/studio:2025.06.02-sha-8f2993d
- Bump superset to 6.0.0
- Trim whitespace from domain input in instance settings (#7837)
+- Upgrade postgres client to fix build error
+- Application rollback uses correct commit sha (#8576)
+- *(deps)* Bump rollup from 4.57.1 to 4.59.0
+- *(deps)* Bump rollup from 4.57.1 to 4.59.0 (#8691)
+- *(deps)* Bump league/commonmark from 2.8.0 to 2.8.1
+- *(deps)* Bump league/commonmark from 2.8.0 to 2.8.1 (#8793)
### 🚜 Refactor
@@ -5510,6 +5818,23 @@ ### 🚜 Refactor
- Move all env sorting to one place
- *(api)* Make docker_compose_raw description more clear
- *(api)* Update application create endpoints docs
+- *(api)* Application urls validation
+- *(services)* Improve some service slogans
+- *(ssh-retry)* Remove Sentry tracking from retry logic
+- *(ssh-retry)* Remove Sentry tracking from retry logic
+- *(jobs)* Split task skip checks into critical and runtime phases
+- Add explicit fillable array to EnvironmentVariable model
+- Replace inline note with callout component for consistency
+- *(application-source)* Use Laravel helpers for null checks
+- *(ssh)* Remove Sentry retry event tracking from ExecuteRemoteCommand
+- Consolidate file path validation patterns and support scoped packages
+- *(environment-variable)* Remove buildtime/runtime options and improve comment field
+- Remove verbose logging and use explicit exception types
+- *(breadcrumb)* Optimize queries and simplify state management
+- *(scheduler)* Extract cron scheduling logic to shared helper
+- *(team)* Make server limit methods accept optional team parameter
+- *(team)* Update serverOverflow to use static serverLimit
+- *(docker)* Simplify installation and remove version pinning
### 📚 Documentation
@@ -5616,7 +5941,6 @@ ### 📚 Documentation
- Update changelog
- *(tests)* Update testing guidelines for unit and feature tests
- *(sync)* Create AI Instructions Synchronization Guide and update CLAUDE.md references
-- Update changelog
- *(database-patterns)* Add critical note on mass assignment protection for new columns
- Clarify cloud-init script compatibility
- Update changelog
@@ -5647,7 +5971,27 @@ ### 📚 Documentation
- Update application architecture and database patterns for request-level caching best practices
- Remove git worktree symlink instructions from CLAUDE.md
- Remove git worktree symlink instructions from CLAUDE.md (#7908)
+- Add transcript lol link and logo to readme (#7331)
+- *(api)* Change domains to urls
+- *(api)* Improve domains API docs
- Update changelog
+- Update changelog
+- *(api)* Improve app endpoint deprecation description
+- Add Coolify design system reference
+- Add Coolify design system reference (#8237)
+- Update changelog
+- Update changelog
+- Update changelog
+- *(sponsors)* Add huge sponsors section and reorganize list
+- *(application)* Add comments explaining commit selection logic for rollback support
+- *(readme)* Add VPSDime to Big Sponsors list
+- *(readme)* Move MVPS to Huge Sponsors section
+- *(settings)* Clarify Do Not Track helper text
+- Update changelog
+- Update changelog
+- *(sponsors)* Add ScreenshotOne as a huge sponsor
+- *(sponsors)* Update Brand.dev to Context.dev
+- *(readme)* Add PetroSky Cloud to sponsors
### ⚡ Performance
@@ -5658,6 +6002,7 @@ ### ⚡ Performance
- Remove dead server filtering code from Kernel scheduler (#7585)
- *(server)* Optimize destinationsByServer query
- *(server)* Optimize destinationsByServer query (#7854)
+- *(breadcrumb)* Optimize queries and simplify navigation to fix OOM (#9048)
### 🎨 Styling
@@ -5670,6 +6015,7 @@ ### 🎨 Styling
- *(campfire)* Format environment variables for better readability in Docker Compose file
- *(campfire)* Update comment for DISABLE_SSL environment variable for clarity
- Update background colors to use gray-50 for consistency in auth views
+- *(modal-confirmation)* Improve mobile responsiveness
### 🧪 Testing
@@ -5686,6 +6032,14 @@ ### 🧪 Testing
- Add tests for shared environment variable spacing and resolution
- Add comprehensive preview deployment port and path tests
- Add comprehensive preview deployment port and path tests (#7677)
+- Add Pest browser testing with SQLite :memory: schema
+- Add dashboard test and improve browser test coverage
+- Migrate to SQLite :memory: and add Pest browser testing (#8364)
+- *(rollback)* Use full-length git commit SHA values in test fixtures
+- *(rollback)* Verify shell metacharacter escaping in git commit parameter
+- *(factories)* Add missing model factories for app test suite
+- *(magic-variables)* Add feature tests for SERVICE_URL/FQDN variable handling
+- Add behavioral ssh key stale-file regression
### ⚙️ Miscellaneous Tasks
@@ -6293,10 +6647,10 @@ ### ⚙️ Miscellaneous Tasks
- *(versions)* Update Coolify versions to 4.0.0-beta.420.2 and 4.0.0-beta.420.3 in multiple files
- *(versions)* Bump coolify and nightly versions to 4.0.0-beta.420.3 and 4.0.0-beta.420.4 respectively
- *(versions)* Update coolify and nightly versions to 4.0.0-beta.420.4 and 4.0.0-beta.420.5 respectively
-- *(service)* Update Nitropage template (#6181)
-- *(versions)* Update all version
- *(bump)* Update composer deps
- *(version)* Bump Coolify version to 4.0.0-beta.420.6
+- *(service)* Update Nitropage template (#6181)
+- *(versions)* Update all version
- *(service)* Improve matrix service
- *(service)* Format runner service
- *(service)* Improve sequin
@@ -6399,6 +6753,94 @@ ### ⚙️ Miscellaneous Tasks
- *(services)* Upgrade service template json files
- *(api)* Update openapi json and yaml
- *(api)* Regenerate openapi docs
+- Prepare for PR
+- *(api)* Improve current request error message
+- *(api)* Improve current request error message
+- *(api)* Update openapi files
+- *(service)* Update service templates json
+- *(services)* Update service template json files
+- *(service)* Use major version for openpanel (#8053)
+- Prepare for PR
+- *(services)* Update service template json files
+- Bump coolify version
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- *(scheduler)* Fix scheduled job duration metric (#8551)
+- Prepare for PR
+- Prepare for PR
+- *(horizon)* Make max time configurable (#8560)
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- *(ui)* Widen project heading nav spacing (#8564)
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Add pr quality check workflow
+- Do not build or generate changelog on pr-quality changes
+- Add pr quality check via anti slop action (#8344)
+- Improve pr quality workflow
+- Delete label removal workflow
+- Improve pr quality workflow (#8374)
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- *(repo)* Improve contributor PR template
+- Add anti-slop v0.2 options to the pr-quality check
+- Improve pr template and quality check workflow (#8574)
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- *(ui)* Add labels header
+- *(ui)* Add container labels header (#8752)
+- *(templates)* Update n8n templates to 2.10.2 (#8679)
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- *(version)* Bump coolify, realtime, and sentinel versions
+- *(realtime)* Upgrade npm dependencies
+- *(realtime)* Upgrade coolify-realtime to 1.0.11
+- Prepare for PR
+- Prepare for PR
+- Prepare for PR
+- *(release)* Bump version to 4.0.0-beta.466
+- Prepare for PR
+- Prepare for PR
+- *(service)* Pin castopod service to a static version instead of latest
+- *(service)* Remove unused attributes on imgcompress service
+- *(service)* Pin imgcompress to a static version instead of latest
+- *(service)* Update SeaweedFS images to version 4.13 (#8738)
+- *(templates)* Bump databasus image version
+- Remove coolify-examples-1 submodule
+- *(versions)* Bump coolify, sentinel, and traefik versions
+- *(versions)* Bump sentinel to 0.0.21
+- *(service)* Disable Booklore service (#9105)
### ◀️ Revert
diff --git a/CLAUDE.md b/CLAUDE.md
index 8e398586b..bb65da405 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -37,14 +37,33 @@ # Frontend
## Architecture
### Backend Structure (app/)
-- **Actions/** — Domain actions organized by area (Application, Database, Docker, Proxy, Server, Service, Shared, Stripe, User). Uses `lorisleiva/laravel-actions`.
-- **Livewire/** — All UI components (Livewire 3). Pages organized by domain: Server, Project, Settings, Notifications, etc. This is the primary UI layer — no traditional Blade controllers.
-- **Jobs/** — Queue jobs for deployments (`ApplicationDeploymentJob`), backups, Docker cleanup, server management, proxy configuration.
-- **Models/** — Eloquent models. Key models: `Server`, `Application`, `Service`, `Project`, `Environment`, `Team`, plus standalone database models (`StandalonePostgresql`, `StandaloneMysql`, etc.).
-- **Services/** — Business logic services.
-- **Helpers/** — Global helper functions loaded via `bootstrap/includeHelpers.php`.
-- **Data/** — Spatie Laravel Data DTOs.
-- **Enums/** — PHP enums (TitleCase keys).
+- **Actions/** — Domain actions organized by area (Application, Database, Docker, Proxy, Server, Service, Shared, Stripe, User, CoolifyTask, Fortify). Uses `lorisleiva/laravel-actions` with `AsAction` trait — actions can be called as objects, dispatched as jobs, or used as controllers.
+- **Livewire/** — All UI components (Livewire 3). Pages organized by domain: Server, Project, Settings, Security, Notifications, Terminal, Subscription, SharedVariables. This is the primary UI layer — no traditional Blade controllers. Components listen to private team channels for real-time status updates via Soketi.
+- **Jobs/** — Queue jobs for deployments (`ApplicationDeploymentJob`), backups, Docker cleanup, server management, proxy configuration. Uses Redis queue with Horizon for monitoring.
+- **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., `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.).
+
+### API Layer
+- REST API at `/api/v1/` with OpenAPI 3.0 attributes (`use OpenApi\Attributes as OA`) for auto-generated docs
+- Authentication via Laravel Sanctum with custom `ApiAbility` middleware for token abilities (read, write, deploy)
+- `ApiSensitiveData` middleware masks sensitive fields (IDs, credentials) in responses
+- API controllers in `app/Http/Controllers/Api/` use inline `Validator` (not Form Request classes)
+- Response serialization via `serializeApiResponse()` helper
+
+### Authorization
+- Policy-based authorization with ~15 model-to-policy mappings in `AuthServiceProvider`
+- Custom gates: `createAnyResource`, `canAccessTerminal`
+- Role hierarchy: `Role::MEMBER` (1) < `Role::ADMIN` (2) < `Role::OWNER` (3) with `lt()`/`gt()` comparison methods
+- Multi-tenancy via Teams — team auto-initializes notification settings on creation
+
+### Event Broadcasting
+- Soketi WebSocket server for real-time updates (ports 6001-6002 in dev)
+- Status change events: `ApplicationStatusChanged`, `ServiceStatusChanged`, `DatabaseStatusChanged`, `ProxyStatusChanged`
+- Livewire components subscribe to private team channels via `getListeners()`
### Key Domain Concepts
- **Server** — A managed host connected via SSH. Has settings, proxy config, and destinations.
@@ -61,7 +80,7 @@ ### Frontend
- Vite for asset bundling
### Laravel 10 Structure (NOT Laravel 11+ slim structure)
-- Middleware in `app/Http/Middleware/`
+- Middleware in `app/Http/Middleware/` — custom middleware includes `CheckForcePasswordReset`, `DecideWhatToDoWithUser`, `ApiAbility`, `ApiSensitiveData`
- Kernels: `app/Http/Kernel.php`, `app/Console/Kernel.php`
- Exception handler: `app/Exceptions/Handler.php`
- Service providers in `app/Providers/`
@@ -71,9 +90,9 @@ ## Key Conventions
- Use `php artisan make:*` commands with `--no-interaction` to create files
- Use Eloquent relationships, avoid `DB::` facade — prefer `Model::query()`
- PHP 8.4: constructor property promotion, explicit return types, type hints
-- Always create Form Request classes for validation
+- Validation uses inline `Validator` facade in controllers/Livewire components and custom rules in `app/Rules/` — not Form Request classes
- 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
@@ -93,14 +112,17 @@ ## Foundational Context
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
-- php - 8.4.1
+- php - 8.5
- laravel/fortify (FORTIFY) - v1
- laravel/framework (LARAVEL) - v12
- laravel/horizon (HORIZON) - v5
+- laravel/nightwatch (NIGHTWATCH) - v1
+- laravel/pail (PAIL) - v1
- laravel/prompts (PROMPTS) - v0
- laravel/sanctum (SANCTUM) - v4
- laravel/socialite (SOCIALITE) - v5
- livewire/livewire (LIVEWIRE) - v3
+- laravel/boost (BOOST) - v2
- laravel/dusk (DUSK) - v8
- laravel/mcp (MCP) - v0
- laravel/pint (PINT) - v1
@@ -116,11 +138,15 @@ ## Skills Activation
This project has domain-specific skills available. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
-- `livewire-development` — 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.
-- `pest-testing` — 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.
-- `tailwindcss-development` — 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.
-- `developing-with-fortify` — 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.
-- `debugging-output-and-previewing-html-using-ray` — Use when user says "send to Ray," "show in Ray," "debug in Ray," "log to Ray," "display in Ray," or wants to visualize data, debug output, or show diagrams in the Ray desktop application.
+- `laravel-best-practices` — 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.
+- `configuring-horizon` — 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.
+- `socialite-development` — 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.
+- `livewire-development` — 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.
+- `pest-testing` — 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.
+- `tailwindcss-development` — 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.
+- `fortify-development` — 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.
+- `laravel-actions` — 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.
+- `debugging-output-and-previewing-html-using-ray` — Use when user says "send to Ray," "show in Ray," "debug in Ray," "log to Ray," "display in Ray," or wants to visualize data, debug output, or show diagrams in the Ray desktop application.
## Conventions
@@ -153,76 +179,51 @@ ## Replies
# Laravel Boost
-- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.
+## Tools
+
+- Laravel Boost is an MCP server with tools designed specifically for this application. Prefer Boost tools over manual alternatives like shell commands or file reads.
+- Use `database-query` to run read-only queries against the database instead of writing raw SQL in tinker.
+- Use `database-schema` to inspect table structure before writing migrations or models.
+- Use `get-absolute-url` to resolve the correct scheme, domain, and port for project URLs. Always use this before sharing a URL with the user.
+- Use `browser-logs` to read browser logs, errors, and exceptions. Only recent logs are useful, ignore old entries.
+
+## Searching Documentation (IMPORTANT)
+
+- Always use `search-docs` before making code changes. Do not skip this step. It returns version-specific docs based on installed packages automatically.
+- Pass a `packages` array to scope results when you know which packages are relevant.
+- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first.
+- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`.
+
+### Search Syntax
+
+1. Use words for auto-stemmed AND logic: `rate limit` matches both "rate" AND "limit".
+2. Use `"quoted phrases"` for exact position matching: `"infinite scroll"` requires adjacent words in order.
+3. Combine words and phrases for mixed queries: `middleware "rate limit"`.
+4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`.
## Artisan
-- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters.
+- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters.
+- Inspect routes with `php artisan route:list`. Filter with: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`.
+- Read configuration values using dot notation: `php artisan config:show app.name`, `php artisan config:show database.default`. Or read config files directly from the `config/` directory.
+- To check environment variables, read the `.env` file directly.
-## URLs
+## Tinker
-- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port.
-
-## Tinker / Debugging
-
-- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.
-- Use the `database-query` tool when you only need to read from the database.
-
-## Reading Browser Logs With the `browser-logs` Tool
-
-- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.
-- Only recent browser logs will be useful - ignore old logs.
-
-## Searching Documentation (Critically Important)
-
-- Boost comes with a powerful `search-docs` tool you should use before trying other approaches when working with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
-- Search the documentation before making code changes to ensure we are taking the correct approach.
-- Use multiple, broad, simple, topic-based queries at once. For example: `['rate limiting', 'routing rate limiting', 'routing']`. The most relevant results will be returned first.
-- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.
-
-### Available Search Syntax
-
-1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'.
-2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit".
-3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order.
-4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit".
-5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms.
+- Execute PHP in app context for debugging and testing code. Do not create models without user approval, prefer tests with factories instead. Prefer existing Artisan commands over custom tinker code.
+- Always use single quotes to prevent shell expansion: `php artisan tinker --execute 'Your::code();'`
+ - Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'`
=== php rules ===
# PHP
- Always use curly braces for control structures, even for single-line bodies.
-
-## Constructors
-
-- Use PHP 8 constructor property promotion in `__construct()`.
- - public function __construct(public GitHub $github) { }
-- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private.
-
-## Type Declarations
-
-- Always use explicit return type declarations for methods and functions.
-- Use appropriate PHP type hints for method parameters.
-
-
-protected function isAccessible(User $user, ?string $path = null): bool
-{
- ...
-}
-
-
-## Enums
-
-- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
-
-## Comments
-
-- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless the logic is exceptionally complex.
-
-## PHPDoc Blocks
-
-- Add useful array shape type definitions when appropriate.
+- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private.
+- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool`
+- Use TitleCase for Enum keys: `FavoritePerson`, `BestLake`, `Monthly`.
+- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic.
+- Use array shape type definitions in PHPDoc blocks.
=== tests rules ===
@@ -235,47 +236,22 @@ # Test Enforcement
# Do Things the Laravel Way
-- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
+- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using `php artisan list` and check their parameters with `php artisan [command] --help`.
- If you're creating a generic PHP class, use `php artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
-## Database
-
-- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.
-- Use Eloquent models and relationships before suggesting raw database queries.
-- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.
-- Generate code that prevents N+1 query problems by using eager loading.
-- Use Laravel's query builder for very complex database operations.
-
### Model Creation
-- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `php artisan make:model`.
+- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `php artisan make:model --help` to check the available options.
-### APIs & Eloquent Resources
+## APIs & Eloquent Resources
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
-## Controllers & Validation
-
-- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.
-- Check sibling Form Requests to see if the application uses array or string based validation rules.
-
-## Authentication & Authorization
-
-- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
-
## URL Generation
- When generating links to other pages, prefer named routes and the `route()` function.
-## Queues
-
-- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.
-
-## Configuration
-
-- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.
-
## Testing
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
@@ -316,16 +292,15 @@ ### Models
# Livewire
-- Livewire allows you to build dynamic, reactive interfaces using only PHP — no JavaScript required.
-- Instead of writing frontend code in JavaScript frameworks, you use Alpine.js to build the UI when client-side interactions are required.
-- State lives on the server; the UI reflects it. Validate and authorize in actions (they're like HTTP requests).
-- IMPORTANT: Activate `livewire-development` every time you're working with Livewire-related tasks.
+- Livewire allow to build dynamic, reactive interfaces in PHP without writing JavaScript.
+- You can use Alpine.js for client-side interactions instead of JavaScript frameworks.
+- Keep state server-side so the UI reflects it. Validate and authorize in actions as you would in HTTP requests.
=== pint/core rules ===
# Laravel Pint Code Formatter
-- You must run `vendor/bin/pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
+- If you have modified any PHP files, you must run `vendor/bin/pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
- Do not run `vendor/bin/pint --test --format agent`, simply run `vendor/bin/pint --format agent` to fix any formatting issues.
=== pest/core rules ===
@@ -335,22 +310,5 @@ ## Pest
- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`.
- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`.
- Do NOT delete tests without approval.
-- CRITICAL: ALWAYS use `search-docs` tool for version-specific Pest documentation and updated code examples.
-- IMPORTANT: Activate `pest-testing` every time you're working with a Pest or testing-related task.
-=== tailwindcss/core rules ===
-
-# Tailwind CSS
-
-- Always use existing Tailwind conventions; check project patterns before adding new ones.
-- IMPORTANT: Always use `search-docs` tool for version-specific Tailwind CSS documentation and updated code examples. Never rely on training data.
-- IMPORTANT: Activate `tailwindcss-development` every time you're working with a Tailwind CSS or styling-related task.
-
-=== laravel/fortify rules ===
-
-# Laravel Fortify
-
-- Fortify is a headless authentication backend that provides authentication routes and controllers for Laravel applications.
-- IMPORTANT: Always use the `search-docs` tool for detailed Laravel Fortify patterns and documentation.
-- IMPORTANT: Activate `developing-with-fortify` skill when working with Fortify authentication features.
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/Actions/Fortify/CreateNewUser.php b/app/Actions/Fortify/CreateNewUser.php
index 9f97dd0d4..7ea6a871e 100644
--- a/app/Actions/Fortify/CreateNewUser.php
+++ b/app/Actions/Fortify/CreateNewUser.php
@@ -37,12 +37,13 @@ public function create(array $input): User
if (User::count() == 0) {
// If this is the first user, make them the root user
// Team is already created in the database/seeders/ProductionSeeder.php
- $user = User::create([
+ $user = (new User)->forceFill([
'id' => 0,
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
+ $user->save();
$team = $user->teams()->first();
// Disable registration after first user is created
diff --git a/app/Actions/Fortify/ResetUserPassword.php b/app/Actions/Fortify/ResetUserPassword.php
index 158996c90..5baa8b7ed 100644
--- a/app/Actions/Fortify/ResetUserPassword.php
+++ b/app/Actions/Fortify/ResetUserPassword.php
@@ -21,7 +21,7 @@ public function reset(User $user, array $input): void
'password' => ['required', Password::defaults(), 'confirmed'],
])->validate();
- $user->forceFill([
+ $user->fill([
'password' => Hash::make($input['password']),
])->save();
$user->deleteAllSessions();
diff --git a/app/Actions/Fortify/UpdateUserPassword.php b/app/Actions/Fortify/UpdateUserPassword.php
index 0c51ec56d..320eede0b 100644
--- a/app/Actions/Fortify/UpdateUserPassword.php
+++ b/app/Actions/Fortify/UpdateUserPassword.php
@@ -24,7 +24,7 @@ public function update(User $user, array $input): void
'current_password.current_password' => __('The provided password does not match your current password.'),
])->validateWithBag('updatePassword');
- $user->forceFill([
+ $user->fill([
'password' => Hash::make($input['password']),
])->save();
}
diff --git a/app/Actions/Fortify/UpdateUserProfileInformation.php b/app/Actions/Fortify/UpdateUserProfileInformation.php
index c8bfd930a..76c6c0736 100644
--- a/app/Actions/Fortify/UpdateUserProfileInformation.php
+++ b/app/Actions/Fortify/UpdateUserProfileInformation.php
@@ -35,7 +35,7 @@ public function update(User $user, array $input): void
) {
$this->updateVerifiedUser($user, $input);
} else {
- $user->forceFill([
+ $user->fill([
'name' => $input['name'],
'email' => $input['email'],
])->save();
@@ -49,7 +49,7 @@ public function update(User $user, array $input): void
*/
protected function updateVerifiedUser(User $user, array $input): void
{
- $user->forceFill([
+ $user->fill([
'name' => $input['name'],
'email' => $input['email'],
'email_verified_at' => null,
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/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/Actions/Service/StartService.php b/app/Actions/Service/StartService.php
index 6b5e1d4ac..17948d93b 100644
--- a/app/Actions/Service/StartService.php
+++ b/app/Actions/Service/StartService.php
@@ -40,10 +40,10 @@ public function handle(Service $service, bool $pullLatestImages = false, bool $s
$commands[] = "docker network connect $service->uuid coolify-proxy >/dev/null 2>&1 || true";
if (data_get($service, 'connect_to_docker_network')) {
$compose = data_get($service, 'docker_compose', []);
- $network = $service->destination->network;
+ $safeNetwork = escapeshellarg($service->destination->network);
$serviceNames = data_get(Yaml::parse($compose), 'services', []);
foreach ($serviceNames as $serviceName => $serviceConfig) {
- $commands[] = "docker network connect --alias {$serviceName}-{$service->uuid} $network {$serviceName}-{$service->uuid} >/dev/null 2>&1 || true";
+ $commands[] = "docker network connect --alias {$serviceName}-{$service->uuid} {$safeNetwork} {$serviceName}-{$service->uuid} >/dev/null 2>&1 || true";
}
}
diff --git a/app/Actions/Stripe/UpdateSubscriptionQuantity.php b/app/Actions/Stripe/UpdateSubscriptionQuantity.php
index a3eab4dca..d4d29af20 100644
--- a/app/Actions/Stripe/UpdateSubscriptionQuantity.php
+++ b/app/Actions/Stripe/UpdateSubscriptionQuantity.php
@@ -4,6 +4,7 @@
use App\Jobs\ServerLimitCheckJob;
use App\Models\Team;
+use Stripe\Exception\InvalidRequestException;
use Stripe\StripeClient;
class UpdateSubscriptionQuantity
@@ -42,6 +43,7 @@ public function fetchPricePreview(Team $team, int $quantity): array
}
$currency = strtoupper($item->price->currency ?? 'usd');
+ $billingInterval = $item->price->recurring->interval ?? 'month';
// Upcoming invoice gives us the prorated amount due now
$upcomingInvoice = $this->stripe->invoices->upcoming([
@@ -99,6 +101,7 @@ public function fetchPricePreview(Team $team, int $quantity): array
'tax_description' => $taxDescription,
'quantity' => $quantity,
'currency' => $currency,
+ 'billing_interval' => $billingInterval,
],
];
} catch (\Exception $e) {
@@ -184,7 +187,7 @@ public function execute(Team $team, int $quantity): array
\Log::info("Subscription {$subscription->stripe_subscription_id} quantity updated to {$quantity} for team {$team->name}");
return ['success' => true, 'error' => null];
- } catch (\Stripe\Exception\InvalidRequestException $e) {
+ } catch (InvalidRequestException $e) {
\Log::error("Stripe update quantity error for team {$team->id}: ".$e->getMessage());
return ['success' => false, 'error' => 'Stripe error: '.$e->getMessage()];
diff --git a/app/Console/Commands/Dev.php b/app/Console/Commands/Dev.php
index acc6dc2f9..7daa6ba28 100644
--- a/app/Console/Commands/Dev.php
+++ b/app/Console/Commands/Dev.php
@@ -30,32 +30,32 @@ public function init()
// Generate APP_KEY if not exists
if (empty(config('app.key'))) {
- echo "Generating APP_KEY.\n";
+ echo " INFO Generating APP_KEY.\n";
Artisan::call('key:generate');
}
// Generate STORAGE link if not exists
if (! file_exists(public_path('storage'))) {
- echo "Generating STORAGE link.\n";
+ echo " INFO Generating storage link.\n";
Artisan::call('storage:link');
}
// Seed database if it's empty
$settings = InstanceSettings::find(0);
if (! $settings) {
- echo "Initializing instance, seeding database.\n";
+ echo " INFO Initializing instance, seeding database.\n";
Artisan::call('migrate --seed');
} else {
- echo "Instance already initialized.\n";
+ echo " INFO Instance already initialized.\n";
}
// Clean up stuck jobs and stale locks on development startup
try {
- echo "Cleaning up Redis (stuck jobs and stale locks)...\n";
+ echo " INFO Cleaning up Redis (stuck jobs and stale locks)...\n";
Artisan::call('cleanup:redis', ['--restart' => true, '--clear-locks' => true]);
- echo "Redis cleanup completed.\n";
+ echo " INFO Redis cleanup completed.\n";
} catch (\Throwable $e) {
- echo "Error in cleanup:redis: {$e->getMessage()}\n";
+ echo " ERROR Redis cleanup failed: {$e->getMessage()}\n";
}
try {
@@ -66,10 +66,10 @@ public function init()
]);
if ($updatedTaskCount > 0) {
- echo "Marked {$updatedTaskCount} stuck scheduled task executions as failed\n";
+ echo " INFO Marked {$updatedTaskCount} stuck scheduled task executions as failed.\n";
}
} catch (\Throwable $e) {
- echo "Could not cleanup stuck scheduled task executions: {$e->getMessage()}\n";
+ echo " ERROR Could not clean up stuck scheduled task executions: {$e->getMessage()}\n";
}
try {
@@ -80,10 +80,10 @@ public function init()
]);
if ($updatedBackupCount > 0) {
- echo "Marked {$updatedBackupCount} stuck database backup executions as failed\n";
+ echo " INFO Marked {$updatedBackupCount} stuck database backup executions as failed.\n";
}
} catch (\Throwable $e) {
- echo "Could not cleanup stuck database backup executions: {$e->getMessage()}\n";
+ echo " ERROR Could not clean up stuck database backup executions: {$e->getMessage()}\n";
}
CheckHelperImageJob::dispatch();
diff --git a/app/Console/Commands/Horizon.php b/app/Console/Commands/Horizon.php
deleted file mode 100644
index d3e35ca5a..000000000
--- a/app/Console/Commands/Horizon.php
+++ /dev/null
@@ -1,23 +0,0 @@
-info('Horizon is enabled on this server.');
- $this->call('horizon');
- exit(0);
- } else {
- exit(0);
- }
- }
-}
diff --git a/app/Console/Commands/Init.php b/app/Console/Commands/Init.php
index 66cb77838..e95c29f72 100644
--- a/app/Console/Commands/Init.php
+++ b/app/Console/Commands/Init.php
@@ -212,18 +212,19 @@ private function cleanupUnusedNetworkFromCoolifyProxy()
$removeNetworks = $allNetworks->diff($networks);
$commands = collect();
foreach ($removeNetworks as $network) {
- $out = instant_remote_process(["docker network inspect -f json $network | jq '.[].Containers | if . == {} then null else . end'"], $server, false);
+ $safe = escapeshellarg($network);
+ $out = instant_remote_process(["docker network inspect -f json {$safe} | jq '.[].Containers | if . == {} then null else . end'"], $server, false);
if (empty($out)) {
- $commands->push("docker network disconnect $network coolify-proxy >/dev/null 2>&1 || true");
- $commands->push("docker network rm $network >/dev/null 2>&1 || true");
+ $commands->push("docker network disconnect {$safe} coolify-proxy >/dev/null 2>&1 || true");
+ $commands->push("docker network rm {$safe} >/dev/null 2>&1 || true");
} else {
$data = collect(json_decode($out, true));
if ($data->count() === 1) {
// If only coolify-proxy itself is connected to that network (it should not be possible, but who knows)
$isCoolifyProxyItself = data_get($data->first(), 'Name') === 'coolify-proxy';
if ($isCoolifyProxyItself) {
- $commands->push("docker network disconnect $network coolify-proxy >/dev/null 2>&1 || true");
- $commands->push("docker network rm $network >/dev/null 2>&1 || true");
+ $commands->push("docker network disconnect {$safe} coolify-proxy >/dev/null 2>&1 || true");
+ $commands->push("docker network rm {$safe} >/dev/null 2>&1 || true");
}
}
}
diff --git a/app/Console/Commands/Nightwatch.php b/app/Console/Commands/Nightwatch.php
deleted file mode 100644
index 40fd86a81..000000000
--- a/app/Console/Commands/Nightwatch.php
+++ /dev/null
@@ -1,22 +0,0 @@
-info('Nightwatch is enabled on this server.');
- $this->call('nightwatch:agent');
- }
-
- exit(0);
- }
-}
diff --git a/app/Console/Commands/Scheduler.php b/app/Console/Commands/Scheduler.php
deleted file mode 100644
index ee64368c3..000000000
--- a/app/Console/Commands/Scheduler.php
+++ /dev/null
@@ -1,23 +0,0 @@
-info('Scheduler is enabled on this server.');
- $this->call('schedule:work');
- exit(0);
- } else {
- exit(0);
- }
- }
-}
diff --git a/app/Console/Commands/SyncBunny.php b/app/Console/Commands/SyncBunny.php
index 0a98f1dc8..9ac3371e0 100644
--- a/app/Console/Commands/SyncBunny.php
+++ b/app/Console/Commands/SyncBunny.php
@@ -363,6 +363,162 @@ private function syncReleasesAndVersionsToGitHubRepo(string $versionsLocation, b
}
}
+ /**
+ * Sync install.sh, docker-compose, and env files to GitHub repository via PR
+ */
+ private function syncFilesToGitHubRepo(array $files, bool $nightly = false): bool
+ {
+ $envLabel = $nightly ? 'NIGHTLY' : 'PRODUCTION';
+ $this->info("Syncing $envLabel files to GitHub repository...");
+ try {
+ $timestamp = time();
+ $tmpDir = sys_get_temp_dir().'/coolify-cdn-files-'.$timestamp;
+ $branchName = 'update-files-'.$timestamp;
+
+ // Clone the repository
+ $this->info('Cloning coolify-cdn repository...');
+ $output = [];
+ exec('gh repo clone coollabsio/coolify-cdn '.escapeshellarg($tmpDir).' 2>&1', $output, $returnCode);
+ if ($returnCode !== 0) {
+ $this->error('Failed to clone repository: '.implode("\n", $output));
+
+ return false;
+ }
+
+ // Create feature branch
+ $this->info('Creating feature branch...');
+ $output = [];
+ exec('cd '.escapeshellarg($tmpDir).' && git checkout -b '.escapeshellarg($branchName).' 2>&1', $output, $returnCode);
+ if ($returnCode !== 0) {
+ $this->error('Failed to create branch: '.implode("\n", $output));
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ return false;
+ }
+
+ // Copy each file to its target path in the CDN repo
+ $copiedFiles = [];
+ foreach ($files as $sourceFile => $targetPath) {
+ if (! file_exists($sourceFile)) {
+ $this->warn("Source file not found, skipping: $sourceFile");
+
+ continue;
+ }
+
+ $destPath = "$tmpDir/$targetPath";
+ $destDir = dirname($destPath);
+
+ if (! is_dir($destDir)) {
+ if (! mkdir($destDir, 0755, true)) {
+ $this->error("Failed to create directory: $destDir");
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ return false;
+ }
+ }
+
+ if (copy($sourceFile, $destPath) === false) {
+ $this->error("Failed to copy $sourceFile to $destPath");
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ return false;
+ }
+
+ $copiedFiles[] = $targetPath;
+ $this->info("Copied: $targetPath");
+ }
+
+ if (empty($copiedFiles)) {
+ $this->warn('No files were copied. Nothing to commit.');
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ return true;
+ }
+
+ // Stage all copied files
+ $this->info('Staging changes...');
+ $output = [];
+ $stageCmd = 'cd '.escapeshellarg($tmpDir).' && git add '.implode(' ', array_map('escapeshellarg', $copiedFiles)).' 2>&1';
+ exec($stageCmd, $output, $returnCode);
+ if ($returnCode !== 0) {
+ $this->error('Failed to stage changes: '.implode("\n", $output));
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ return false;
+ }
+
+ // Check for changes
+ $this->info('Checking for changes...');
+ $statusOutput = [];
+ exec('cd '.escapeshellarg($tmpDir).' && git status --porcelain 2>&1', $statusOutput, $returnCode);
+ if ($returnCode !== 0) {
+ $this->error('Failed to check repository status: '.implode("\n", $statusOutput));
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ return false;
+ }
+
+ if (empty(array_filter($statusOutput))) {
+ $this->info('All files are already up to date. No changes to commit.');
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ return true;
+ }
+
+ // Commit changes
+ $commitMessage = "Update $envLabel files (install.sh, docker-compose, env) - ".date('Y-m-d H:i:s');
+ $output = [];
+ exec('cd '.escapeshellarg($tmpDir).' && git commit -m '.escapeshellarg($commitMessage).' 2>&1', $output, $returnCode);
+ if ($returnCode !== 0) {
+ $this->error('Failed to commit changes: '.implode("\n", $output));
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ return false;
+ }
+
+ // Push to remote
+ $this->info('Pushing branch to remote...');
+ $output = [];
+ exec('cd '.escapeshellarg($tmpDir).' && git push origin '.escapeshellarg($branchName).' 2>&1', $output, $returnCode);
+ if ($returnCode !== 0) {
+ $this->error('Failed to push branch: '.implode("\n", $output));
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ return false;
+ }
+
+ // Create pull request
+ $this->info('Creating pull request...');
+ $prTitle = "Update $envLabel files - ".date('Y-m-d H:i:s');
+ $fileList = implode("\n- ", $copiedFiles);
+ $prBody = "Automated update of $envLabel files:\n- $fileList";
+ $prCommand = 'gh pr create --repo coollabsio/coolify-cdn --title '.escapeshellarg($prTitle).' --body '.escapeshellarg($prBody).' --base main --head '.escapeshellarg($branchName).' 2>&1';
+ $output = [];
+ exec($prCommand, $output, $returnCode);
+
+ // Clean up
+ exec('rm -rf '.escapeshellarg($tmpDir));
+
+ if ($returnCode !== 0) {
+ $this->error('Failed to create PR: '.implode("\n", $output));
+
+ return false;
+ }
+
+ $this->info('Pull request created successfully!');
+ if (! empty($output)) {
+ $this->info('PR URL: '.implode("\n", $output));
+ }
+ $this->info('Files synced: '.count($copiedFiles));
+
+ return true;
+ } catch (\Throwable $e) {
+ $this->error('Error syncing files to GitHub: '.$e->getMessage());
+
+ return false;
+ }
+ }
+
/**
* Sync versions.json to GitHub repository via PR
*/
@@ -581,11 +737,130 @@ public function handle()
$versions_location = "$parent_dir/other/nightly/$versions";
}
if (! $only_template && ! $only_version && ! $only_github_releases && ! $only_github_versions) {
+ $envLabel = $nightly ? 'NIGHTLY' : 'PRODUCTION';
+ $this->info("About to sync $envLabel files to BunnyCDN and create a GitHub PR for coolify-cdn.");
+ $this->newLine();
+
+ // Build file mapping for diff
if ($nightly) {
- $this->info('About to sync files NIGHTLY (docker-compose.prod.yaml, upgrade.sh, install.sh, etc) to BunnyCDN.');
+ $fileMapping = [
+ $compose_file_location => 'docker/nightly/docker-compose.yml',
+ $compose_file_prod_location => 'docker/nightly/docker-compose.prod.yml',
+ $production_env_location => 'environment/nightly/.env.production',
+ $upgrade_script_location => 'scripts/nightly/upgrade.sh',
+ $install_script_location => 'scripts/nightly/install.sh',
+ ];
} else {
- $this->info('About to sync files PRODUCTION (docker-compose.yml, docker-compose.prod.yml, upgrade.sh, install.sh, etc) to BunnyCDN.');
+ $fileMapping = [
+ $compose_file_location => 'docker/docker-compose.yml',
+ $compose_file_prod_location => 'docker/docker-compose.prod.yml',
+ $production_env_location => 'environment/.env.production',
+ $upgrade_script_location => 'scripts/upgrade.sh',
+ $install_script_location => 'scripts/install.sh',
+ ];
}
+
+ // BunnyCDN file mapping (local file => CDN URL path)
+ $bunnyFileMapping = [
+ $compose_file_location => "$bunny_cdn/$bunny_cdn_path/$compose_file",
+ $compose_file_prod_location => "$bunny_cdn/$bunny_cdn_path/$compose_file_prod",
+ $production_env_location => "$bunny_cdn/$bunny_cdn_path/$production_env",
+ $upgrade_script_location => "$bunny_cdn/$bunny_cdn_path/$upgrade_script",
+ $install_script_location => "$bunny_cdn/$bunny_cdn_path/$install_script",
+ ];
+
+ $diffTmpDir = sys_get_temp_dir().'/coolify-cdn-diff-'.time();
+ @mkdir($diffTmpDir, 0755, true);
+ $hasChanges = false;
+
+ // Diff against BunnyCDN
+ $this->info('Fetching files from BunnyCDN to compare...');
+ foreach ($bunnyFileMapping as $localFile => $cdnUrl) {
+ if (! file_exists($localFile)) {
+ $this->warn('Local file not found: '.$localFile);
+
+ continue;
+ }
+
+ $fileName = basename($cdnUrl);
+ $remoteTmp = "$diffTmpDir/bunny-$fileName";
+
+ try {
+ $response = Http::timeout(10)->get($cdnUrl);
+ if ($response->successful()) {
+ file_put_contents($remoteTmp, $response->body());
+ $diffOutput = [];
+ exec('diff -u '.escapeshellarg($remoteTmp).' '.escapeshellarg($localFile).' 2>&1', $diffOutput, $diffCode);
+ if ($diffCode !== 0) {
+ $hasChanges = true;
+ $this->newLine();
+ $this->info("--- BunnyCDN: $bunny_cdn_path/$fileName");
+ $this->info("+++ Local: $fileName");
+ foreach ($diffOutput as $line) {
+ if (str_starts_with($line, '---') || str_starts_with($line, '+++')) {
+ continue;
+ }
+ $this->line($line);
+ }
+ }
+ } else {
+ $this->info("NEW on BunnyCDN: $bunny_cdn_path/$fileName (HTTP {$response->status()})");
+ $hasChanges = true;
+ }
+ } catch (\Throwable $e) {
+ $this->warn("Could not fetch $cdnUrl: {$e->getMessage()}");
+ }
+ }
+
+ // Diff against GitHub coolify-cdn repo
+ $this->newLine();
+ $this->info('Fetching coolify-cdn repo to compare...');
+ $output = [];
+ exec('gh repo clone coollabsio/coolify-cdn '.escapeshellarg("$diffTmpDir/repo").' -- --depth 1 2>&1', $output, $returnCode);
+
+ if ($returnCode === 0) {
+ foreach ($fileMapping as $localFile => $cdnPath) {
+ $remotePath = "$diffTmpDir/repo/$cdnPath";
+ if (! file_exists($localFile)) {
+ continue;
+ }
+ if (! file_exists($remotePath)) {
+ $this->info("NEW on GitHub: $cdnPath (does not exist in coolify-cdn yet)");
+ $hasChanges = true;
+
+ continue;
+ }
+
+ $diffOutput = [];
+ exec('diff -u '.escapeshellarg($remotePath).' '.escapeshellarg($localFile).' 2>&1', $diffOutput, $diffCode);
+ if ($diffCode !== 0) {
+ $hasChanges = true;
+ $this->newLine();
+ $this->info("--- GitHub: $cdnPath");
+ $this->info("+++ Local: $cdnPath");
+ foreach ($diffOutput as $line) {
+ if (str_starts_with($line, '---') || str_starts_with($line, '+++')) {
+ continue;
+ }
+ $this->line($line);
+ }
+ }
+ }
+ } else {
+ $this->warn('Could not fetch coolify-cdn repo for diff.');
+ }
+
+ exec('rm -rf '.escapeshellarg($diffTmpDir));
+
+ if (! $hasChanges) {
+ $this->newLine();
+ $this->info('No differences found. All files are already up to date.');
+
+ return;
+ }
+
+ $this->newLine();
+
$confirmed = confirm('Are you sure you want to sync?');
if (! $confirmed) {
return;
@@ -692,7 +967,34 @@ public function handle()
$pool->purge("$bunny_cdn/$bunny_cdn_path/$upgrade_script"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$install_script"),
]);
- $this->info('All files uploaded & purged...');
+ $this->info('All files uploaded & purged to BunnyCDN.');
+ $this->newLine();
+
+ // Sync files to GitHub CDN repository via PR
+ $this->info('Creating GitHub PR for coolify-cdn repository...');
+ if ($nightly) {
+ $files = [
+ $compose_file_location => 'docker/nightly/docker-compose.yml',
+ $compose_file_prod_location => 'docker/nightly/docker-compose.prod.yml',
+ $production_env_location => 'environment/nightly/.env.production',
+ $upgrade_script_location => 'scripts/nightly/upgrade.sh',
+ $install_script_location => 'scripts/nightly/install.sh',
+ ];
+ } else {
+ $files = [
+ $compose_file_location => 'docker/docker-compose.yml',
+ $compose_file_prod_location => 'docker/docker-compose.prod.yml',
+ $production_env_location => 'environment/.env.production',
+ $upgrade_script_location => 'scripts/upgrade.sh',
+ $install_script_location => 'scripts/install.sh',
+ ];
+ }
+
+ $githubSuccess = $this->syncFilesToGitHubRepo($files, $nightly);
+ $this->newLine();
+ $this->info('=== Summary ===');
+ $this->info('BunnyCDN sync: Complete');
+ $this->info('GitHub PR: '.($githubSuccess ? 'Created' : 'Failed'));
} catch (\Throwable $e) {
$this->error('Error: '.$e->getMessage());
}
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/Http/Controllers/Api/ApplicationsController.php b/app/Http/Controllers/Api/ApplicationsController.php
index 66f6a1ef8..77f4e626f 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;
@@ -229,6 +230,7 @@ public function applications(Request $request)
'force_domain_override' => ['type' => 'boolean', 'description' => 'Force domain usage even if conflicts are detected. Default is false.'],
'autogenerate_domain' => ['type' => 'boolean', 'default' => true, 'description' => 'If true and domains is empty, auto-generate a domain using the server\'s wildcard domain or sslip.io fallback. Default: true.'],
'is_container_label_escape_enabled' => ['type' => 'boolean', 'default' => true, 'description' => 'Escape special characters in labels. By default, $ (and other chars) is escaped. So if you write $ in the labels, it will be saved as $$. If you want to use env variables inside the labels, turn this off.'],
+ 'is_preserve_repository_enabled' => ['type' => 'boolean', 'default' => false, 'description' => 'Preserve repository during deployment.'],
],
)
),
@@ -394,6 +396,7 @@ public function create_public_application(Request $request)
'force_domain_override' => ['type' => 'boolean', 'description' => 'Force domain usage even if conflicts are detected. Default is false.'],
'autogenerate_domain' => ['type' => 'boolean', 'default' => true, 'description' => 'If true and domains is empty, auto-generate a domain using the server\'s wildcard domain or sslip.io fallback. Default: true.'],
'is_container_label_escape_enabled' => ['type' => 'boolean', 'default' => true, 'description' => 'Escape special characters in labels. By default, $ (and other chars) is escaped. So if you write $ in the labels, it will be saved as $$. If you want to use env variables inside the labels, turn this off.'],
+ 'is_preserve_repository_enabled' => ['type' => 'boolean', 'default' => false, 'description' => 'Preserve repository during deployment.'],
],
)
),
@@ -559,6 +562,7 @@ public function create_private_gh_app_application(Request $request)
'force_domain_override' => ['type' => 'boolean', 'description' => 'Force domain usage even if conflicts are detected. Default is false.'],
'autogenerate_domain' => ['type' => 'boolean', 'default' => true, 'description' => 'If true and domains is empty, auto-generate a domain using the server\'s wildcard domain or sslip.io fallback. Default: true.'],
'is_container_label_escape_enabled' => ['type' => 'boolean', 'default' => true, 'description' => 'Escape special characters in labels. By default, $ (and other chars) is escaped. So if you write $ in the labels, it will be saved as $$. If you want to use env variables inside the labels, turn this off.'],
+ 'is_preserve_repository_enabled' => ['type' => 'boolean', 'default' => false, 'description' => 'Preserve repository during deployment.'],
],
)
),
@@ -1002,10 +1006,10 @@ 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'];
+ $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', 'is_preserve_repository_enabled'];
$validator = customApiValidator($request->all(), [
'name' => 'string|max:255',
@@ -1054,6 +1058,7 @@ private function create_application(Request $request, $type)
$connectToDockerNetwork = $request->connect_to_docker_network;
$customNginxConfiguration = $request->custom_nginx_configuration;
$isContainerLabelEscapeEnabled = $request->boolean('is_container_label_escape_enabled', true);
+ $isPreserveRepositoryEnabled = $request->boolean('is_preserve_repository_enabled',false);
if (! is_null($customNginxConfiguration)) {
if (! isBase64Encoded($customNginxConfiguration)) {
@@ -1150,14 +1155,14 @@ 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;
}
$application = new Application;
removeUnnecessaryFieldsFromRequest($request);
- $application->fill($request->all());
+ $application->fill($request->only($allowedFields));
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
$dockerComposeDomains = collect($request->docker_compose_domains);
@@ -1266,6 +1271,10 @@ private function create_application(Request $request, $type)
$application->settings->is_container_label_escape_enabled = $isContainerLabelEscapeEnabled;
$application->settings->save();
}
+ if (isset($isPreserveRepositoryEnabled)) {
+ $application->settings->is_preserve_repository_enabled = $isPreserveRepositoryEnabled;
+ $application->settings->save();
+ }
$application->refresh();
// Auto-generate domain if requested and no custom domain provided
if ($autogenerateDomain && blank($fqdn)) {
@@ -1345,7 +1354,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();
@@ -1384,7 +1393,7 @@ private function create_application(Request $request, $type)
$application = new Application;
removeUnnecessaryFieldsFromRequest($request);
- $application->fill($request->all());
+ $application->fill($request->only($allowedFields));
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
@@ -1498,6 +1507,10 @@ private function create_application(Request $request, $type)
$application->settings->is_container_label_escape_enabled = $isContainerLabelEscapeEnabled;
$application->settings->save();
}
+ if (isset($isPreserveRepositoryEnabled)) {
+ $application->settings->is_preserve_repository_enabled = $isPreserveRepositoryEnabled;
+ $application->settings->save();
+ }
if ($application->settings->is_container_label_readonly_enabled) {
$application->custom_labels = str(implode('|coolify|', generateLabelsApplication($application)))->replace('|coolify|', "\n");
$application->save();
@@ -1573,7 +1586,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();
@@ -1584,7 +1597,7 @@ private function create_application(Request $request, $type)
$application = new Application;
removeUnnecessaryFieldsFromRequest($request);
- $application->fill($request->all());
+ $application->fill($request->only($allowedFields));
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
@@ -1694,6 +1707,10 @@ private function create_application(Request $request, $type)
$application->settings->is_container_label_escape_enabled = $isContainerLabelEscapeEnabled;
$application->settings->save();
}
+ if (isset($isPreserveRepositoryEnabled)) {
+ $application->settings->is_preserve_repository_enabled = $isPreserveRepositoryEnabled;
+ $application->settings->save();
+ }
if ($application->settings->is_container_label_readonly_enabled) {
$application->custom_labels = str(implode('|coolify|', generateLabelsApplication($application)))->replace('|coolify|', "\n");
$application->save();
@@ -1742,7 +1759,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)) {
@@ -1771,7 +1788,7 @@ private function create_application(Request $request, $type)
}
$application = new Application;
- $application->fill($request->all());
+ $application->fill($request->only($allowedFields));
$application->fqdn = $fqdn;
$application->ports_exposes = $port;
$application->build_pack = 'dockerfile';
@@ -1850,7 +1867,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
@@ -1883,7 +1900,7 @@ private function create_application(Request $request, $type)
$application = new Application;
removeUnnecessaryFieldsFromRequest($request);
- $application->fill($request->all());
+ $application->fill($request->only($allowedFields));
$application->fqdn = $fqdn;
$application->build_pack = 'dockerimage';
$application->destination_id = $destination->id;
@@ -1974,7 +1991,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)) {
@@ -1999,7 +2016,7 @@ private function create_application(Request $request, $type)
$service = new Service;
removeUnnecessaryFieldsFromRequest($request);
- $service->fill($request->all());
+ $service->fill($request->only($allowedFields));
$service->docker_compose_raw = $dockerComposeRaw;
$service->environment_id = $environment->id;
@@ -2389,6 +2406,7 @@ public function delete_by_uuid(Request $request)
'connect_to_docker_network' => ['type' => 'boolean', 'description' => 'The flag to connect the service to the predefined Docker network.'],
'force_domain_override' => ['type' => 'boolean', 'description' => 'Force domain usage even if conflicts are detected. Default is false.'],
'is_container_label_escape_enabled' => ['type' => 'boolean', 'default' => true, 'description' => 'Escape special characters in labels. By default, $ (and other chars) is escaped. So if you write $ in the labels, it will be saved as $$. If you want to use env variables inside the labels, turn this off.'],
+ 'is_preserve_repository_enabled' => ['type' => 'boolean', 'description' => 'Preserve git repository during application update. If false, the existing repository will be removed and replaced with the new one. If true, the existing repository will be kept and the new one will be ignored. Default is false.'],
],
)
),
@@ -2460,7 +2478,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;
}
@@ -2474,7 +2492,7 @@ public function update_by_uuid(Request $request)
$this->authorize('update', $application);
$server = $application->destination->server;
- $allowedFields = ['name', 'description', 'is_static', 'is_spa', 'is_auto_deploy_enabled', 'is_force_https_enabled', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'static_image', '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', 'watch_paths', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'dockerfile_location', 'dockerfile_target_build', 'docker_compose_location', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'redirect', 'instant_deploy', 'use_build_server', 'custom_nginx_configuration', 'is_http_basic_auth_enabled', 'http_basic_auth_username', 'http_basic_auth_password', 'connect_to_docker_network', 'force_domain_override', 'is_container_label_escape_enabled'];
+ $allowedFields = ['name', 'description', 'is_static', 'is_spa', 'is_auto_deploy_enabled', 'is_force_https_enabled', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'static_image', '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', 'watch_paths', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'dockerfile_location', 'dockerfile_target_build', 'docker_compose_location', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'redirect', 'instant_deploy', 'use_build_server', 'custom_nginx_configuration', 'is_http_basic_auth_enabled', 'http_basic_auth_username', 'http_basic_auth_password', 'connect_to_docker_network', 'force_domain_override', 'is_container_label_escape_enabled', 'is_preserve_repository_enabled'];
$validationRules = [
'name' => 'string|max:255',
@@ -2530,7 +2548,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);
@@ -2721,7 +2739,7 @@ public function update_by_uuid(Request $request)
$connectToDockerNetwork = $request->connect_to_docker_network;
$useBuildServer = $request->use_build_server;
$isContainerLabelEscapeEnabled = $request->boolean('is_container_label_escape_enabled');
-
+ $isPreserveRepositoryEnabled = $request->boolean('is_preserve_repository_enabled');
if (isset($useBuildServer)) {
$application->settings->is_build_server_enabled = $useBuildServer;
$application->settings->save();
@@ -2756,10 +2774,13 @@ public function update_by_uuid(Request $request)
$application->settings->is_container_label_escape_enabled = $isContainerLabelEscapeEnabled;
$application->settings->save();
}
-
+ if ($request->has('is_preserve_repository_enabled')) {
+ $application->settings->is_preserve_repository_enabled = $isPreserveRepositoryEnabled;
+ $application->settings->save();
+ }
removeUnnecessaryFieldsFromRequest($request);
- $data = $request->all();
+ $data = $request->only($allowedFields);
if ($requestHasDomains && $server->isProxyShouldRun()) {
data_set($data, 'fqdn', $domains);
}
@@ -2956,7 +2977,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 +3178,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 +4098,7 @@ public function update_storage(Request $request): JsonResponse
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -4096,7 +4117,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 +4295,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',
@@ -4361,6 +4382,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 700055fcc..8e31a7051 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;
@@ -263,6 +264,7 @@ public function database_by_uuid(Request $request)
'image' => ['type' => 'string', 'description' => 'Docker Image of the database'],
'is_public' => ['type' => 'boolean', 'description' => 'Is the database public?'],
'public_port' => ['type' => 'integer', 'description' => 'Public port of the database'],
+ 'public_port_timeout' => ['type' => 'integer', 'description' => 'Public port timeout in seconds (default: 3600)'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit of the database'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit of the database'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness of the database'],
@@ -326,7 +328,7 @@ public function database_by_uuid(Request $request)
)]
public function update_by_uuid(Request $request)
{
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf', 'clickhouse_admin_user', 'clickhouse_admin_password', 'dragonfly_password', 'redis_password', 'redis_conf', 'keydb_password', 'keydb_conf', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf', 'clickhouse_admin_user', 'clickhouse_admin_password', 'dragonfly_password', 'redis_password', 'redis_conf', 'keydb_password', 'keydb_conf', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
@@ -334,7 +336,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(), [
@@ -343,6 +345,7 @@ public function update_by_uuid(Request $request)
'image' => 'string',
'is_public' => 'boolean',
'public_port' => 'numeric|nullable',
+ 'public_port_timeout' => 'integer|nullable|min:1',
'limits_memory' => 'string',
'limits_memory_swap' => 'string',
'limits_memory_swappiness' => 'numeric',
@@ -374,7 +377,7 @@ public function update_by_uuid(Request $request)
}
switch ($database->type()) {
case 'standalone-postgresql':
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf'];
$validator = customApiValidator($request->all(), [
'postgres_user' => 'string',
'postgres_password' => 'string',
@@ -405,20 +408,20 @@ public function update_by_uuid(Request $request)
}
break;
case 'standalone-clickhouse':
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'clickhouse_admin_user', 'clickhouse_admin_password'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'clickhouse_admin_user', 'clickhouse_admin_password'];
$validator = customApiValidator($request->all(), [
'clickhouse_admin_user' => 'string',
'clickhouse_admin_password' => 'string',
]);
break;
case 'standalone-dragonfly':
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'dragonfly_password'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'dragonfly_password'];
$validator = customApiValidator($request->all(), [
'dragonfly_password' => 'string',
]);
break;
case 'standalone-redis':
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'redis_password', 'redis_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'redis_password', 'redis_conf'];
$validator = customApiValidator($request->all(), [
'redis_password' => 'string',
'redis_conf' => 'string',
@@ -445,7 +448,7 @@ public function update_by_uuid(Request $request)
}
break;
case 'standalone-keydb':
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'keydb_password', 'keydb_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'keydb_password', 'keydb_conf'];
$validator = customApiValidator($request->all(), [
'keydb_password' => 'string',
'keydb_conf' => 'string',
@@ -472,7 +475,7 @@ public function update_by_uuid(Request $request)
}
break;
case 'standalone-mariadb':
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database'];
$validator = customApiValidator($request->all(), [
'mariadb_conf' => 'string',
'mariadb_root_password' => 'string',
@@ -502,7 +505,7 @@ public function update_by_uuid(Request $request)
}
break;
case 'standalone-mongodb':
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database'];
$validator = customApiValidator($request->all(), [
'mongo_conf' => 'string',
'mongo_initdb_root_username' => 'string',
@@ -532,7 +535,7 @@ public function update_by_uuid(Request $request)
break;
case 'standalone-mysql':
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
$validator = customApiValidator($request->all(), [
'mysql_root_password' => 'string',
'mysql_password' => 'string',
@@ -640,6 +643,7 @@ public function update_by_uuid(Request $request)
'database_backup_retention_amount_s3' => ['type' => 'integer', 'description' => 'Number of backups to retain in S3'],
'database_backup_retention_days_s3' => ['type' => 'integer', 'description' => 'Number of days to retain backups in S3'],
'database_backup_retention_max_storage_s3' => ['type' => 'integer', 'description' => 'Max storage (MB) for S3 backups'],
+ 'timeout' => ['type' => 'integer', 'description' => 'Backup job timeout in seconds (min: 60, max: 36000)', 'default' => 3600],
],
),
)
@@ -676,7 +680,7 @@ public function update_by_uuid(Request $request)
)]
public function create_backup(Request $request)
{
- $backupConfigFields = ['save_s3', 'enabled', 'dump_all', 'frequency', 'databases_to_backup', 'database_backup_retention_amount_locally', 'database_backup_retention_days_locally', 'database_backup_retention_max_storage_locally', 'database_backup_retention_amount_s3', 'database_backup_retention_days_s3', 'database_backup_retention_max_storage_s3', 's3_storage_uuid'];
+ $backupConfigFields = ['save_s3', 'enabled', 'dump_all', 'frequency', 'databases_to_backup', 'database_backup_retention_amount_locally', 'database_backup_retention_days_locally', 'database_backup_retention_max_storage_locally', 'database_backup_retention_amount_s3', 'database_backup_retention_days_s3', 'database_backup_retention_max_storage_s3', 's3_storage_uuid', 'timeout'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
@@ -685,7 +689,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;
}
@@ -703,6 +707,7 @@ public function create_backup(Request $request)
'database_backup_retention_amount_s3' => 'integer|min:0',
'database_backup_retention_days_s3' => 'integer|min:0',
'database_backup_retention_max_storage_s3' => 'integer|min:0',
+ 'timeout' => 'integer|min:60|max:36000',
]);
if ($validator->fails()) {
@@ -792,6 +797,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();
@@ -865,6 +882,7 @@ public function create_backup(Request $request)
'database_backup_retention_amount_s3' => ['type' => 'integer', 'description' => 'Retention amount of the backup in s3'],
'database_backup_retention_days_s3' => ['type' => 'integer', 'description' => 'Retention days of the backup in s3'],
'database_backup_retention_max_storage_s3' => ['type' => 'integer', 'description' => 'Max storage of the backup in S3'],
+ 'timeout' => ['type' => 'integer', 'description' => 'Backup job timeout in seconds (min: 60, max: 36000)', 'default' => 3600],
],
),
)
@@ -894,7 +912,7 @@ public function create_backup(Request $request)
)]
public function update_backup(Request $request)
{
- $backupConfigFields = ['save_s3', 'enabled', 'dump_all', 'frequency', 'databases_to_backup', 'database_backup_retention_amount_locally', 'database_backup_retention_days_locally', 'database_backup_retention_max_storage_locally', 'database_backup_retention_amount_s3', 'database_backup_retention_days_s3', 'database_backup_retention_max_storage_s3', 's3_storage_uuid'];
+ $backupConfigFields = ['save_s3', 'enabled', 'dump_all', 'frequency', 'databases_to_backup', 'database_backup_retention_amount_locally', 'database_backup_retention_days_locally', 'database_backup_retention_max_storage_locally', 'database_backup_retention_amount_s3', 'database_backup_retention_days_s3', 'database_backup_retention_max_storage_s3', 's3_storage_uuid', 'timeout'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
@@ -902,7 +920,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(), [
@@ -912,13 +930,14 @@ public function update_backup(Request $request)
'dump_all' => 'boolean',
's3_storage_uuid' => 'string|exists:s3_storages,uuid|nullable',
'databases_to_backup' => 'string|nullable',
- 'frequency' => 'string|in:every_minute,hourly,daily,weekly,monthly,yearly',
+ 'frequency' => 'string',
'database_backup_retention_amount_locally' => 'integer|min:0',
'database_backup_retention_days_locally' => 'integer|min:0',
'database_backup_retention_max_storage_locally' => 'integer|min:0',
'database_backup_retention_amount_s3' => 'integer|min:0',
'database_backup_retention_days_s3' => 'integer|min:0',
'database_backup_retention_max_storage_s3' => 'integer|min:0',
+ 'timeout' => 'integer|min:60|max:36000',
]);
if ($validator->fails()) {
return response()->json([
@@ -945,6 +964,17 @@ public function update_backup(Request $request)
$this->authorize('update', $database);
+ // Validate frequency is a valid cron expression
+ if ($request->filled('frequency')) {
+ $isValid = validate_cron_expression($request->frequency);
+ if (! $isValid) {
+ return response()->json([
+ 'message' => 'Validation failed.',
+ 'errors' => ['frequency' => ['Invalid cron expression or frequency format.']],
+ ], 422);
+ }
+ }
+
if ($request->boolean('save_s3') && ! $request->filled('s3_storage_uuid')) {
return response()->json([
'message' => 'Validation failed.',
@@ -997,6 +1027,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) {
@@ -1043,6 +1085,7 @@ public function update_backup(Request $request)
'image' => ['type' => 'string', 'description' => 'Docker Image of the database'],
'is_public' => ['type' => 'boolean', 'description' => 'Is the database public?'],
'public_port' => ['type' => 'integer', 'description' => 'Public port of the database'],
+ 'public_port_timeout' => ['type' => 'integer', 'description' => 'Public port timeout in seconds (default: 3600)'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit of the database'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit of the database'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness of the database'],
@@ -1110,6 +1153,7 @@ public function create_database_postgresql(Request $request)
'image' => ['type' => 'string', 'description' => 'Docker Image of the database'],
'is_public' => ['type' => 'boolean', 'description' => 'Is the database public?'],
'public_port' => ['type' => 'integer', 'description' => 'Public port of the database'],
+ 'public_port_timeout' => ['type' => 'integer', 'description' => 'Public port timeout in seconds (default: 3600)'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit of the database'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit of the database'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness of the database'],
@@ -1176,6 +1220,7 @@ public function create_database_clickhouse(Request $request)
'image' => ['type' => 'string', 'description' => 'Docker Image of the database'],
'is_public' => ['type' => 'boolean', 'description' => 'Is the database public?'],
'public_port' => ['type' => 'integer', 'description' => 'Public port of the database'],
+ 'public_port_timeout' => ['type' => 'integer', 'description' => 'Public port timeout in seconds (default: 3600)'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit of the database'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit of the database'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness of the database'],
@@ -1243,6 +1288,7 @@ public function create_database_dragonfly(Request $request)
'image' => ['type' => 'string', 'description' => 'Docker Image of the database'],
'is_public' => ['type' => 'boolean', 'description' => 'Is the database public?'],
'public_port' => ['type' => 'integer', 'description' => 'Public port of the database'],
+ 'public_port_timeout' => ['type' => 'integer', 'description' => 'Public port timeout in seconds (default: 3600)'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit of the database'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit of the database'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness of the database'],
@@ -1310,6 +1356,7 @@ public function create_database_redis(Request $request)
'image' => ['type' => 'string', 'description' => 'Docker Image of the database'],
'is_public' => ['type' => 'boolean', 'description' => 'Is the database public?'],
'public_port' => ['type' => 'integer', 'description' => 'Public port of the database'],
+ 'public_port_timeout' => ['type' => 'integer', 'description' => 'Public port timeout in seconds (default: 3600)'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit of the database'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit of the database'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness of the database'],
@@ -1380,6 +1427,7 @@ public function create_database_keydb(Request $request)
'image' => ['type' => 'string', 'description' => 'Docker Image of the database'],
'is_public' => ['type' => 'boolean', 'description' => 'Is the database public?'],
'public_port' => ['type' => 'integer', 'description' => 'Public port of the database'],
+ 'public_port_timeout' => ['type' => 'integer', 'description' => 'Public port timeout in seconds (default: 3600)'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit of the database'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit of the database'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness of the database'],
@@ -1450,6 +1498,7 @@ public function create_database_mariadb(Request $request)
'image' => ['type' => 'string', 'description' => 'Docker Image of the database'],
'is_public' => ['type' => 'boolean', 'description' => 'Is the database public?'],
'public_port' => ['type' => 'integer', 'description' => 'Public port of the database'],
+ 'public_port_timeout' => ['type' => 'integer', 'description' => 'Public port timeout in seconds (default: 3600)'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit of the database'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit of the database'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness of the database'],
@@ -1517,6 +1566,7 @@ public function create_database_mysql(Request $request)
'image' => ['type' => 'string', 'description' => 'Docker Image of the database'],
'is_public' => ['type' => 'boolean', 'description' => 'Is the database public?'],
'public_port' => ['type' => 'integer', 'description' => 'Public port of the database'],
+ 'public_port_timeout' => ['type' => 'integer', 'description' => 'Public port timeout in seconds (default: 3600)'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit of the database'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit of the database'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness of the database'],
@@ -1555,7 +1605,7 @@ public function create_database_mongodb(Request $request)
public function create_database(Request $request, NewDatabaseTypes $type)
{
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf', 'clickhouse_admin_user', 'clickhouse_admin_password', 'dragonfly_password', 'redis_password', 'redis_conf', 'keydb_password', 'keydb_conf', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf', 'clickhouse_admin_user', 'clickhouse_admin_password', 'dragonfly_password', 'redis_password', 'redis_conf', 'keydb_password', 'keydb_conf', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
@@ -1566,7 +1616,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;
}
@@ -1645,6 +1695,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
'destination_uuid' => 'string',
'is_public' => 'boolean',
'public_port' => 'numeric|nullable',
+ 'public_port_timeout' => 'integer|nullable|min:1',
'limits_memory' => 'string',
'limits_memory_swap' => 'string',
'limits_memory_swappiness' => 'numeric',
@@ -1671,7 +1722,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
}
}
if ($type === NewDatabaseTypes::POSTGRESQL) {
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf'];
$validator = customApiValidator($request->all(), [
'postgres_user' => 'string',
'postgres_password' => 'string',
@@ -1715,7 +1766,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
}
$request->offsetSet('postgres_conf', $postgresConf);
}
- $database = create_standalone_postgresql($environment->id, $destination->uuid, $request->all());
+ $database = create_standalone_postgresql($environment->id, $destination->uuid, $request->only($allowedFields));
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
@@ -1730,7 +1781,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
} elseif ($type === NewDatabaseTypes::MARIADB) {
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database'];
$validator = customApiValidator($request->all(), [
'clickhouse_admin_user' => 'string',
'clickhouse_admin_password' => 'string',
@@ -1770,7 +1821,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
}
$request->offsetSet('mariadb_conf', $mariadbConf);
}
- $database = create_standalone_mariadb($environment->id, $destination->uuid, $request->all());
+ $database = create_standalone_mariadb($environment->id, $destination->uuid, $request->only($allowedFields));
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
@@ -1786,7 +1837,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
} elseif ($type === NewDatabaseTypes::MYSQL) {
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
$validator = customApiValidator($request->all(), [
'mysql_root_password' => 'string',
'mysql_password' => 'string',
@@ -1829,7 +1880,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
}
$request->offsetSet('mysql_conf', $mysqlConf);
}
- $database = create_standalone_mysql($environment->id, $destination->uuid, $request->all());
+ $database = create_standalone_mysql($environment->id, $destination->uuid, $request->only($allowedFields));
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
@@ -1845,7 +1896,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
} elseif ($type === NewDatabaseTypes::REDIS) {
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'redis_password', 'redis_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'redis_password', 'redis_conf'];
$validator = customApiValidator($request->all(), [
'redis_password' => 'string',
'redis_conf' => 'string',
@@ -1885,7 +1936,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
}
$request->offsetSet('redis_conf', $redisConf);
}
- $database = create_standalone_redis($environment->id, $destination->uuid, $request->all());
+ $database = create_standalone_redis($environment->id, $destination->uuid, $request->only($allowedFields));
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
@@ -1901,7 +1952,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
} elseif ($type === NewDatabaseTypes::DRAGONFLY) {
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'dragonfly_password'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'dragonfly_password'];
$validator = customApiValidator($request->all(), [
'dragonfly_password' => 'string',
]);
@@ -1922,7 +1973,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
}
removeUnnecessaryFieldsFromRequest($request);
- $database = create_standalone_dragonfly($environment->id, $destination->uuid, $request->all());
+ $database = create_standalone_dragonfly($environment->id, $destination->uuid, $request->only($allowedFields));
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
@@ -1931,7 +1982,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
'uuid' => $database->uuid,
]))->setStatusCode(201);
} elseif ($type === NewDatabaseTypes::KEYDB) {
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'keydb_password', 'keydb_conf'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'keydb_password', 'keydb_conf'];
$validator = customApiValidator($request->all(), [
'keydb_password' => 'string',
'keydb_conf' => 'string',
@@ -1971,7 +2022,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
}
$request->offsetSet('keydb_conf', $keydbConf);
}
- $database = create_standalone_keydb($environment->id, $destination->uuid, $request->all());
+ $database = create_standalone_keydb($environment->id, $destination->uuid, $request->only($allowedFields));
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
@@ -1987,7 +2038,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
} elseif ($type === NewDatabaseTypes::CLICKHOUSE) {
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'clickhouse_admin_user', 'clickhouse_admin_password'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'clickhouse_admin_user', 'clickhouse_admin_password'];
$validator = customApiValidator($request->all(), [
'clickhouse_admin_user' => 'string',
'clickhouse_admin_password' => 'string',
@@ -2007,7 +2058,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
], 422);
}
removeUnnecessaryFieldsFromRequest($request);
- $database = create_standalone_clickhouse($environment->id, $destination->uuid, $request->all());
+ $database = create_standalone_clickhouse($environment->id, $destination->uuid, $request->only($allowedFields));
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
@@ -2023,7 +2074,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
} elseif ($type === NewDatabaseTypes::MONGODB) {
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database'];
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'public_port_timeout', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database'];
$validator = customApiValidator($request->all(), [
'mongo_conf' => 'string',
'mongo_initdb_root_username' => 'string',
@@ -2065,7 +2116,7 @@ public function create_database(Request $request, NewDatabaseTypes $type)
}
$request->offsetSet('mongo_conf', $mongoConf);
}
- $database = create_standalone_mongodb($environment->id, $destination->uuid, $request->all());
+ $database = create_standalone_mongodb($environment->id, $destination->uuid, $request->only($allowedFields));
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
@@ -3443,7 +3494,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',
@@ -3530,6 +3581,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([
@@ -3622,7 +3676,7 @@ public function update_storage(Request $request): JsonResponse
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -3638,7 +3692,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/DeployController.php b/app/Http/Controllers/Api/DeployController.php
index 85d532f62..6ff06c10a 100644
--- a/app/Http/Controllers/Api/DeployController.php
+++ b/app/Http/Controllers/Api/DeployController.php
@@ -4,12 +4,15 @@
use App\Actions\Database\StartDatabase;
use App\Actions\Service\StartService;
+use App\Enums\ApplicationDeploymentStatus;
use App\Http\Controllers\Controller;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
+use App\Models\ApplicationPreview;
use App\Models\Server;
use App\Models\Service;
use App\Models\Tag;
+use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
use Visus\Cuid2\Cuid2;
@@ -228,8 +231,8 @@ public function cancel_deployment(Request $request)
// Check if deployment can be cancelled (must be queued or in_progress)
$cancellableStatuses = [
- \App\Enums\ApplicationDeploymentStatus::QUEUED->value,
- \App\Enums\ApplicationDeploymentStatus::IN_PROGRESS->value,
+ ApplicationDeploymentStatus::QUEUED->value,
+ ApplicationDeploymentStatus::IN_PROGRESS->value,
];
if (! in_array($deployment->status, $cancellableStatuses)) {
@@ -246,11 +249,11 @@ public function cancel_deployment(Request $request)
// Mark deployment as cancelled
$deployment->update([
- 'status' => \App\Enums\ApplicationDeploymentStatus::CANCELLED_BY_USER->value,
+ 'status' => ApplicationDeploymentStatus::CANCELLED_BY_USER->value,
]);
// Get the server
- $server = Server::find($build_server_id);
+ $server = Server::whereTeamId($teamId)->find($build_server_id);
if ($server) {
// Add cancellation log entry
@@ -304,6 +307,8 @@ public function cancel_deployment(Request $request)
new OA\Parameter(name: 'uuid', in: 'query', description: 'Resource UUID(s). Comma separated list is also accepted.', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'force', in: 'query', description: 'Force rebuild (without cache)', schema: new OA\Schema(type: 'boolean')),
new OA\Parameter(name: 'pr', in: 'query', description: 'Pull Request Id for deploying specific PR builds. Cannot be used with tag parameter.', schema: new OA\Schema(type: 'integer')),
+ new OA\Parameter(name: 'pull_request_id', in: 'query', description: 'Preview deployment identifier. Alias of pr.', schema: new OA\Schema(type: 'integer')),
+ new OA\Parameter(name: 'docker_tag', in: 'query', description: 'Docker image tag for Docker Image preview deployments. Requires pull_request_id.', schema: new OA\Schema(type: 'string')),
],
responses: [
@@ -354,7 +359,9 @@ public function deploy(Request $request)
$uuids = $request->input('uuid');
$tags = $request->input('tag');
$force = $request->input('force') ?? false;
- $pr = $request->input('pr') ? max((int) $request->input('pr'), 0) : 0;
+ $pullRequestId = $request->input('pull_request_id', $request->input('pr'));
+ $pr = $pullRequestId ? max((int) $pullRequestId, 0) : 0;
+ $dockerTag = $request->string('docker_tag')->trim()->value() ?: null;
if ($uuids && $tags) {
return response()->json(['message' => 'You can only use uuid or tag, not both.'], 400);
@@ -362,16 +369,22 @@ public function deploy(Request $request)
if ($tags && $pr) {
return response()->json(['message' => 'You can only use tag or pr, not both.'], 400);
}
+ if ($dockerTag && $pr === 0) {
+ return response()->json(['message' => 'docker_tag requires pull_request_id.'], 400);
+ }
+ if ($dockerTag && $tags) {
+ return response()->json(['message' => 'You can only use tag or docker_tag, not both.'], 400);
+ }
if ($tags) {
return $this->by_tags($tags, $teamId, $force);
} elseif ($uuids) {
- return $this->by_uuids($uuids, $teamId, $force, $pr);
+ return $this->by_uuids($uuids, $teamId, $force, $pr, $dockerTag);
}
return response()->json(['message' => 'You must provide uuid or tag.'], 400);
}
- private function by_uuids(string $uuid, int $teamId, bool $force = false, int $pr = 0)
+ private function by_uuids(string $uuid, int $teamId, bool $force = false, int $pr = 0, ?string $dockerTag = null)
{
$uuids = explode(',', $uuid);
$uuids = collect(array_filter($uuids));
@@ -384,15 +397,22 @@ private function by_uuids(string $uuid, int $teamId, bool $force = false, int $p
foreach ($uuids as $uuid) {
$resource = getResourceByUuid($uuid, $teamId);
if ($resource) {
+ $dockerTagForResource = $dockerTag;
if ($pr !== 0) {
- $preview = $resource->previews()->where('pull_request_id', $pr)->first();
+ $preview = null;
+ if ($resource instanceof Application && $resource->build_pack === 'dockerimage') {
+ $preview = $this->upsertDockerImagePreview($resource, $pr, $dockerTag);
+ $dockerTagForResource = $preview?->docker_registry_image_tag;
+ } else {
+ $preview = $resource->previews()->where('pull_request_id', $pr)->first();
+ }
if (! $preview) {
$deployments->push(['message' => "Pull request {$pr} not found for this resource.", 'resource_uuid' => $uuid]);
continue;
}
}
- $result = $this->deploy_resource($resource, $force, $pr);
+ $result = $this->deploy_resource($resource, $force, $pr, $dockerTagForResource);
if (isset($result['status']) && $result['status'] === 429) {
return response()->json(['message' => $result['message']], 429)->header('Retry-After', 60);
}
@@ -465,7 +485,7 @@ public function by_tags(string $tags, int $team_id, bool $force = false)
return response()->json(['message' => 'No resources found with this tag.'], 404);
}
- public function deploy_resource($resource, bool $force = false, int $pr = 0): array
+ public function deploy_resource($resource, bool $force = false, int $pr = 0, ?string $dockerTag = null): array
{
$message = null;
$deployment_uuid = null;
@@ -477,9 +497,12 @@ public function deploy_resource($resource, bool $force = false, int $pr = 0): ar
// Check authorization for application deployment
try {
$this->authorize('deploy', $resource);
- } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ } catch (AuthorizationException $e) {
return ['message' => 'Unauthorized to deploy this application.', 'deployment_uuid' => null];
}
+ if ($dockerTag !== null && $resource->build_pack !== 'dockerimage') {
+ return ['message' => 'docker_tag can only be used with Docker Image applications.', 'deployment_uuid' => null];
+ }
$deployment_uuid = new Cuid2;
$result = queue_application_deployment(
application: $resource,
@@ -487,6 +510,7 @@ public function deploy_resource($resource, bool $force = false, int $pr = 0): ar
force_rebuild: $force,
pull_request_id: $pr,
is_api: true,
+ docker_registry_image_tag: $dockerTag,
);
if ($result['status'] === 'queue_full') {
return ['message' => $result['message'], 'deployment_uuid' => null, 'status' => 429];
@@ -500,7 +524,7 @@ public function deploy_resource($resource, bool $force = false, int $pr = 0): ar
// Check authorization for service deployment
try {
$this->authorize('deploy', $resource);
- } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ } catch (AuthorizationException $e) {
return ['message' => 'Unauthorized to deploy this service.', 'deployment_uuid' => null];
}
StartService::run($resource);
@@ -510,7 +534,7 @@ public function deploy_resource($resource, bool $force = false, int $pr = 0): ar
// Database resource - check authorization
try {
$this->authorize('manage', $resource);
- } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ } catch (AuthorizationException $e) {
return ['message' => 'Unauthorized to start this database.', 'deployment_uuid' => null];
}
StartDatabase::dispatch($resource);
@@ -525,6 +549,34 @@ public function deploy_resource($resource, bool $force = false, int $pr = 0): ar
return ['message' => $message, 'deployment_uuid' => $deployment_uuid];
}
+ private function upsertDockerImagePreview(Application $application, int $pullRequestId, ?string $dockerTag): ?ApplicationPreview
+ {
+ $preview = $application->previews()->where('pull_request_id', $pullRequestId)->first();
+
+ if (! $preview && $dockerTag === null) {
+ return null;
+ }
+
+ if (! $preview) {
+ $preview = ApplicationPreview::create([
+ 'application_id' => $application->id,
+ 'pull_request_id' => $pullRequestId,
+ 'pull_request_html_url' => '',
+ 'docker_registry_image_tag' => $dockerTag,
+ ]);
+ $preview->generate_preview_fqdn();
+
+ return $preview;
+ }
+
+ if ($dockerTag !== null && $preview->docker_registry_image_tag !== $dockerTag) {
+ $preview->docker_registry_image_tag = $dockerTag;
+ $preview->save();
+ }
+
+ return $preview;
+ }
+
#[OA\Get(
summary: 'List application deployments',
description: 'List application deployments by using the app uuid',
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/Http/Controllers/Api/ProjectController.php b/app/Http/Controllers/Api/ProjectController.php
index da553a68c..ec2e300ff 100644
--- a/app/Http/Controllers/Api/ProjectController.php
+++ b/app/Http/Controllers/Api/ProjectController.php
@@ -5,6 +5,7 @@
use App\Http\Controllers\Controller;
use App\Models\Project;
use App\Support\ValidationPatterns;
+use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use OpenApi\Attributes as OA;
@@ -234,7 +235,7 @@ public function create_project(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$validator = Validator::make($request->all(), [
@@ -347,7 +348,7 @@ public function update_project(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$validator = Validator::make($request->all(), [
@@ -600,7 +601,7 @@ public function create_environment(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$validator = Validator::make($request->all(), [
diff --git a/app/Http/Controllers/Api/SecurityController.php b/app/Http/Controllers/Api/SecurityController.php
index e7b36cb9a..2c62928c2 100644
--- a/app/Http/Controllers/Api/SecurityController.php
+++ b/app/Http/Controllers/Api/SecurityController.php
@@ -4,6 +4,7 @@
use App\Http\Controllers\Controller;
use App\Models\PrivateKey;
+use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
@@ -176,7 +177,7 @@ public function create_key(Request $request)
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -300,7 +301,7 @@ public function update_key(Request $request)
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -330,7 +331,7 @@ public function update_key(Request $request)
'message' => 'Private Key not found.',
], 404);
}
- $foundKey->update($request->all());
+ $foundKey->update($request->only($allowedFields));
return response()->json(serializeApiResponse([
'uuid' => $foundKey->uuid,
diff --git a/app/Http/Controllers/Api/ServersController.php b/app/Http/Controllers/Api/ServersController.php
index da94521a8..c13c6665c 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,
]);
}
}
@@ -589,6 +598,11 @@ public function create_server(Request $request)
'is_build_server' => ['type' => 'boolean', 'description' => 'Is build server.'],
'instant_validate' => ['type' => 'boolean', 'description' => 'Instant validate.'],
'proxy_type' => ['type' => 'string', 'enum' => ['traefik', 'caddy', 'none'], 'description' => 'The proxy type.'],
+ 'concurrent_builds' => ['type' => 'integer', 'description' => 'Number of concurrent builds.'],
+ 'dynamic_timeout' => ['type' => 'integer', 'description' => 'Deployment timeout in seconds.'],
+ 'deployment_queue_limit' => ['type' => 'integer', 'description' => 'Maximum number of queued deployments.'],
+ 'server_disk_usage_notification_threshold' => ['type' => 'integer', 'description' => 'Server disk usage notification threshold (%).'],
+ 'server_disk_usage_check_frequency' => ['type' => 'string', 'description' => 'Cron expression for disk usage check frequency.'],
],
),
),
@@ -625,7 +639,7 @@ public function create_server(Request $request)
)]
public function update_server(Request $request)
{
- $allowedFields = ['name', 'description', 'ip', 'port', 'user', 'private_key_uuid', 'is_build_server', 'instant_validate', 'proxy_type'];
+ $allowedFields = ['name', 'description', 'ip', 'port', 'user', 'private_key_uuid', 'is_build_server', 'instant_validate', 'proxy_type', 'concurrent_builds', 'dynamic_timeout', 'deployment_queue_limit', 'server_disk_usage_notification_threshold', 'server_disk_usage_check_frequency'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
@@ -646,6 +660,11 @@ public function update_server(Request $request)
'is_build_server' => 'boolean|nullable',
'instant_validate' => 'boolean|nullable',
'proxy_type' => 'string|nullable',
+ 'concurrent_builds' => 'integer|min:1',
+ 'dynamic_timeout' => 'integer|min:1',
+ 'deployment_queue_limit' => 'integer|min:1',
+ 'server_disk_usage_notification_threshold' => 'integer|min:1|max:100',
+ 'server_disk_usage_check_frequency' => 'string',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
@@ -682,6 +701,19 @@ public function update_server(Request $request)
'is_build_server' => $request->is_build_server,
]);
}
+
+ if ($request->has('server_disk_usage_check_frequency') && ! validate_cron_expression($request->server_disk_usage_check_frequency)) {
+ return response()->json([
+ 'message' => 'Validation failed.',
+ 'errors' => ['server_disk_usage_check_frequency' => ['Invalid Cron / Human expression for Disk Usage Check Frequency.']],
+ ], 422);
+ }
+
+ $advancedSettings = $request->only(['concurrent_builds', 'dynamic_timeout', 'deployment_queue_limit', 'server_disk_usage_notification_threshold', 'server_disk_usage_check_frequency']);
+ if (! empty($advancedSettings)) {
+ $server->settings()->update(array_filter($advancedSettings, fn ($value) => ! is_null($value)));
+ }
+
if ($request->instant_validate) {
ValidateServer::dispatch($server);
}
diff --git a/app/Http/Controllers/Api/ServicesController.php b/app/Http/Controllers/Api/ServicesController.php
index ca565ece0..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;
@@ -302,7 +303,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 +926,7 @@ public function update_by_uuid(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof \Illuminate\Http\JsonResponse) {
+ if ($return instanceof JsonResponse) {
return $return;
}
@@ -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',
@@ -2110,6 +2111,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([
@@ -2221,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',
diff --git a/app/Http/Controllers/Api/TeamController.php b/app/Http/Controllers/Api/TeamController.php
index fd0282d96..03b36e4e0 100644
--- a/app/Http/Controllers/Api/TeamController.php
+++ b/app/Http/Controllers/Api/TeamController.php
@@ -14,14 +14,6 @@ private function removeSensitiveData($team)
'custom_server_limit',
'pivot',
]);
- if (request()->attributes->get('can_read_sensitive', false) === false) {
- $team->makeHidden([
- 'smtp_username',
- 'smtp_password',
- 'resend_api_key',
- 'telegram_token',
- ]);
- }
return serializeApiResponse($team);
}
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/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php
index 9d927d10c..d070cefc6 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;
@@ -75,6 +76,8 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
private ?string $dockerImageTag = null;
+ private ?string $dockerImagePreviewTag = null;
+
private GithubApp|GitlabApp|string $source = 'other';
private StandaloneDocker|SwarmDocker $destination;
@@ -207,6 +210,7 @@ public function __construct(public int $application_deployment_queue_id)
$this->restart_only = $this->application_deployment_queue->restart_only;
$this->restart_only = $this->restart_only && $this->application->build_pack !== 'dockerimage' && $this->application->build_pack !== 'dockerfile';
$this->only_this_server = $this->application_deployment_queue->only_this_server;
+ $this->dockerImagePreviewTag = $this->application_deployment_queue->docker_registry_image_tag;
$this->git_type = data_get($this->application_deployment_queue, 'git_type');
@@ -245,6 +249,9 @@ public function __construct(public int $application_deployment_queue_id)
// Set preview fqdn
if ($this->pull_request_id !== 0) {
$this->preview = ApplicationPreview::findPreviewByApplicationAndPullId($this->application->id, $this->pull_request_id);
+ if ($this->application->build_pack === 'dockerimage' && str($this->dockerImagePreviewTag)->isEmpty()) {
+ $this->dockerImagePreviewTag = $this->preview?->docker_registry_image_tag;
+ }
if ($this->preview) {
if ($this->application->build_pack === 'dockercompose') {
$this->preview->generate_preview_fqdn_compose();
@@ -287,7 +294,8 @@ public function handle(): void
// Make sure the private key is stored in the filesystem
$this->server->privateKey->storeInFileSystem();
// Generate custom host<->ip mapping
- $allContainers = instant_remote_process(["docker network inspect {$this->destination->network} -f '{{json .Containers}}' "], $this->server);
+ $safeNetwork = escapeshellarg($this->destination->network);
+ $allContainers = instant_remote_process(["docker network inspect {$safeNetwork} -f '{{json .Containers}}' "], $this->server);
if (! is_null($allContainers)) {
$allContainers = format_docker_command_output_to_json($allContainers);
@@ -317,7 +325,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 +459,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()}");
@@ -464,14 +472,14 @@ private function decide_what_to_do()
$this->just_restart();
return;
+ } elseif ($this->application->build_pack === 'dockerimage') {
+ $this->deploy_dockerimage_buildpack();
} elseif ($this->pull_request_id !== 0) {
$this->deploy_pull_request();
} elseif ($this->application->dockerfile) {
$this->deploy_simple_dockerfile();
} elseif ($this->application->build_pack === 'dockercompose') {
$this->deploy_docker_compose_buildpack();
- } elseif ($this->application->build_pack === 'dockerimage') {
- $this->deploy_dockerimage_buildpack();
} elseif ($this->application->build_pack === 'dockerfile') {
$this->deploy_dockerfile_buildpack();
} elseif ($this->application->build_pack === 'static') {
@@ -491,7 +499,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 +507,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 +515,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());
}
}
@@ -552,11 +560,7 @@ private function deploy_simple_dockerfile()
private function deploy_dockerimage_buildpack()
{
$this->dockerImage = $this->application->docker_registry_image_name;
- if (str($this->application->docker_registry_image_tag)->isEmpty()) {
- $this->dockerImageTag = 'latest';
- } else {
- $this->dockerImageTag = $this->application->docker_registry_image_tag;
- }
+ $this->dockerImageTag = $this->resolveDockerImageTag();
// Check if this is an image hash deployment
$isImageHash = str($this->dockerImageTag)->startsWith('sha256-');
@@ -573,6 +577,19 @@ private function deploy_dockerimage_buildpack()
$this->rolling_update();
}
+ private function resolveDockerImageTag(): string
+ {
+ if ($this->pull_request_id !== 0 && str($this->dockerImagePreviewTag)->isNotEmpty()) {
+ return $this->dockerImagePreviewTag;
+ }
+
+ if (str($this->application->docker_registry_image_tag)->isNotEmpty()) {
+ return $this->application->docker_registry_image_tag;
+ }
+
+ return 'latest';
+ }
+
private function deploy_docker_compose_buildpack()
{
if (data_get($this->application, 'docker_compose_location')) {
@@ -695,7 +712,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 +750,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.');
@@ -783,7 +800,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 +818,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 +835,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 +851,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();
}
@@ -1265,7 +1282,7 @@ private function generate_runtime_environment_variables()
});
foreach ($runtime_environment_variables as $env) {
- $envs->push($env->key.'='.$env->real_value);
+ $envs->push($env->key.'='.$env->getResolvedValueWithServer($this->mainServer));
}
// Check for PORT environment variable mismatch with ports_exposes
@@ -1331,8 +1348,24 @@ private function generate_runtime_environment_variables()
});
foreach ($runtime_environment_variables_preview as $env) {
- $envs->push($env->key.'='.$env->real_value);
+ $envs->push($env->key.'='.$env->getResolvedValueWithServer($this->mainServer));
}
+
+ // Fall back to production env vars for keys not overridden by preview vars,
+ // but only when preview vars are configured. This ensures variables like
+ // DB_PASSWORD that are only set for production will be available in the
+ // preview .env file (fixing ${VAR} interpolation in docker-compose YAML),
+ // while avoiding leaking production values when previews aren't 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->getResolvedValueWithServer($this->mainServer));
+ }
+ }
+
// Add PORT if not exists, use the first port as default
if ($this->build_pack !== 'dockercompose') {
if ($this->application->environment_variables_preview->where('key', 'PORT')->isEmpty()) {
@@ -1571,10 +1604,11 @@ private function generate_buildtime_environment_variables()
}
foreach ($sorted_environment_variables as $env) {
+ $resolvedValue = $env->getResolvedValueWithServer($this->mainServer);
// For literal/multiline vars, real_value includes quotes that we need to remove
if ($env->is_literal || $env->is_multiline) {
// Strip outer quotes from real_value and apply proper bash escaping
- $value = trim($env->real_value, "'");
+ $value = trim($resolvedValue, "'");
$escapedValue = escapeBashEnvValue($value);
if (isDev() && isset($envs_dict[$env->key])) {
@@ -1586,13 +1620,13 @@ private function generate_buildtime_environment_variables()
if (isDev()) {
$this->application_deployment_queue->addLogEntry("[DEBUG] Build-time env: {$env->key}");
$this->application_deployment_queue->addLogEntry('[DEBUG] Type: literal/multiline');
- $this->application_deployment_queue->addLogEntry("[DEBUG] raw real_value: {$env->real_value}");
+ $this->application_deployment_queue->addLogEntry("[DEBUG] raw real_value: {$resolvedValue}");
$this->application_deployment_queue->addLogEntry("[DEBUG] stripped value: {$value}");
$this->application_deployment_queue->addLogEntry("[DEBUG] final escaped: {$escapedValue}");
}
} else {
// For normal vars, use double quotes to allow $VAR expansion
- $escapedValue = escapeBashDoubleQuoted($env->real_value);
+ $escapedValue = escapeBashDoubleQuoted($resolvedValue);
if (isDev() && isset($envs_dict[$env->key])) {
$this->application_deployment_queue->addLogEntry("[DEBUG] User override: {$env->key} (was: {$envs_dict[$env->key]}, now: {$escapedValue})");
@@ -1603,7 +1637,7 @@ private function generate_buildtime_environment_variables()
if (isDev()) {
$this->application_deployment_queue->addLogEntry("[DEBUG] Build-time env: {$env->key}");
$this->application_deployment_queue->addLogEntry('[DEBUG] Type: normal (allows expansion)');
- $this->application_deployment_queue->addLogEntry("[DEBUG] real_value: {$env->real_value}");
+ $this->application_deployment_queue->addLogEntry("[DEBUG] real_value: {$resolvedValue}");
$this->application_deployment_queue->addLogEntry("[DEBUG] final escaped: {$escapedValue}");
}
}
@@ -1622,10 +1656,11 @@ private function generate_buildtime_environment_variables()
}
foreach ($sorted_environment_variables as $env) {
+ $resolvedValue = $env->getResolvedValueWithServer($this->mainServer);
// For literal/multiline vars, real_value includes quotes that we need to remove
if ($env->is_literal || $env->is_multiline) {
// Strip outer quotes from real_value and apply proper bash escaping
- $value = trim($env->real_value, "'");
+ $value = trim($resolvedValue, "'");
$escapedValue = escapeBashEnvValue($value);
if (isDev() && isset($envs_dict[$env->key])) {
@@ -1637,13 +1672,13 @@ private function generate_buildtime_environment_variables()
if (isDev()) {
$this->application_deployment_queue->addLogEntry("[DEBUG] Build-time env: {$env->key}");
$this->application_deployment_queue->addLogEntry('[DEBUG] Type: literal/multiline');
- $this->application_deployment_queue->addLogEntry("[DEBUG] raw real_value: {$env->real_value}");
+ $this->application_deployment_queue->addLogEntry("[DEBUG] raw real_value: {$resolvedValue}");
$this->application_deployment_queue->addLogEntry("[DEBUG] stripped value: {$value}");
$this->application_deployment_queue->addLogEntry("[DEBUG] final escaped: {$escapedValue}");
}
} else {
// For normal vars, use double quotes to allow $VAR expansion
- $escapedValue = escapeBashDoubleQuoted($env->real_value);
+ $escapedValue = escapeBashDoubleQuoted($resolvedValue);
if (isDev() && isset($envs_dict[$env->key])) {
$this->application_deployment_queue->addLogEntry("[DEBUG] User override: {$env->key} (was: {$envs_dict[$env->key]}, now: {$escapedValue})");
@@ -1654,7 +1689,7 @@ private function generate_buildtime_environment_variables()
if (isDev()) {
$this->application_deployment_queue->addLogEntry("[DEBUG] Build-time env: {$env->key}");
$this->application_deployment_queue->addLogEntry('[DEBUG] Type: normal (allows expansion)');
- $this->application_deployment_queue->addLogEntry("[DEBUG] real_value: {$env->real_value}");
+ $this->application_deployment_queue->addLogEntry("[DEBUG] real_value: {$resolvedValue}");
$this->application_deployment_queue->addLogEntry("[DEBUG] final escaped: {$escapedValue}");
}
}
@@ -1916,6 +1951,11 @@ private function query_logs()
private function deploy_pull_request()
{
+ if ($this->application->build_pack === 'dockerimage') {
+ $this->deploy_dockerimage_buildpack();
+
+ return;
+ }
if ($this->application->build_pack === 'dockercompose') {
$this->deploy_docker_compose_buildpack();
@@ -1998,9 +2038,11 @@ private function prepare_builder_image(bool $firstTry = true)
$runCommand = "docker run -d --name {$this->deployment_uuid} {$env_flags} --rm -v {$this->serverUserHomeDir}/.docker/config.json:/root/.docker/config.json:ro -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
} else {
if ($this->dockerConfigFileExists === 'OK') {
- $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} {$env_flags} --rm -v {$this->serverUserHomeDir}/.docker/config.json:/root/.docker/config.json:ro -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
+ $safeNetwork = escapeshellarg($this->destination->network);
+ $runCommand = "docker run -d --network {$safeNetwork} --name {$this->deployment_uuid} {$env_flags} --rm -v {$this->serverUserHomeDir}/.docker/config.json:/root/.docker/config.json:ro -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
} else {
- $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} {$env_flags} --rm -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
+ $safeNetwork = escapeshellarg($this->destination->network);
+ $runCommand = "docker run -d --network {$safeNetwork} --name {$this->deployment_uuid} {$env_flags} --rm -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
}
}
if ($firstTry) {
@@ -2112,7 +2154,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');
@@ -2352,15 +2394,17 @@ private function generate_nixpacks_env_variables()
$this->env_nixpacks_args = collect([]);
if ($this->pull_request_id === 0) {
foreach ($this->application->nixpacks_environment_variables as $env) {
- if (! is_null($env->real_value) && $env->real_value !== '') {
- $value = ($env->is_literal || $env->is_multiline) ? trim($env->real_value, "'") : $env->real_value;
+ $resolvedValue = $env->getResolvedValueWithServer($this->mainServer);
+ if (! is_null($resolvedValue) && $resolvedValue !== '') {
+ $value = ($env->is_literal || $env->is_multiline) ? trim($resolvedValue, "'") : $resolvedValue;
$this->env_nixpacks_args->push('--env '.escapeShellValue("{$env->key}={$value}"));
}
}
} else {
foreach ($this->application->nixpacks_environment_variables_preview as $env) {
- if (! is_null($env->real_value) && $env->real_value !== '') {
- $value = ($env->is_literal || $env->is_multiline) ? trim($env->real_value, "'") : $env->real_value;
+ $resolvedValue = $env->getResolvedValueWithServer($this->mainServer);
+ if (! is_null($resolvedValue) && $resolvedValue !== '') {
+ $value = ($env->is_literal || $env->is_multiline) ? trim($resolvedValue, "'") : $resolvedValue;
$this->env_nixpacks_args->push('--env '.escapeShellValue("{$env->key}={$value}"));
}
}
@@ -2499,8 +2543,9 @@ private function generate_env_variables()
->get();
foreach ($envs as $env) {
- if (! is_null($env->real_value)) {
- $this->env_args->put($env->key, $env->real_value);
+ $resolvedValue = $env->getResolvedValueWithServer($this->mainServer);
+ if (! is_null($resolvedValue)) {
+ $this->env_args->put($env->key, $resolvedValue);
}
}
} else {
@@ -2510,8 +2555,9 @@ private function generate_env_variables()
->get();
foreach ($envs as $env) {
- if (! is_null($env->real_value)) {
- $this->env_args->put($env->key, $env->real_value);
+ $resolvedValue = $env->getResolvedValueWithServer($this->mainServer);
+ if (! is_null($resolvedValue)) {
+ $this->env_args->put($env->key, $resolvedValue);
}
}
}
@@ -2948,7 +2994,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;
@@ -3029,28 +3075,29 @@ private function build_image()
$this->execute_remote_command([executeInDocker($this->deployment_uuid, 'rm '.self::NIXPACKS_PLAN_PATH), 'hidden' => true]);
} else {
// Dockerfile buildpack
+ $safeNetwork = escapeshellarg($this->destination->network);
if ($this->dockerSecretsSupported) {
// Modify the Dockerfile to use build secrets
$this->modify_dockerfile_for_secrets("{$this->workdir}{$this->dockerfile_location}");
$secrets_flags = $this->build_secrets ? " {$this->build_secrets}" : '';
if ($this->force_rebuild) {
- $build_command = $this->wrap_build_command_with_env_export("DOCKER_BUILDKIT=1 docker build --no-cache {$this->buildTarget} --network {$this->destination->network} -f {$this->workdir}{$this->dockerfile_location}{$secrets_flags} --progress plain -t $this->build_image_name {$this->workdir}");
+ $build_command = $this->wrap_build_command_with_env_export("DOCKER_BUILDKIT=1 docker build --no-cache {$this->buildTarget} --network {$safeNetwork} -f {$this->workdir}{$this->dockerfile_location}{$secrets_flags} --progress plain -t $this->build_image_name {$this->workdir}");
} else {
- $build_command = $this->wrap_build_command_with_env_export("DOCKER_BUILDKIT=1 docker build {$this->buildTarget} --network {$this->destination->network} -f {$this->workdir}{$this->dockerfile_location}{$secrets_flags} --progress plain -t $this->build_image_name {$this->workdir}");
+ $build_command = $this->wrap_build_command_with_env_export("DOCKER_BUILDKIT=1 docker build {$this->buildTarget} --network {$safeNetwork} -f {$this->workdir}{$this->dockerfile_location}{$secrets_flags} --progress plain -t $this->build_image_name {$this->workdir}");
}
} elseif ($this->dockerBuildkitSupported) {
// BuildKit without secrets
if ($this->force_rebuild) {
- $build_command = $this->wrap_build_command_with_env_export("DOCKER_BUILDKIT=1 docker build --no-cache {$this->buildTarget} --network {$this->destination->network} -f {$this->workdir}{$this->dockerfile_location} --progress plain -t $this->build_image_name {$this->build_args} {$this->workdir}");
+ $build_command = $this->wrap_build_command_with_env_export("DOCKER_BUILDKIT=1 docker build --no-cache {$this->buildTarget} --network {$safeNetwork} -f {$this->workdir}{$this->dockerfile_location} --progress plain -t $this->build_image_name {$this->build_args} {$this->workdir}");
} else {
- $build_command = $this->wrap_build_command_with_env_export("DOCKER_BUILDKIT=1 docker build {$this->buildTarget} --network {$this->destination->network} -f {$this->workdir}{$this->dockerfile_location} --progress plain -t $this->build_image_name {$this->build_args} {$this->workdir}");
+ $build_command = $this->wrap_build_command_with_env_export("DOCKER_BUILDKIT=1 docker build {$this->buildTarget} --network {$safeNetwork} -f {$this->workdir}{$this->dockerfile_location} --progress plain -t $this->build_image_name {$this->build_args} {$this->workdir}");
}
} else {
// Traditional build with args
if ($this->force_rebuild) {
- $build_command = $this->wrap_build_command_with_env_export("docker build --no-cache {$this->buildTarget} --network {$this->destination->network} -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} -t $this->build_image_name {$this->workdir}");
+ $build_command = $this->wrap_build_command_with_env_export("docker build --no-cache {$this->buildTarget} --network {$safeNetwork} -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} -t $this->build_image_name {$this->workdir}");
} else {
- $build_command = $this->wrap_build_command_with_env_export("docker build {$this->buildTarget} --network {$this->destination->network} -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} -t $this->build_image_name {$this->workdir}");
+ $build_command = $this->wrap_build_command_with_env_export("docker build {$this->buildTarget} --network {$safeNetwork} -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} -t $this->build_image_name {$this->workdir}");
}
}
$base64_build_command = base64_encode($build_command);
@@ -3525,7 +3572,7 @@ private function generate_secrets_hash($variables)
} else {
$secrets_string = $variables
->map(function ($env) {
- return "{$env->key}={$env->real_value}";
+ return "{$env->key}={$env->getResolvedValueWithServer($this->mainServer)}";
})
->sort()
->implode('|');
@@ -3591,7 +3638,7 @@ private function add_build_env_variables_to_dockerfile()
if (data_get($env, 'is_multiline') === true) {
$argsToInsert->push("ARG {$env->key}");
} else {
- $argsToInsert->push("ARG {$env->key}={$env->real_value}");
+ $argsToInsert->push("ARG {$env->key}={$env->getResolvedValueWithServer($this->mainServer)}");
}
}
// Add Coolify variables as ARGs
@@ -3613,7 +3660,7 @@ private function add_build_env_variables_to_dockerfile()
if (data_get($env, 'is_multiline') === true) {
$argsToInsert->push("ARG {$env->key}");
} else {
- $argsToInsert->push("ARG {$env->key}={$env->real_value}");
+ $argsToInsert->push("ARG {$env->key}={$env->getResolvedValueWithServer($this->mainServer)}");
}
}
// Add Coolify variables as ARGs
@@ -3649,7 +3696,7 @@ private function add_build_env_variables_to_dockerfile()
}
}
$envs_mapped = $envs->mapWithKeys(function ($env) {
- return [$env->key => $env->real_value];
+ return [$env->key => $env->getResolvedValueWithServer($this->mainServer)];
});
$secrets_hash = $this->generate_secrets_hash($envs_mapped);
$argsToInsert->push("ARG COOLIFY_BUILD_SECRETS_HASH={$secrets_hash}");
@@ -3949,7 +3996,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);
@@ -3961,7 +4008,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, '..')) {
@@ -3973,7 +4020,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.");
}
@@ -3982,13 +4029,58 @@ 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.');
}
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 +4088,39 @@ 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().
+ // 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(
+ [
+ 'command' => $exec,
+ 'hidden' => true,
+ ],
+ );
}
private function run_post_deployment_command()
@@ -4037,36 +4132,42 @@ 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.
+ // 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(
+ [
+ '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/app/Jobs/CleanupInstanceStuffsJob.php b/app/Jobs/CleanupInstanceStuffsJob.php
index 011c58639..e37a39c3d 100644
--- a/app/Jobs/CleanupInstanceStuffsJob.php
+++ b/app/Jobs/CleanupInstanceStuffsJob.php
@@ -2,6 +2,7 @@
namespace App\Jobs;
+use App\Models\ScheduledDatabaseBackup;
use App\Models\TeamInvitation;
use App\Models\User;
use Illuminate\Bus\Queueable;
@@ -12,6 +13,7 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
+use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class CleanupInstanceStuffsJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue
@@ -32,6 +34,7 @@ public function handle(): void
try {
$this->cleanupInvitationLink();
$this->cleanupExpiredEmailChangeRequests();
+ $this->enforceBackupRetention();
} catch (\Throwable $e) {
Log::error('CleanupInstanceStuffsJob failed with error: '.$e->getMessage());
}
@@ -55,4 +58,25 @@ private function cleanupExpiredEmailChangeRequests()
'email_change_code_expires_at' => null,
]);
}
+
+ private function enforceBackupRetention(): void
+ {
+ if (! Cache::add('backup-retention-enforcement', true, 1800)) {
+ return;
+ }
+
+ try {
+ $backups = ScheduledDatabaseBackup::where('enabled', true)->get();
+ foreach ($backups as $backup) {
+ try {
+ removeOldBackups($backup);
+ } catch (\Throwable $e) {
+ Log::warning('Failed to enforce retention for backup '.$backup->id.': '.$e->getMessage());
+ }
+ }
+ } catch (\Throwable $e) {
+ Log::error('Failed to enforce backup retention: '.$e->getMessage());
+ Cache::forget('backup-retention-enforcement');
+ }
+ }
}
diff --git a/app/Jobs/DatabaseBackupJob.php b/app/Jobs/DatabaseBackupJob.php
index b55c324be..207191cbd 100644
--- a/app/Jobs/DatabaseBackupJob.php
+++ b/app/Jobs/DatabaseBackupJob.php
@@ -22,6 +22,7 @@
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
@@ -80,6 +81,13 @@ public function __construct(public ScheduledDatabaseBackup $backup)
$this->timeout = $backup->timeout ?? 3600;
}
+ public function middleware(): array
+ {
+ $expireAfter = ($this->backup->timeout ?? 3600) + 300;
+
+ return [(new WithoutOverlapping('database-backup-'.$this->backup->id))->expireAfter($expireAfter)->dontRelease()];
+ }
+
public function handle(): void
{
try {
@@ -91,7 +99,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;
@@ -107,6 +115,8 @@ public function handle(): void
throw new \Exception('Database not found?!');
}
+ $this->markStaleExecutionsAsFailed();
+
BackupCreated::dispatch($this->team->id);
$status = str(data_get($this->database, 'status'));
@@ -119,7 +129,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 +251,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 +398,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([
@@ -399,7 +409,15 @@ public function handle(): void
's3_uploaded' => null,
]);
}
- $this->team?->notify(new BackupFailed($this->backup, $this->database, $this->error_output ?? $this->backup_output ?? $e->getMessage(), $database));
+ try {
+ $this->team?->notify(new BackupFailed($this->backup, $this->database, $this->error_output ?? $this->backup_output ?? $e->getMessage(), $database));
+ } catch (Throwable $notifyException) {
+ Log::channel('scheduled-errors')->warning('Failed to send backup failure notification', [
+ 'backup_id' => $this->backup->uuid,
+ 'database' => $database,
+ 'error' => $notifyException->getMessage(),
+ ]);
+ }
continue;
}
@@ -415,7 +433,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();
}
@@ -439,18 +457,27 @@ public function handle(): void
'local_storage_deleted' => $localStorageDeleted,
]);
- // Send appropriate notification
- if ($s3UploadError) {
- $this->team->notify(new BackupSuccessWithS3Warning($this->backup, $this->database, $database, $s3UploadError));
- } else {
- $this->team->notify(new BackupSuccess($this->backup, $this->database, $database));
+ // Send appropriate notification (wrapped in try-catch so notification
+ // failures never affect backup status — see GitHub issue #9088)
+ try {
+ if ($s3UploadError) {
+ $this->team->notify(new BackupSuccessWithS3Warning($this->backup, $this->database, $database, $s3UploadError));
+ } else {
+ $this->team->notify(new BackupSuccess($this->backup, $this->database, $database));
+ }
+ } catch (Throwable $e) {
+ Log::channel('scheduled-errors')->warning('Failed to send backup success notification', [
+ 'backup_id' => $this->backup->uuid,
+ 'database' => $database,
+ 'error' => $e->getMessage(),
+ ]);
}
}
}
if ($this->backup_log && $this->backup_log->status === 'success') {
removeOldBackups($this->backup);
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
throw $e;
} finally {
if ($this->team) {
@@ -472,19 +499,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(':')) {
@@ -502,15 +533,23 @@ 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
+ $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=$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 ".$collectionsToExclude->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";
}
}
}
@@ -519,7 +558,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;
}
@@ -531,15 +570,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;
@@ -548,7 +588,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;
}
@@ -558,20 +598,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;
}
@@ -581,20 +622,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;
}
@@ -641,11 +683,12 @@ 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;
}
+ $safeNetwork = escapeshellarg($network);
$fullImageName = $this->getFullImageName();
@@ -657,13 +700,13 @@ private function upload_to_s3(): void
if (isDev()) {
if ($this->database->name === 'coolify-db') {
$backup_location_from = '/var/lib/docker/volumes/coolify_dev_backups_data/_data/coolify/coolify-db-'.$this->server->ip.$this->backup_file;
- $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup_log_uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";
+ $commands[] = "docker run -d --network {$safeNetwork} --name backup-of-{$this->backup_log_uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";
} else {
$backup_location_from = '/var/lib/docker/volumes/coolify_dev_backups_data/_data/databases/'.str($this->team->name)->slug().'-'.$this->team->id.'/'.$this->directory_name.$this->backup_file;
- $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup_log_uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";
+ $commands[] = "docker run -d --network {$safeNetwork} --name backup-of-{$this->backup_log_uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";
}
} else {
- $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup_log_uuid} --rm -v $this->backup_location:$this->backup_location:ro {$fullImageName}";
+ $commands[] = "docker run -d --network {$safeNetwork} --name backup-of-{$this->backup_log_uuid} --rm -v $this->backup_location:$this->backup_location:ro {$fullImageName}";
}
// Escape S3 credentials to prevent command injection
@@ -676,7 +719,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;
@@ -694,6 +737,31 @@ private function getFullImageName(): string
return "{$helperImage}:{$latestVersion}";
}
+ private function markStaleExecutionsAsFailed(): void
+ {
+ try {
+ $timeoutSeconds = ($this->backup->timeout ?? 3600) * 2;
+
+ $staleExecutions = $this->backup->executions()
+ ->where('status', 'running')
+ ->where('created_at', '<', now()->subSeconds($timeoutSeconds))
+ ->get();
+
+ foreach ($staleExecutions as $execution) {
+ $execution->update([
+ 'status' => 'failed',
+ 'message' => 'Marked as failed - backup execution exceeded maximum allowed time',
+ 'finished_at' => now(),
+ ]);
+ }
+ } catch (Throwable $e) {
+ Log::channel('scheduled-errors')->warning('Failed to clean up stale backup executions', [
+ 'backup_id' => $this->backup->uuid,
+ 'error' => $e->getMessage(),
+ ]);
+ }
+ }
+
public function failed(?Throwable $exception): void
{
Log::channel('scheduled-errors')->error('DatabaseBackup permanently failed', [
@@ -710,20 +778,32 @@ public function failed(?Throwable $exception): void
$log = ScheduledDatabaseBackupExecution::where('uuid', $this->backup_log_uuid)->first();
if ($log) {
- $log->update([
- 'status' => 'failed',
- 'message' => 'Job permanently failed after '.$this->attempts().' attempts: '.($exception?->getMessage() ?? 'Unknown error'),
- 'size' => 0,
- 'filename' => null,
- 'finished_at' => Carbon::now(),
- ]);
+ // Don't overwrite a successful backup status — a post-backup error
+ // (e.g. notification failure) should not retroactively mark the backup
+ // as failed (see GitHub issue #9088)
+ if ($log->status !== 'success') {
+ $log->update([
+ 'status' => 'failed',
+ 'message' => 'Job permanently failed after '.$this->attempts().' attempts: '.($exception?->getMessage() ?? 'Unknown error'),
+ 'size' => 0,
+ 'filename' => null,
+ 'finished_at' => Carbon::now(),
+ ]);
+ }
}
- // Notify team about permanent failure
- if ($this->team) {
+ // Notify team about permanent failure (only if backup didn't already succeed)
+ if ($this->team && $log?->status !== 'success') {
$databaseName = $log?->database_name ?? 'unknown';
$output = $this->backup_output ?? $exception?->getMessage() ?? 'Unknown error';
- $this->team->notify(new BackupFailed($this->backup, $this->database, $output, $databaseName));
+ try {
+ $this->team->notify(new BackupFailed($this->backup, $this->database, $output, $databaseName));
+ } 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/app/Jobs/SendWebhookJob.php b/app/Jobs/SendWebhookJob.php
index 607fda3fe..9d2a94606 100644
--- a/app/Jobs/SendWebhookJob.php
+++ b/app/Jobs/SendWebhookJob.php
@@ -9,6 +9,8 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Validator;
class SendWebhookJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -40,6 +42,20 @@ public function __construct(
*/
public function handle(): void
{
+ $validator = Validator::make(
+ ['webhook_url' => $this->webhookUrl],
+ ['webhook_url' => ['required', 'url', new \App\Rules\SafeWebhookUrl]]
+ );
+
+ if ($validator->fails()) {
+ Log::warning('SendWebhookJob: blocked unsafe webhook URL', [
+ 'url' => $this->webhookUrl,
+ 'errors' => $validator->errors()->all(),
+ ]);
+
+ return;
+ }
+
if (isDev()) {
ray('Sending webhook notification', [
'url' => $this->webhookUrl,
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/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/ActivityMonitor.php b/app/Livewire/ActivityMonitor.php
index 370ff1eaa..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';
@@ -55,16 +58,49 @@ public function hydrateActivity()
return;
}
- $this->activity = Activity::find($this->activityId);
- }
+ $activity = Activity::find($this->activityId);
- public function updatedActivityId($value)
- {
- if ($value) {
- $this->hydrateActivity();
- $this->isPollingActive = true;
- self::$eventDispatched = false;
+ 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;
+ }
+ }
+
+ // Fail closed: no team_id and no server_uuid means we cannot verify ownership
+ $this->activity = null;
}
public function polling()
diff --git a/app/Livewire/Admin/Index.php b/app/Livewire/Admin/Index.php
index b5f6d2929..d1345e7bf 100644
--- a/app/Livewire/Admin/Index.php
+++ b/app/Livewire/Admin/Index.php
@@ -6,7 +6,6 @@
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
-use Illuminate\Support\Facades\Cache;
use Livewire\Component;
class Index extends Component
@@ -22,16 +21,15 @@ class Index extends Component
public function mount()
{
if (! isCloud() && ! isDev()) {
- return redirect()->route('dashboard');
- }
- if (Auth::id() !== 0 && ! session('impersonating')) {
- return redirect()->route('dashboard');
+ abort(403);
}
+ $this->authorizeAdminAccess();
$this->getSubscribers();
}
public function back()
{
+ $this->authorizeAdminAccess();
if (session('impersonating')) {
session()->forget('impersonating');
$user = User::find(0);
@@ -45,6 +43,7 @@ public function back()
public function submitSearch()
{
+ $this->authorizeAdminAccess();
if ($this->search !== '') {
$this->foundUsers = User::where(function ($query) {
$query->where('name', 'like', "%{$this->search}%")
@@ -61,19 +60,33 @@ public function getSubscribers()
public function switchUser(int $user_id)
{
- if (Auth::id() !== 0) {
- return redirect()->route('dashboard');
- }
+ $this->authorizeRootOnly();
session(['impersonating' => true]);
$user = User::find($user_id);
+ if (! $user) {
+ abort(404);
+ }
$team_to_switch_to = $user->teams->first();
- // Cache::forget("team:{$user->id}");
Auth::login($user);
refreshSession($team_to_switch_to);
return redirect(request()->header('Referer'));
}
+ private function authorizeAdminAccess(): void
+ {
+ if (! Auth::check() || (Auth::id() !== 0 && ! session('impersonating'))) {
+ abort(403);
+ }
+ }
+
+ private function authorizeRootOnly(): void
+ {
+ if (! Auth::check() || Auth::id() !== 0) {
+ abort(403);
+ }
+ }
+
public function render()
{
return view('livewire.admin.index');
diff --git a/app/Livewire/Boarding/Index.php b/app/Livewire/Boarding/Index.php
index 0f6f45d83..33c75bf70 100644
--- a/app/Livewire/Boarding/Index.php
+++ b/app/Livewire/Boarding/Index.php
@@ -9,6 +9,7 @@
use App\Models\Team;
use App\Services\ConfigurationRepository;
use Illuminate\Support\Collection;
+use Livewire\Attributes\Url;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
@@ -19,18 +20,18 @@ class Index extends Component
'prerequisitesInstalled' => 'handlePrerequisitesInstalled',
];
- #[\Livewire\Attributes\Url(as: 'step', history: true)]
+ #[Url(as: 'step', history: true)]
public string $currentState = 'welcome';
- #[\Livewire\Attributes\Url(keep: true)]
+ #[Url(keep: true)]
public ?string $selectedServerType = null;
public ?Collection $privateKeys = null;
- #[\Livewire\Attributes\Url(keep: true)]
+ #[Url(keep: true)]
public ?int $selectedExistingPrivateKey = null;
- #[\Livewire\Attributes\Url(keep: true)]
+ #[Url(keep: true)]
public ?string $privateKeyType = null;
public ?string $privateKey = null;
@@ -45,7 +46,7 @@ class Index extends Component
public ?Collection $servers = null;
- #[\Livewire\Attributes\Url(keep: true)]
+ #[Url(keep: true)]
public ?int $selectedExistingServer = null;
public ?string $remoteServerName = null;
@@ -66,7 +67,7 @@ class Index extends Component
public Collection $projects;
- #[\Livewire\Attributes\Url(keep: true)]
+ #[Url(keep: true)]
public ?int $selectedProject = null;
public ?Project $createdProject = null;
@@ -121,7 +122,7 @@ public function mount()
}
if ($this->selectedExistingServer) {
- $this->createdServer = Server::find($this->selectedExistingServer);
+ $this->createdServer = Server::ownedByCurrentTeam()->find($this->selectedExistingServer);
if ($this->createdServer) {
$this->serverPublicKey = $this->createdServer->privateKey->getPublicKey();
$this->updateServerDetails();
@@ -145,7 +146,7 @@ public function mount()
}
if ($this->selectedProject) {
- $this->createdProject = Project::find($this->selectedProject);
+ $this->createdProject = Project::ownedByCurrentTeam()->find($this->selectedProject);
if (! $this->createdProject) {
$this->projects = Project::ownedByCurrentTeam(['name'])->get();
}
@@ -431,7 +432,10 @@ public function getProjects()
public function selectExistingProject()
{
- $this->createdProject = Project::find($this->selectedProject);
+ $this->createdProject = Project::ownedByCurrentTeam()->find($this->selectedProject);
+ if (! $this->createdProject) {
+ return $this->dispatch('error', 'Project not found.');
+ }
$this->currentState = 'create-resource';
}
diff --git a/app/Livewire/Destination/New/Docker.php b/app/Livewire/Destination/New/Docker.php
index 70751fa03..6f9b6f995 100644
--- a/app/Livewire/Destination/New/Docker.php
+++ b/app/Livewire/Destination/New/Docker.php
@@ -24,7 +24,7 @@ class Docker extends Component
#[Validate(['required', 'string'])]
public string $name;
- #[Validate(['required', 'string'])]
+ #[Validate(['required', 'string', 'max:255', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/'])]
public string $network;
#[Validate(['required', 'string'])]
diff --git a/app/Livewire/Destination/Show.php b/app/Livewire/Destination/Show.php
index 98cf72376..f2cdad074 100644
--- a/app/Livewire/Destination/Show.php
+++ b/app/Livewire/Destination/Show.php
@@ -20,7 +20,7 @@ class Show extends Component
#[Validate(['string', 'required'])]
public string $name;
- #[Validate(['string', 'required'])]
+ #[Validate(['string', 'required', 'max:255', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/'])]
public string $network;
#[Validate(['string', 'required'])]
@@ -84,8 +84,9 @@ public function delete()
if ($this->destination->attachedTo()) {
return $this->dispatch('error', 'You must delete all resources before deleting this destination.');
}
- instant_remote_process(["docker network disconnect {$this->destination->network} coolify-proxy"], $this->destination->server, throwError: false);
- instant_remote_process(['docker network rm -f '.$this->destination->network], $this->destination->server);
+ $safeNetwork = escapeshellarg($this->destination->network);
+ instant_remote_process(["docker network disconnect {$safeNetwork} coolify-proxy"], $this->destination->server, throwError: false);
+ instant_remote_process(["docker network rm -f {$safeNetwork}"], $this->destination->server);
}
$this->destination->delete();
diff --git a/app/Livewire/ForcePasswordReset.php b/app/Livewire/ForcePasswordReset.php
index 61a2a20e9..e6392497f 100644
--- a/app/Livewire/ForcePasswordReset.php
+++ b/app/Livewire/ForcePasswordReset.php
@@ -48,7 +48,7 @@ public function submit()
$this->rateLimit(10);
$this->validate();
$firstLogin = auth()->user()->created_at == auth()->user()->updated_at;
- auth()->user()->forceFill([
+ auth()->user()->fill([
'password' => Hash::make($this->password),
'force_password_reset' => false,
])->save();
diff --git a/app/Livewire/GlobalSearch.php b/app/Livewire/GlobalSearch.php
index f910110dc..154748b47 100644
--- a/app/Livewire/GlobalSearch.php
+++ b/app/Livewire/GlobalSearch.php
@@ -1203,7 +1203,7 @@ public function selectServer($serverId, $shouldProgress = true)
public function loadDestinations()
{
$this->loadingDestinations = true;
- $server = Server::find($this->selectedServerId);
+ $server = Server::ownedByCurrentTeam()->find($this->selectedServerId);
if (! $server) {
$this->loadingDestinations = false;
@@ -1280,7 +1280,7 @@ public function selectProject($projectUuid, $shouldProgress = true)
public function loadEnvironments()
{
$this->loadingEnvironments = true;
- $project = Project::where('uuid', $this->selectedProjectUuid)->first();
+ $project = Project::ownedByCurrentTeam()->where('uuid', $this->selectedProjectUuid)->first();
if (! $project) {
$this->loadingEnvironments = false;
diff --git a/app/Livewire/Notifications/Discord.php b/app/Livewire/Notifications/Discord.php
index b914fbd94..ab3884320 100644
--- a/app/Livewire/Notifications/Discord.php
+++ b/app/Livewire/Notifications/Discord.php
@@ -5,6 +5,7 @@
use App\Models\DiscordNotificationSettings;
use App\Models\Team;
use App\Notifications\Test;
+use App\Rules\SafeWebhookUrl;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Validate;
use Livewire\Component;
@@ -20,7 +21,7 @@ class Discord extends Component
#[Validate(['boolean'])]
public bool $discordEnabled = false;
- #[Validate(['url', 'nullable'])]
+ #[Validate(['nullable', new SafeWebhookUrl])]
public ?string $discordWebhookUrl = null;
#[Validate(['boolean'])]
diff --git a/app/Livewire/Notifications/Email.php b/app/Livewire/Notifications/Email.php
index 847f10765..364163ff8 100644
--- a/app/Livewire/Notifications/Email.php
+++ b/app/Livewire/Notifications/Email.php
@@ -42,7 +42,7 @@ class Email extends Component
public ?string $smtpHost = null;
#[Validate(['nullable', 'numeric', 'min:1', 'max:65535'])]
- public ?int $smtpPort = null;
+ public ?string $smtpPort = null;
#[Validate(['nullable', 'string', 'in:starttls,tls,none'])]
public ?string $smtpEncryption = null;
@@ -54,7 +54,7 @@ class Email extends Component
public ?string $smtpPassword = null;
#[Validate(['nullable', 'numeric'])]
- public ?int $smtpTimeout = null;
+ public ?string $smtpTimeout = null;
#[Validate(['boolean'])]
public bool $resendEnabled = false;
diff --git a/app/Livewire/Notifications/Slack.php b/app/Livewire/Notifications/Slack.php
index fa8c97ae9..f870b3986 100644
--- a/app/Livewire/Notifications/Slack.php
+++ b/app/Livewire/Notifications/Slack.php
@@ -5,6 +5,7 @@
use App\Models\SlackNotificationSettings;
use App\Models\Team;
use App\Notifications\Test;
+use App\Rules\SafeWebhookUrl;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
@@ -25,7 +26,7 @@ class Slack extends Component
#[Validate(['boolean'])]
public bool $slackEnabled = false;
- #[Validate(['url', 'nullable'])]
+ #[Validate(['nullable', new SafeWebhookUrl])]
public ?string $slackWebhookUrl = null;
#[Validate(['boolean'])]
diff --git a/app/Livewire/Notifications/Webhook.php b/app/Livewire/Notifications/Webhook.php
index 8af70c6eb..630d422a9 100644
--- a/app/Livewire/Notifications/Webhook.php
+++ b/app/Livewire/Notifications/Webhook.php
@@ -5,6 +5,7 @@
use App\Models\Team;
use App\Models\WebhookNotificationSettings;
use App\Notifications\Test;
+use App\Rules\SafeWebhookUrl;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Validate;
use Livewire\Component;
@@ -20,7 +21,7 @@ class Webhook extends Component
#[Validate(['boolean'])]
public bool $webhookEnabled = false;
- #[Validate(['url', 'nullable'])]
+ #[Validate(['nullable', new SafeWebhookUrl])]
public ?string $webhookUrl = null;
#[Validate(['boolean'])]
diff --git a/app/Livewire/Project/Application/General.php b/app/Livewire/Project/Application/General.php
index ca1daef72..25ce82eb0 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;
@@ -143,15 +146,15 @@ protected function rules(): array
'gitRepository' => 'required',
'gitBranch' => 'required',
'gitCommitSha' => ['nullable', 'string', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9._\-\/]*$/'],
- 'installCommand' => 'nullable',
- 'buildCommand' => 'nullable',
- 'startCommand' => 'nullable',
+ 'installCommand' => ValidationPatterns::shellSafeCommandRules(),
+ 'buildCommand' => ValidationPatterns::shellSafeCommandRules(),
+ 'startCommand' => ValidationPatterns::shellSafeCommandRules(),
'buildPack' => 'required',
'staticImage' => 'required',
'baseDirectory' => array_merge(['required'], array_slice(ValidationPatterns::directoryPathRules(), 1)),
'publishDirectory' => ValidationPatterns::directoryPathRules(),
- 'portsExposes' => 'required',
- 'portsMappings' => 'nullable',
+ 'portsExposes' => ['required', 'string', 'regex:/^(\d+)(,\d+)*$/'],
+ 'portsMappings' => ValidationPatterns::portMappingRules(),
'customNetworkAliases' => 'nullable',
'dockerfile' => 'nullable',
'dockerRegistryImageName' => 'nullable',
@@ -194,9 +197,12 @@ 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.',
+ 'installCommand.regex' => 'The install command contains invalid characters. Shell operators like ;, |, $, and backticks are not allowed.',
+ 'buildCommand.regex' => 'The build command contains invalid characters. Shell operators like ;, |, $, and backticks are not allowed.',
+ 'startCommand.regex' => 'The start command contains 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.',
@@ -206,6 +212,8 @@ protected function messages(): array
'staticImage.required' => 'The Static Image field is required.',
'baseDirectory.required' => 'The Base Directory field is required.',
'portsExposes.required' => 'The Exposed Ports field is required.',
+ 'portsExposes.regex' => 'Ports exposes must be a comma-separated list of port numbers (e.g. 3000,3001).',
+ ...ValidationPatterns::portMappingMessages(),
'isStatic.required' => 'The Static setting is required.',
'isStatic.boolean' => 'The Static setting must be true or false.',
'isSpa.required' => 'The SPA setting is required.',
@@ -288,7 +296,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 +317,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 +329,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 +595,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 +620,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
}
}
@@ -729,6 +737,7 @@ public function setRedirect()
$this->authorize('update', $this->application);
try {
+ $this->application->redirect = $this->redirect;
$has_www = collect($this->application->fqdns)->filter(fn ($fqdn) => str($fqdn)->contains('www.'))->count();
if ($has_www === 0 && $this->application->redirect === 'www') {
$this->dispatch('error', 'You want to redirect to www, but you do not have a www domain set.
Please add www to your domain list and as an A DNS record (if applicable).');
@@ -749,6 +758,12 @@ public function submit($showToaster = true)
$this->authorize('update', $this->application);
$this->resetErrorBag();
+
+ $this->portsExposes = str($this->portsExposes)->replace(' ', '')->trim()->toString();
+ if ($this->portsMappings) {
+ $this->portsMappings = str($this->portsMappings)->replace(' ', '')->trim()->toString();
+ }
+
$this->validate();
$oldPortsExposes = $this->application->ports_exposes;
@@ -809,7 +824,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 +954,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/Livewire/Project/Application/Previews.php b/app/Livewire/Project/Application/Previews.php
index 41f352c14..c887e9b83 100644
--- a/app/Livewire/Project/Application/Previews.php
+++ b/app/Livewire/Project/Application/Previews.php
@@ -35,8 +35,17 @@ class Previews extends Component
public array $previewFqdns = [];
+ public array $previewDockerTags = [];
+
+ public ?int $manualPullRequestId = null;
+
+ public ?string $manualDockerTag = null;
+
protected $rules = [
'previewFqdns.*' => 'string|nullable',
+ 'previewDockerTags.*' => 'string|nullable',
+ 'manualPullRequestId' => 'integer|min:1|nullable',
+ 'manualDockerTag' => 'string|nullable',
];
public function mount()
@@ -53,12 +62,17 @@ private function syncData(bool $toModel = false): void
$preview = $this->application->previews->get($key);
if ($preview) {
$preview->fqdn = $fqdn;
+ if ($this->application->build_pack === 'dockerimage') {
+ $preview->docker_registry_image_tag = $this->previewDockerTags[$key] ?? null;
+ }
}
}
} else {
$this->previewFqdns = [];
+ $this->previewDockerTags = [];
foreach ($this->application->previews as $key => $preview) {
$this->previewFqdns[$key] = $preview->fqdn;
+ $this->previewDockerTags[$key] = $preview->docker_registry_image_tag;
}
}
}
@@ -174,7 +188,7 @@ public function generate_preview($preview_id)
}
}
- public function add(int $pull_request_id, ?string $pull_request_html_url = null)
+ public function add(int $pull_request_id, ?string $pull_request_html_url = null, ?string $docker_registry_image_tag = null)
{
try {
$this->authorize('update', $this->application);
@@ -195,13 +209,18 @@ public function add(int $pull_request_id, ?string $pull_request_html_url = null)
} else {
$this->setDeploymentUuid();
$found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();
- if (! $found && ! is_null($pull_request_html_url)) {
+ if (! $found && (! is_null($pull_request_html_url) || ($this->application->build_pack === 'dockerimage' && str($docker_registry_image_tag)->isNotEmpty()))) {
$found = ApplicationPreview::create([
'application_id' => $this->application->id,
'pull_request_id' => $pull_request_id,
- 'pull_request_html_url' => $pull_request_html_url,
+ 'pull_request_html_url' => $pull_request_html_url ?? '',
+ 'docker_registry_image_tag' => $docker_registry_image_tag,
]);
}
+ if ($found && $this->application->build_pack === 'dockerimage' && str($docker_registry_image_tag)->isNotEmpty()) {
+ $found->docker_registry_image_tag = $docker_registry_image_tag;
+ $found->save();
+ }
$found->generate_preview_fqdn();
$this->application->refresh();
$this->syncData(false);
@@ -217,37 +236,50 @@ public function force_deploy_without_cache(int $pull_request_id, ?string $pull_r
{
$this->authorize('deploy', $this->application);
- $this->deploy($pull_request_id, $pull_request_html_url, force_rebuild: true);
+ $dockerRegistryImageTag = null;
+ if ($this->application->build_pack === 'dockerimage') {
+ $dockerRegistryImageTag = $this->application->previews()
+ ->where('pull_request_id', $pull_request_id)
+ ->value('docker_registry_image_tag');
+ }
+
+ $this->deploy($pull_request_id, $pull_request_html_url, force_rebuild: true, docker_registry_image_tag: $dockerRegistryImageTag);
}
- public function add_and_deploy(int $pull_request_id, ?string $pull_request_html_url = null)
+ public function add_and_deploy(int $pull_request_id, ?string $pull_request_html_url = null, ?string $docker_registry_image_tag = null)
{
$this->authorize('deploy', $this->application);
- $this->add($pull_request_id, $pull_request_html_url);
- $this->deploy($pull_request_id, $pull_request_html_url);
+ $this->add($pull_request_id, $pull_request_html_url, $docker_registry_image_tag);
+ $this->deploy($pull_request_id, $pull_request_html_url, force_rebuild: false, docker_registry_image_tag: $docker_registry_image_tag);
}
- public function deploy(int $pull_request_id, ?string $pull_request_html_url = null, bool $force_rebuild = false)
+ public function deploy(int $pull_request_id, ?string $pull_request_html_url = null, bool $force_rebuild = false, ?string $docker_registry_image_tag = null)
{
$this->authorize('deploy', $this->application);
try {
$this->setDeploymentUuid();
$found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();
- if (! $found && ! is_null($pull_request_html_url)) {
- ApplicationPreview::create([
+ if (! $found && (! is_null($pull_request_html_url) || ($this->application->build_pack === 'dockerimage' && str($docker_registry_image_tag)->isNotEmpty()))) {
+ $found = ApplicationPreview::create([
'application_id' => $this->application->id,
'pull_request_id' => $pull_request_id,
- 'pull_request_html_url' => $pull_request_html_url,
+ 'pull_request_html_url' => $pull_request_html_url ?? '',
+ 'docker_registry_image_tag' => $docker_registry_image_tag,
]);
}
+ if ($found && $this->application->build_pack === 'dockerimage' && str($docker_registry_image_tag)->isNotEmpty()) {
+ $found->docker_registry_image_tag = $docker_registry_image_tag;
+ $found->save();
+ }
$result = queue_application_deployment(
application: $this->application,
deployment_uuid: $this->deployment_uuid,
force_rebuild: $force_rebuild,
pull_request_id: $pull_request_id,
git_type: $found->git_type ?? null,
+ docker_registry_image_tag: $docker_registry_image_tag,
);
if ($result['status'] === 'queue_full') {
$this->dispatch('error', 'Deployment queue full', $result['message']);
@@ -277,6 +309,32 @@ protected function setDeploymentUuid()
$this->parameters['deployment_uuid'] = $this->deployment_uuid;
}
+ public function addDockerImagePreview()
+ {
+ $this->authorize('deploy', $this->application);
+ $this->validateOnly('manualPullRequestId');
+ $this->validateOnly('manualDockerTag');
+
+ if ($this->application->build_pack !== 'dockerimage') {
+ $this->dispatch('error', 'Manual Docker Image previews are only available for Docker Image applications.');
+
+ return;
+ }
+
+ if ($this->manualPullRequestId === null || str($this->manualDockerTag)->isEmpty()) {
+ $this->dispatch('error', 'Both pull request id and docker tag are required.');
+
+ return;
+ }
+
+ $dockerTag = str($this->manualDockerTag)->trim()->value();
+
+ $this->add_and_deploy($this->manualPullRequestId, null, $dockerTag);
+
+ $this->manualPullRequestId = null;
+ $this->manualDockerTag = null;
+ }
+
private function stopContainers(array $containers, $server)
{
$containersToStop = collect($containers)->pluck('Names')->toArray();
diff --git a/app/Livewire/Project/CloneMe.php b/app/Livewire/Project/CloneMe.php
index 3b3e42619..644753c83 100644
--- a/app/Livewire/Project/CloneMe.php
+++ b/app/Livewire/Project/CloneMe.php
@@ -54,7 +54,7 @@ protected function messages(): array
public function mount($project_uuid)
{
$this->project_uuid = $project_uuid;
- $this->project = Project::where('uuid', $project_uuid)->firstOrFail();
+ $this->project = Project::ownedByCurrentTeam()->where('uuid', $project_uuid)->firstOrFail();
$this->environment = $this->project->environments->where('uuid', $this->environment_uuid)->first();
$this->project_id = $this->project->id;
$this->servers = currentTeam()
@@ -187,6 +187,7 @@ public function clone(string $type)
'id',
'created_at',
'updated_at',
+ 'uuid',
])->fill([
'name' => $newName,
'resource_id' => $newDatabase->id,
@@ -298,9 +299,9 @@ public function clone(string $type)
}
foreach ($newService->applications() as $application) {
- $application->update([
+ $application->fill([
'status' => 'exited',
- ]);
+ ])->save();
$persistentVolumes = $application->persistentStorages()->get();
foreach ($persistentVolumes as $volume) {
@@ -315,6 +316,7 @@ public function clone(string $type)
'id',
'created_at',
'updated_at',
+ 'uuid',
])->fill([
'name' => $newName,
'resource_id' => $application->id,
@@ -352,9 +354,9 @@ public function clone(string $type)
}
foreach ($newService->databases() as $database) {
- $database->update([
+ $database->fill([
'status' => 'exited',
- ]);
+ ])->save();
$persistentVolumes = $database->persistentStorages()->get();
foreach ($persistentVolumes as $volume) {
@@ -369,6 +371,7 @@ public function clone(string $type)
'id',
'created_at',
'updated_at',
+ 'uuid',
])->fill([
'name' => $newName,
'resource_id' => $database->id,
diff --git a/app/Livewire/Project/Database/BackupEdit.php b/app/Livewire/Project/Database/BackupEdit.php
index c24e2a3f1..a18022882 100644
--- a/app/Livewire/Project/Database/BackupEdit.php
+++ b/app/Livewire/Project/Database/BackupEdit.php
@@ -76,7 +76,7 @@ class BackupEdit extends Component
public bool $dumpAll = false;
#[Validate(['required', 'int', 'min:60', 'max:36000'])]
- public int $timeout = 3600;
+ public int|string $timeout = 3600;
public function mount()
{
@@ -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/app/Livewire/Project/Database/Clickhouse/General.php b/app/Livewire/Project/Database/Clickhouse/General.php
index 9de75c1c5..e06629d10 100644
--- a/app/Livewire/Project/Database/Clickhouse/General.php
+++ b/app/Livewire/Project/Database/Clickhouse/General.php
@@ -34,9 +34,9 @@ class General extends Component
public ?bool $isPublic = null;
- public ?int $publicPort = null;
+ public mixed $publicPort = null;
- public ?int $publicPortTimeout = 3600;
+ public mixed $publicPortTimeout = 3600;
public ?string $customDockerRunOptions = null;
@@ -79,9 +79,9 @@ protected function rules(): array
'clickhouseAdminUser' => 'required|string',
'clickhouseAdminPassword' => 'required|string',
'image' => 'required|string',
- 'portsMappings' => 'nullable|string',
+ 'portsMappings' => ValidationPatterns::portMappingRules(),
'isPublic' => 'nullable|boolean',
- 'publicPort' => 'nullable|integer',
+ 'publicPort' => 'nullable|integer|min:1|max:65535',
'publicPortTimeout' => 'nullable|integer|min:1',
'customDockerRunOptions' => 'nullable|string',
'dbUrl' => 'nullable|string',
@@ -94,6 +94,7 @@ protected function messages(): array
{
return array_merge(
ValidationPatterns::combinedMessages(),
+ ValidationPatterns::portMappingMessages(),
[
'clickhouseAdminUser.required' => 'The Admin User field is required.',
'clickhouseAdminUser.string' => 'The Admin User must be a string.',
@@ -102,6 +103,8 @@ protected function messages(): array
'image.required' => 'The Docker Image field is required.',
'image.string' => 'The Docker Image must be a string.',
'publicPort.integer' => 'The Public Port must be an integer.',
+ 'publicPort.min' => 'The Public Port must be at least 1.',
+ 'publicPort.max' => 'The Public Port must not exceed 65535.',
'publicPortTimeout.integer' => 'The Public Port Timeout must be an integer.',
'publicPortTimeout.min' => 'The Public Port Timeout must be at least 1.',
]
@@ -119,8 +122,8 @@ public function syncData(bool $toModel = false)
$this->database->image = $this->image;
$this->database->ports_mappings = $this->portsMappings;
$this->database->is_public = $this->isPublic;
- $this->database->public_port = $this->publicPort;
- $this->database->public_port_timeout = $this->publicPortTimeout;
+ $this->database->public_port = $this->publicPort ?: null;
+ $this->database->public_port_timeout = $this->publicPortTimeout ?: null;
$this->database->custom_docker_run_options = $this->customDockerRunOptions;
$this->database->is_log_drain_enabled = $this->isLogDrainEnabled;
$this->database->save();
@@ -207,6 +210,9 @@ public function submit()
try {
$this->authorize('update', $this->database);
+ if ($this->portsMappings) {
+ $this->portsMappings = str($this->portsMappings)->replace(' ', '')->trim()->toString();
+ }
if (str($this->publicPort)->isEmpty()) {
$this->publicPort = null;
}
diff --git a/app/Livewire/Project/Database/Dragonfly/General.php b/app/Livewire/Project/Database/Dragonfly/General.php
index d35e57a9d..5176f5ff9 100644
--- a/app/Livewire/Project/Database/Dragonfly/General.php
+++ b/app/Livewire/Project/Database/Dragonfly/General.php
@@ -34,9 +34,9 @@ class General extends Component
public ?bool $isPublic = null;
- public ?int $publicPort = null;
+ public mixed $publicPort = null;
- public ?int $publicPortTimeout = 3600;
+ public mixed $publicPortTimeout = 3600;
public ?string $customDockerRunOptions = null;
@@ -57,7 +57,8 @@ public function getListeners()
return [
"echo-private:team.{$teamId},DatabaseProxyStopped" => 'databaseProxyStopped',
- "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh',
+ "echo-private:user.{$userId},DatabaseStatusChanged" => 'refresh',
+ "echo-private:team.{$teamId},ServiceChecked" => 'refresh',
];
}
@@ -90,9 +91,9 @@ protected function rules(): array
'description' => ValidationPatterns::descriptionRules(),
'dragonflyPassword' => 'required|string',
'image' => 'required|string',
- 'portsMappings' => 'nullable|string',
+ 'portsMappings' => ValidationPatterns::portMappingRules(),
'isPublic' => 'nullable|boolean',
- 'publicPort' => 'nullable|integer',
+ 'publicPort' => 'nullable|integer|min:1|max:65535',
'publicPortTimeout' => 'nullable|integer|min:1',
'customDockerRunOptions' => 'nullable|string',
'dbUrl' => 'nullable|string',
@@ -106,12 +107,15 @@ protected function messages(): array
{
return array_merge(
ValidationPatterns::combinedMessages(),
+ ValidationPatterns::portMappingMessages(),
[
'dragonflyPassword.required' => 'The Dragonfly Password field is required.',
'dragonflyPassword.string' => 'The Dragonfly Password must be a string.',
'image.required' => 'The Docker Image field is required.',
'image.string' => 'The Docker Image must be a string.',
'publicPort.integer' => 'The Public Port must be an integer.',
+ 'publicPort.min' => 'The Public Port must be at least 1.',
+ 'publicPort.max' => 'The Public Port must not exceed 65535.',
'publicPortTimeout.integer' => 'The Public Port Timeout must be an integer.',
'publicPortTimeout.min' => 'The Public Port Timeout must be at least 1.',
]
@@ -128,8 +132,8 @@ public function syncData(bool $toModel = false)
$this->database->image = $this->image;
$this->database->ports_mappings = $this->portsMappings;
$this->database->is_public = $this->isPublic;
- $this->database->public_port = $this->publicPort;
- $this->database->public_port_timeout = $this->publicPortTimeout;
+ $this->database->public_port = $this->publicPort ?: null;
+ $this->database->public_port_timeout = $this->publicPortTimeout ?: null;
$this->database->custom_docker_run_options = $this->customDockerRunOptions;
$this->database->is_log_drain_enabled = $this->isLogDrainEnabled;
$this->database->enable_ssl = $this->enable_ssl;
@@ -217,6 +221,9 @@ public function submit()
try {
$this->authorize('update', $this->database);
+ if ($this->portsMappings) {
+ $this->portsMappings = str($this->portsMappings)->replace(' ', '')->trim()->toString();
+ }
if (str($this->publicPort)->isEmpty()) {
$this->publicPort = null;
}
@@ -276,8 +283,8 @@ public function regenerateSslCertificate()
}
SslHelper::generateSslCertificate(
- commonName: $existingCert->commonName,
- subjectAlternativeNames: $existingCert->subjectAlternativeNames ?? [],
+ commonName: $existingCert->common_name,
+ subjectAlternativeNames: $existingCert->subject_alternative_names ?? [],
resourceType: $existingCert->resource_type,
resourceId: $existingCert->resource_id,
serverId: $existingCert->server_id,
@@ -293,4 +300,10 @@ public function regenerateSslCertificate()
handleError($e, $this);
}
}
+
+ public function refresh(): void
+ {
+ $this->database->refresh();
+ $this->syncData();
+ }
}
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/Database/Keydb/General.php b/app/Livewire/Project/Database/Keydb/General.php
index adb4ccb5f..b50f196a8 100644
--- a/app/Livewire/Project/Database/Keydb/General.php
+++ b/app/Livewire/Project/Database/Keydb/General.php
@@ -36,9 +36,9 @@ class General extends Component
public ?bool $isPublic = null;
- public ?int $publicPort = null;
+ public mixed $publicPort = null;
- public ?int $publicPortTimeout = 3600;
+ public mixed $publicPortTimeout = 3600;
public ?string $customDockerRunOptions = null;
@@ -59,7 +59,8 @@ public function getListeners()
return [
"echo-private:team.{$teamId},DatabaseProxyStopped" => 'databaseProxyStopped',
- "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh',
+ "echo-private:user.{$userId},DatabaseStatusChanged" => 'refresh',
+ "echo-private:team.{$teamId},ServiceChecked" => 'refresh',
];
}
@@ -93,9 +94,9 @@ protected function rules(): array
'keydbConf' => 'nullable|string',
'keydbPassword' => 'required|string',
'image' => 'required|string',
- 'portsMappings' => 'nullable|string',
+ 'portsMappings' => ValidationPatterns::portMappingRules(),
'isPublic' => 'nullable|boolean',
- 'publicPort' => 'nullable|integer',
+ 'publicPort' => 'nullable|integer|min:1|max:65535',
'publicPortTimeout' => 'nullable|integer|min:1',
'customDockerRunOptions' => 'nullable|string',
'dbUrl' => 'nullable|string',
@@ -111,12 +112,15 @@ protected function messages(): array
{
return array_merge(
ValidationPatterns::combinedMessages(),
+ ValidationPatterns::portMappingMessages(),
[
'keydbPassword.required' => 'The KeyDB Password field is required.',
'keydbPassword.string' => 'The KeyDB Password must be a string.',
'image.required' => 'The Docker Image field is required.',
'image.string' => 'The Docker Image must be a string.',
'publicPort.integer' => 'The Public Port must be an integer.',
+ 'publicPort.min' => 'The Public Port must be at least 1.',
+ 'publicPort.max' => 'The Public Port must not exceed 65535.',
'publicPortTimeout.integer' => 'The Public Port Timeout must be an integer.',
'publicPortTimeout.min' => 'The Public Port Timeout must be at least 1.',
]
@@ -134,8 +138,8 @@ public function syncData(bool $toModel = false)
$this->database->image = $this->image;
$this->database->ports_mappings = $this->portsMappings;
$this->database->is_public = $this->isPublic;
- $this->database->public_port = $this->publicPort;
- $this->database->public_port_timeout = $this->publicPortTimeout;
+ $this->database->public_port = $this->publicPort ?: null;
+ $this->database->public_port_timeout = $this->publicPortTimeout ?: null;
$this->database->custom_docker_run_options = $this->customDockerRunOptions;
$this->database->is_log_drain_enabled = $this->isLogDrainEnabled;
$this->database->enable_ssl = $this->enable_ssl;
@@ -224,6 +228,9 @@ public function submit()
try {
$this->authorize('manageEnvironment', $this->database);
+ if ($this->portsMappings) {
+ $this->portsMappings = str($this->portsMappings)->replace(' ', '')->trim()->toString();
+ }
if (str($this->publicPort)->isEmpty()) {
$this->publicPort = null;
}
@@ -269,9 +276,20 @@ public function regenerateSslCertificate()
->where('is_ca_certificate', true)
->first();
+ if (! $caCert) {
+ $this->server->generateCaCertificate();
+ $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ }
+
+ if (! $caCert) {
+ $this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
+
+ return;
+ }
+
SslHelper::generateSslCertificate(
- commonName: $existingCert->commonName,
- subjectAlternativeNames: $existingCert->subjectAlternativeNames ?? [],
+ commonName: $existingCert->common_name,
+ subjectAlternativeNames: $existingCert->subject_alternative_names ?? [],
resourceType: $existingCert->resource_type,
resourceId: $existingCert->resource_id,
serverId: $existingCert->server_id,
@@ -287,4 +305,10 @@ public function regenerateSslCertificate()
handleError($e, $this);
}
}
+
+ public function refresh(): void
+ {
+ $this->database->refresh();
+ $this->syncData();
+ }
}
diff --git a/app/Livewire/Project/Database/Mariadb/General.php b/app/Livewire/Project/Database/Mariadb/General.php
index 14240c82d..9a1a8bd68 100644
--- a/app/Livewire/Project/Database/Mariadb/General.php
+++ b/app/Livewire/Project/Database/Mariadb/General.php
@@ -42,9 +42,9 @@ class General extends Component
public ?bool $isPublic = null;
- public ?int $publicPort = null;
+ public mixed $publicPort = null;
- public ?int $publicPortTimeout = 3600;
+ public mixed $publicPortTimeout = 3600;
public bool $isLogDrainEnabled = false;
@@ -61,9 +61,11 @@ class General extends Component
public function getListeners()
{
$userId = Auth::id();
+ $teamId = Auth::user()->currentTeam()->id;
return [
- "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh',
+ "echo-private:user.{$userId},DatabaseStatusChanged" => 'refresh',
+ "echo-private:team.{$teamId},ServiceChecked" => 'refresh',
];
}
@@ -78,9 +80,9 @@ protected function rules(): array
'mariadbDatabase' => 'required',
'mariadbConf' => 'nullable',
'image' => 'required',
- 'portsMappings' => 'nullable',
+ 'portsMappings' => ValidationPatterns::portMappingRules(),
'isPublic' => 'nullable|boolean',
- 'publicPort' => 'nullable|integer',
+ 'publicPort' => 'nullable|integer|min:1|max:65535',
'publicPortTimeout' => 'nullable|integer|min:1',
'isLogDrainEnabled' => 'nullable|boolean',
'customDockerRunOptions' => 'nullable',
@@ -92,6 +94,7 @@ protected function messages(): array
{
return array_merge(
ValidationPatterns::combinedMessages(),
+ ValidationPatterns::portMappingMessages(),
[
'name.required' => 'The Name field is required.',
'mariadbRootPassword.required' => 'The Root Password field is required.',
@@ -100,6 +103,8 @@ protected function messages(): array
'mariadbDatabase.required' => 'The MariaDB Database field is required.',
'image.required' => 'The Docker Image field is required.',
'publicPort.integer' => 'The Public Port must be an integer.',
+ 'publicPort.min' => 'The Public Port must be at least 1.',
+ 'publicPort.max' => 'The Public Port must not exceed 65535.',
'publicPortTimeout.integer' => 'The Public Port Timeout must be an integer.',
'publicPortTimeout.min' => 'The Public Port Timeout must be at least 1.',
]
@@ -159,8 +164,8 @@ public function syncData(bool $toModel = false)
$this->database->image = $this->image;
$this->database->ports_mappings = $this->portsMappings;
$this->database->is_public = $this->isPublic;
- $this->database->public_port = $this->publicPort;
- $this->database->public_port_timeout = $this->publicPortTimeout;
+ $this->database->public_port = $this->publicPort ?: null;
+ $this->database->public_port_timeout = $this->publicPortTimeout ?: null;
$this->database->is_log_drain_enabled = $this->isLogDrainEnabled;
$this->database->custom_docker_run_options = $this->customDockerRunOptions;
$this->database->enable_ssl = $this->enableSsl;
@@ -213,6 +218,9 @@ public function submit()
try {
$this->authorize('update', $this->database);
+ if ($this->portsMappings) {
+ $this->portsMappings = str($this->portsMappings)->replace(' ', '')->trim()->toString();
+ }
if (str($this->publicPort)->isEmpty()) {
$this->publicPort = null;
}
@@ -289,6 +297,17 @@ public function regenerateSslCertificate()
$caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ if (! $caCert) {
+ $this->server->generateCaCertificate();
+ $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ }
+
+ if (! $caCert) {
+ $this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
+
+ return;
+ }
+
SslHelper::generateSslCertificate(
commonName: $existingCert->common_name,
subjectAlternativeNames: $existingCert->subject_alternative_names ?? [],
diff --git a/app/Livewire/Project/Database/Mongodb/General.php b/app/Livewire/Project/Database/Mongodb/General.php
index 11419ec71..a21de744a 100644
--- a/app/Livewire/Project/Database/Mongodb/General.php
+++ b/app/Livewire/Project/Database/Mongodb/General.php
@@ -40,9 +40,9 @@ class General extends Component
public ?bool $isPublic = null;
- public ?int $publicPort = null;
+ public mixed $publicPort = null;
- public ?int $publicPortTimeout = 3600;
+ public mixed $publicPortTimeout = 3600;
public bool $isLogDrainEnabled = false;
@@ -61,9 +61,11 @@ class General extends Component
public function getListeners()
{
$userId = Auth::id();
+ $teamId = Auth::user()->currentTeam()->id;
return [
- "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh',
+ "echo-private:user.{$userId},DatabaseStatusChanged" => 'refresh',
+ "echo-private:team.{$teamId},ServiceChecked" => 'refresh',
];
}
@@ -77,9 +79,9 @@ protected function rules(): array
'mongoInitdbRootPassword' => 'required',
'mongoInitdbDatabase' => 'required',
'image' => 'required',
- 'portsMappings' => 'nullable',
+ 'portsMappings' => ValidationPatterns::portMappingRules(),
'isPublic' => 'nullable|boolean',
- 'publicPort' => 'nullable|integer',
+ 'publicPort' => 'nullable|integer|min:1|max:65535',
'publicPortTimeout' => 'nullable|integer|min:1',
'isLogDrainEnabled' => 'nullable|boolean',
'customDockerRunOptions' => 'nullable',
@@ -92,6 +94,7 @@ protected function messages(): array
{
return array_merge(
ValidationPatterns::combinedMessages(),
+ ValidationPatterns::portMappingMessages(),
[
'name.required' => 'The Name field is required.',
'mongoInitdbRootUsername.required' => 'The Root Username field is required.',
@@ -99,6 +102,8 @@ protected function messages(): array
'mongoInitdbDatabase.required' => 'The MongoDB Database field is required.',
'image.required' => 'The Docker Image field is required.',
'publicPort.integer' => 'The Public Port must be an integer.',
+ 'publicPort.min' => 'The Public Port must be at least 1.',
+ 'publicPort.max' => 'The Public Port must not exceed 65535.',
'publicPortTimeout.integer' => 'The Public Port Timeout must be an integer.',
'publicPortTimeout.min' => 'The Public Port Timeout must be at least 1.',
'sslMode.in' => 'The SSL Mode must be one of: allow, prefer, require, verify-full.',
@@ -158,8 +163,8 @@ public function syncData(bool $toModel = false)
$this->database->image = $this->image;
$this->database->ports_mappings = $this->portsMappings;
$this->database->is_public = $this->isPublic;
- $this->database->public_port = $this->publicPort;
- $this->database->public_port_timeout = $this->publicPortTimeout;
+ $this->database->public_port = $this->publicPort ?: null;
+ $this->database->public_port_timeout = $this->publicPortTimeout ?: null;
$this->database->is_log_drain_enabled = $this->isLogDrainEnabled;
$this->database->custom_docker_run_options = $this->customDockerRunOptions;
$this->database->enable_ssl = $this->enableSsl;
@@ -213,6 +218,9 @@ public function submit()
try {
$this->authorize('update', $this->database);
+ if ($this->portsMappings) {
+ $this->portsMappings = str($this->portsMappings)->replace(' ', '')->trim()->toString();
+ }
if (str($this->publicPort)->isEmpty()) {
$this->publicPort = null;
}
@@ -297,6 +305,17 @@ public function regenerateSslCertificate()
$caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ if (! $caCert) {
+ $this->server->generateCaCertificate();
+ $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ }
+
+ if (! $caCert) {
+ $this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
+
+ return;
+ }
+
SslHelper::generateSslCertificate(
commonName: $existingCert->common_name,
subjectAlternativeNames: $existingCert->subject_alternative_names ?? [],
diff --git a/app/Livewire/Project/Database/Mysql/General.php b/app/Livewire/Project/Database/Mysql/General.php
index 4f0f5eb19..cacb4ac49 100644
--- a/app/Livewire/Project/Database/Mysql/General.php
+++ b/app/Livewire/Project/Database/Mysql/General.php
@@ -42,9 +42,9 @@ class General extends Component
public ?bool $isPublic = null;
- public ?int $publicPort = null;
+ public mixed $publicPort = null;
- public ?int $publicPortTimeout = 3600;
+ public mixed $publicPortTimeout = 3600;
public bool $isLogDrainEnabled = false;
@@ -63,9 +63,11 @@ class General extends Component
public function getListeners()
{
$userId = Auth::id();
+ $teamId = Auth::user()->currentTeam()->id;
return [
- "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh',
+ "echo-private:user.{$userId},DatabaseStatusChanged" => 'refresh',
+ "echo-private:team.{$teamId},ServiceChecked" => 'refresh',
];
}
@@ -80,9 +82,9 @@ protected function rules(): array
'mysqlDatabase' => 'required',
'mysqlConf' => 'nullable',
'image' => 'required',
- 'portsMappings' => 'nullable',
+ 'portsMappings' => ValidationPatterns::portMappingRules(),
'isPublic' => 'nullable|boolean',
- 'publicPort' => 'nullable|integer',
+ 'publicPort' => 'nullable|integer|min:1|max:65535',
'publicPortTimeout' => 'nullable|integer|min:1',
'isLogDrainEnabled' => 'nullable|boolean',
'customDockerRunOptions' => 'nullable',
@@ -95,6 +97,7 @@ protected function messages(): array
{
return array_merge(
ValidationPatterns::combinedMessages(),
+ ValidationPatterns::portMappingMessages(),
[
'name.required' => 'The Name field is required.',
'mysqlRootPassword.required' => 'The Root Password field is required.',
@@ -103,6 +106,8 @@ protected function messages(): array
'mysqlDatabase.required' => 'The MySQL Database field is required.',
'image.required' => 'The Docker Image field is required.',
'publicPort.integer' => 'The Public Port must be an integer.',
+ 'publicPort.min' => 'The Public Port must be at least 1.',
+ 'publicPort.max' => 'The Public Port must not exceed 65535.',
'publicPortTimeout.integer' => 'The Public Port Timeout must be an integer.',
'publicPortTimeout.min' => 'The Public Port Timeout must be at least 1.',
'sslMode.in' => 'The SSL Mode must be one of: PREFERRED, REQUIRED, VERIFY_CA, VERIFY_IDENTITY.',
@@ -164,8 +169,8 @@ public function syncData(bool $toModel = false)
$this->database->image = $this->image;
$this->database->ports_mappings = $this->portsMappings;
$this->database->is_public = $this->isPublic;
- $this->database->public_port = $this->publicPort;
- $this->database->public_port_timeout = $this->publicPortTimeout;
+ $this->database->public_port = $this->publicPort ?: null;
+ $this->database->public_port_timeout = $this->publicPortTimeout ?: null;
$this->database->is_log_drain_enabled = $this->isLogDrainEnabled;
$this->database->custom_docker_run_options = $this->customDockerRunOptions;
$this->database->enable_ssl = $this->enableSsl;
@@ -220,6 +225,9 @@ public function submit()
try {
$this->authorize('update', $this->database);
+ if ($this->portsMappings) {
+ $this->portsMappings = str($this->portsMappings)->replace(' ', '')->trim()->toString();
+ }
if (str($this->publicPort)->isEmpty()) {
$this->publicPort = null;
}
@@ -301,6 +309,17 @@ public function regenerateSslCertificate()
$caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ if (! $caCert) {
+ $this->server->generateCaCertificate();
+ $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ }
+
+ if (! $caCert) {
+ $this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
+
+ return;
+ }
+
SslHelper::generateSslCertificate(
commonName: $existingCert->common_name,
subjectAlternativeNames: $existingCert->subject_alternative_names ?? [],
diff --git a/app/Livewire/Project/Database/Postgresql/General.php b/app/Livewire/Project/Database/Postgresql/General.php
index 4e044672b..22e350683 100644
--- a/app/Livewire/Project/Database/Postgresql/General.php
+++ b/app/Livewire/Project/Database/Postgresql/General.php
@@ -46,9 +46,9 @@ class General extends Component
public ?bool $isPublic = null;
- public ?int $publicPort = null;
+ public mixed $publicPort = null;
- public ?int $publicPortTimeout = 3600;
+ public mixed $publicPortTimeout = 3600;
public bool $isLogDrainEnabled = false;
@@ -71,9 +71,11 @@ class General extends Component
public function getListeners()
{
$userId = Auth::id();
+ $teamId = Auth::user()->currentTeam()->id;
return [
- "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh',
+ "echo-private:user.{$userId},DatabaseStatusChanged" => 'refresh',
+ "echo-private:team.{$teamId},ServiceChecked" => 'refresh',
'save_init_script',
'delete_init_script',
];
@@ -92,9 +94,9 @@ protected function rules(): array
'postgresConf' => 'nullable',
'initScripts' => 'nullable',
'image' => 'required',
- 'portsMappings' => 'nullable',
+ 'portsMappings' => ValidationPatterns::portMappingRules(),
'isPublic' => 'nullable|boolean',
- 'publicPort' => 'nullable|integer',
+ 'publicPort' => 'nullable|integer|min:1|max:65535',
'publicPortTimeout' => 'nullable|integer|min:1',
'isLogDrainEnabled' => 'nullable|boolean',
'customDockerRunOptions' => 'nullable',
@@ -107,6 +109,7 @@ protected function messages(): array
{
return array_merge(
ValidationPatterns::combinedMessages(),
+ ValidationPatterns::portMappingMessages(),
[
'name.required' => 'The Name field is required.',
'postgresUser.required' => 'The Postgres User field is required.',
@@ -114,6 +117,8 @@ protected function messages(): array
'postgresDb.required' => 'The Postgres Database field is required.',
'image.required' => 'The Docker Image field is required.',
'publicPort.integer' => 'The Public Port must be an integer.',
+ 'publicPort.min' => 'The Public Port must be at least 1.',
+ 'publicPort.max' => 'The Public Port must not exceed 65535.',
'publicPortTimeout.integer' => 'The Public Port Timeout must be an integer.',
'publicPortTimeout.min' => 'The Public Port Timeout must be at least 1.',
'sslMode.in' => 'The SSL Mode must be one of: allow, prefer, require, verify-ca, verify-full.',
@@ -179,8 +184,8 @@ public function syncData(bool $toModel = false)
$this->database->image = $this->image;
$this->database->ports_mappings = $this->portsMappings;
$this->database->is_public = $this->isPublic;
- $this->database->public_port = $this->publicPort;
- $this->database->public_port_timeout = $this->publicPortTimeout;
+ $this->database->public_port = $this->publicPort ?: null;
+ $this->database->public_port_timeout = $this->publicPortTimeout ?: null;
$this->database->is_log_drain_enabled = $this->isLogDrainEnabled;
$this->database->custom_docker_run_options = $this->customDockerRunOptions;
$this->database->enable_ssl = $this->enableSsl;
@@ -264,6 +269,17 @@ public function regenerateSslCertificate()
$caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ if (! $caCert) {
+ $this->server->generateCaCertificate();
+ $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ }
+
+ if (! $caCert) {
+ $this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
+
+ return;
+ }
+
SslHelper::generateSslCertificate(
commonName: $existingCert->common_name,
subjectAlternativeNames: $existingCert->subject_alternative_names ?? [],
@@ -456,6 +472,9 @@ public function submit()
try {
$this->authorize('update', $this->database);
+ if ($this->portsMappings) {
+ $this->portsMappings = str($this->portsMappings)->replace(' ', '')->trim()->toString();
+ }
if (str($this->publicPort)->isEmpty()) {
$this->publicPort = null;
}
@@ -471,4 +490,10 @@ public function submit()
}
}
}
+
+ public function refresh(): void
+ {
+ $this->database->refresh();
+ $this->syncData();
+ }
}
diff --git a/app/Livewire/Project/Database/Redis/General.php b/app/Livewire/Project/Database/Redis/General.php
index ebe2f3ba0..3c32a6192 100644
--- a/app/Livewire/Project/Database/Redis/General.php
+++ b/app/Livewire/Project/Database/Redis/General.php
@@ -34,9 +34,9 @@ class General extends Component
public ?bool $isPublic = null;
- public ?int $publicPort = null;
+ public mixed $publicPort = null;
- public ?int $publicPortTimeout = 3600;
+ public mixed $publicPortTimeout = 3600;
public bool $isLogDrainEnabled = false;
@@ -59,9 +59,11 @@ class General extends Component
public function getListeners()
{
$userId = Auth::id();
+ $teamId = Auth::user()->currentTeam()->id;
return [
- "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh',
+ "echo-private:user.{$userId},DatabaseStatusChanged" => 'refresh',
+ "echo-private:team.{$teamId},ServiceChecked" => 'refresh',
'envsUpdated' => 'refresh',
];
}
@@ -73,9 +75,9 @@ protected function rules(): array
'description' => ValidationPatterns::descriptionRules(),
'redisConf' => 'nullable',
'image' => 'required',
- 'portsMappings' => 'nullable',
+ 'portsMappings' => ValidationPatterns::portMappingRules(),
'isPublic' => 'nullable|boolean',
- 'publicPort' => 'nullable|integer',
+ 'publicPort' => 'nullable|integer|min:1|max:65535',
'publicPortTimeout' => 'nullable|integer|min:1',
'isLogDrainEnabled' => 'nullable|boolean',
'customDockerRunOptions' => 'nullable',
@@ -89,10 +91,13 @@ protected function messages(): array
{
return array_merge(
ValidationPatterns::combinedMessages(),
+ ValidationPatterns::portMappingMessages(),
[
'name.required' => 'The Name field is required.',
'image.required' => 'The Docker Image field is required.',
'publicPort.integer' => 'The Public Port must be an integer.',
+ 'publicPort.min' => 'The Public Port must be at least 1.',
+ 'publicPort.max' => 'The Public Port must not exceed 65535.',
'publicPortTimeout.integer' => 'The Public Port Timeout must be an integer.',
'publicPortTimeout.min' => 'The Public Port Timeout must be at least 1.',
'redisUsername.required' => 'The Redis Username field is required.',
@@ -148,8 +153,8 @@ public function syncData(bool $toModel = false)
$this->database->image = $this->image;
$this->database->ports_mappings = $this->portsMappings;
$this->database->is_public = $this->isPublic;
- $this->database->public_port = $this->publicPort;
- $this->database->public_port_timeout = $this->publicPortTimeout;
+ $this->database->public_port = $this->publicPort ?: null;
+ $this->database->public_port_timeout = $this->publicPortTimeout ?: null;
$this->database->is_log_drain_enabled = $this->isLogDrainEnabled;
$this->database->custom_docker_run_options = $this->customDockerRunOptions;
$this->database->enable_ssl = $this->enableSsl;
@@ -201,6 +206,9 @@ public function submit()
try {
$this->authorize('manageEnvironment', $this->database);
+ if ($this->portsMappings) {
+ $this->portsMappings = str($this->portsMappings)->replace(' ', '')->trim()->toString();
+ }
$this->syncData(true);
if (version_compare($this->redisVersion, '6.0', '>=')) {
@@ -282,9 +290,20 @@ public function regenerateSslCertificate()
$caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ if (! $caCert) {
+ $this->server->generateCaCertificate();
+ $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first();
+ }
+
+ if (! $caCert) {
+ $this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
+
+ return;
+ }
+
SslHelper::generateSslCertificate(
- commonName: $existingCert->commonName,
- subjectAlternativeNames: $existingCert->subjectAlternativeNames ?? [],
+ commonName: $existingCert->common_name,
+ subjectAlternativeNames: $existingCert->subject_alternative_names ?? [],
resourceType: $existingCert->resource_type,
resourceId: $existingCert->resource_id,
serverId: $existingCert->server_id,
diff --git a/app/Livewire/Project/DeleteProject.php b/app/Livewire/Project/DeleteProject.php
index a018046fd..d95041c2d 100644
--- a/app/Livewire/Project/DeleteProject.php
+++ b/app/Livewire/Project/DeleteProject.php
@@ -21,7 +21,7 @@ class DeleteProject extends Component
public function mount()
{
$this->parameters = get_route_parameters();
- $this->projectName = Project::findOrFail($this->project_id)->name;
+ $this->projectName = Project::ownedByCurrentTeam()->findOrFail($this->project_id)->name;
}
public function delete()
@@ -29,7 +29,7 @@ public function delete()
$this->validate([
'project_id' => 'required|int',
]);
- $project = Project::findOrFail($this->project_id);
+ $project = Project::ownedByCurrentTeam()->findOrFail($this->project_id);
$this->authorize('delete', $project);
if ($project->isEmpty()) {
diff --git a/app/Livewire/Project/New/DockerCompose.php b/app/Livewire/Project/New/DockerCompose.php
index 634a012c0..2b92902c6 100644
--- a/app/Livewire/Project/New/DockerCompose.php
+++ b/app/Livewire/Project/New/DockerCompose.php
@@ -41,8 +41,8 @@ public function submit()
// Validate for command injection BEFORE saving to database
validateDockerComposeForInjection($this->dockerComposeRaw);
- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
- $environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
+ $project = Project::ownedByCurrentTeam()->where('uuid', $this->parameters['project_uuid'])->firstOrFail();
+ $environment = $project->environments()->where('uuid', $this->parameters['environment_uuid'])->firstOrFail();
$destination_uuid = $this->query['destination'];
$destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
diff --git a/app/Livewire/Project/New/DockerImage.php b/app/Livewire/Project/New/DockerImage.php
index 8aff83153..268333d07 100644
--- a/app/Livewire/Project/New/DockerImage.php
+++ b/app/Livewire/Project/New/DockerImage.php
@@ -121,8 +121,8 @@ public function submit()
}
$destination_class = $destination->getMorphClass();
- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
- $environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
+ $project = Project::ownedByCurrentTeam()->where('uuid', $this->parameters['project_uuid'])->firstOrFail();
+ $environment = $project->environments()->where('uuid', $this->parameters['environment_uuid'])->firstOrFail();
// Append @sha256 to image name if using digest and not already present
$imageName = $parser->getFullImageNameWithoutTag();
diff --git a/app/Livewire/Project/New/GithubPrivateRepository.php b/app/Livewire/Project/New/GithubPrivateRepository.php
index 61ae0e151..0222008b0 100644
--- a/app/Livewire/Project/New/GithubPrivateRepository.php
+++ b/app/Livewire/Project/New/GithubPrivateRepository.php
@@ -8,6 +8,7 @@
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
use App\Rules\ValidGitBranch;
+use App\Support\ValidationPatterns;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Livewire\Component;
@@ -98,6 +99,8 @@ public function updatedBuildPack()
public function loadRepositories($github_app_id)
{
$this->repositories = collect();
+ $this->branches = collect();
+ $this->total_branches_count = 0;
$this->page = 1;
$this->selected_github_app_id = $github_app_id;
$this->github_app = GithubApp::where('id', $github_app_id)->first();
@@ -168,7 +171,7 @@ public function submit()
'selected_repository_owner' => 'required|string|regex:/^[a-zA-Z0-9\-_]+$/',
'selected_repository_repo' => 'required|string|regex:/^[a-zA-Z0-9\-_\.]+$/',
'selected_branch_name' => ['required', 'string', new ValidGitBranch],
- 'docker_compose_location' => \App\Support\ValidationPatterns::filePathRules(),
+ 'docker_compose_location' => ValidationPatterns::filePathRules(),
]);
if ($validator->fails()) {
@@ -185,8 +188,8 @@ public function submit()
}
$destination_class = $destination->getMorphClass();
- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
- $environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
+ $project = Project::ownedByCurrentTeam()->where('uuid', $this->parameters['project_uuid'])->firstOrFail();
+ $environment = $project->environments()->where('uuid', $this->parameters['environment_uuid'])->firstOrFail();
$application = Application::create([
'name' => generate_application_name($this->selected_repository_owner.'/'.$this->selected_repository_repo, $this->selected_branch_name),
diff --git a/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php b/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php
index e46ad7d78..f8642d6fc 100644
--- a/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php
+++ b/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php
@@ -11,6 +11,7 @@
use App\Models\SwarmDocker;
use App\Rules\ValidGitBranch;
use App\Rules\ValidGitRepositoryUrl;
+use App\Support\ValidationPatterns;
use Illuminate\Support\Str;
use Livewire\Component;
use Spatie\Url\Url;
@@ -66,7 +67,7 @@ protected function rules()
'is_static' => 'required|boolean',
'publish_directory' => 'nullable|string',
'build_pack' => 'required|string',
- 'docker_compose_location' => \App\Support\ValidationPatterns::filePathRules(),
+ 'docker_compose_location' => ValidationPatterns::filePathRules(),
];
}
@@ -144,8 +145,8 @@ public function submit()
// Note: git_repository has already been validated and transformed in get_git_source()
// It may now be in SSH format (git@host:repo.git) which is valid for deploy keys
- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
- $environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
+ $project = Project::ownedByCurrentTeam()->where('uuid', $this->parameters['project_uuid'])->firstOrFail();
+ $environment = $project->environments()->where('uuid', $this->parameters['environment_uuid'])->firstOrFail();
if ($this->git_source === 'other') {
$application_init = [
'name' => generate_random_name(),
diff --git a/app/Livewire/Project/New/PublicGitRepository.php b/app/Livewire/Project/New/PublicGitRepository.php
index 3df31a6a3..dbfa15a55 100644
--- a/app/Livewire/Project/New/PublicGitRepository.php
+++ b/app/Livewire/Project/New/PublicGitRepository.php
@@ -11,6 +11,7 @@
use App\Models\SwarmDocker;
use App\Rules\ValidGitBranch;
use App\Rules\ValidGitRepositoryUrl;
+use App\Support\ValidationPatterns;
use Carbon\Carbon;
use Livewire\Component;
use Spatie\Url\Url;
@@ -72,7 +73,7 @@ protected function rules()
'publish_directory' => 'nullable|string',
'build_pack' => 'required|string',
'base_directory' => 'nullable|string',
- 'docker_compose_location' => \App\Support\ValidationPatterns::filePathRules(),
+ 'docker_compose_location' => ValidationPatterns::filePathRules(),
'git_branch' => ['required', 'string', new ValidGitBranch],
];
}
@@ -207,13 +208,8 @@ private function getGitSource()
if ($this->repository_url_parsed->getSegment(3) === 'tree') {
$path = str($this->repository_url_parsed->getPath())->trim('/');
- $this->git_branch = str($path)->after('tree/')->before('/')->value();
- $this->base_directory = str($path)->after($this->git_branch)->after('/')->value();
- if (filled($this->base_directory)) {
- $this->base_directory = '/'.$this->base_directory;
- } else {
- $this->base_directory = '/';
- }
+ $this->git_branch = str($path)->after('tree/')->value();
+ $this->base_directory = '/';
} else {
$this->git_branch = 'main';
}
@@ -233,10 +229,33 @@ private function getBranch()
return;
}
- if ($this->git_source->getMorphClass() === \App\Models\GithubApp::class) {
- ['rate_limit_remaining' => $this->rate_limit_remaining, 'rate_limit_reset' => $this->rate_limit_reset] = githubApi(source: $this->git_source, endpoint: "/repos/{$this->git_repository}/branches/{$this->git_branch}");
- $this->rate_limit_reset = Carbon::parse((int) $this->rate_limit_reset)->format('Y-M-d H:i:s');
- $this->branchFound = true;
+ if ($this->git_source->getMorphClass() === GithubApp::class) {
+ $originalBranch = $this->git_branch;
+ $branchToTry = $originalBranch;
+
+ while (true) {
+ try {
+ $encodedBranch = urlencode($branchToTry);
+ ['rate_limit_remaining' => $this->rate_limit_remaining, 'rate_limit_reset' => $this->rate_limit_reset] = githubApi(source: $this->git_source, endpoint: "/repos/{$this->git_repository}/branches/{$encodedBranch}");
+ $this->rate_limit_reset = Carbon::parse((int) $this->rate_limit_reset)->format('Y-M-d H:i:s');
+ $this->git_branch = $branchToTry;
+
+ $remaining = str($originalBranch)->after($branchToTry)->trim('/')->value();
+ $this->base_directory = filled($remaining) ? '/'.$remaining : '/';
+
+ $this->branchFound = true;
+
+ return;
+ } catch (\Throwable $e) {
+ if (str_contains($branchToTry, '/')) {
+ $branchToTry = str($branchToTry)->beforeLast('/')->value();
+
+ continue;
+ }
+
+ throw $e;
+ }
+ }
}
}
@@ -278,8 +297,8 @@ public function submit()
}
$destination_class = $destination->getMorphClass();
- $project = Project::where('uuid', $project_uuid)->first();
- $environment = $project->load(['environments'])->environments->where('uuid', $environment_uuid)->first();
+ $project = Project::ownedByCurrentTeam()->where('uuid', $project_uuid)->firstOrFail();
+ $environment = $project->environments()->where('uuid', $environment_uuid)->firstOrFail();
if ($this->build_pack === 'dockercompose' && isDev() && $this->new_compose_services) {
$server = $destination->server;
diff --git a/app/Livewire/Project/New/Select.php b/app/Livewire/Project/New/Select.php
index c5dc13987..165e4b59e 100644
--- a/app/Livewire/Project/New/Select.php
+++ b/app/Livewire/Project/New/Select.php
@@ -65,7 +65,7 @@ public function mount()
$this->existingPostgresqlUrl = 'postgres://coolify:password@coolify-db:5432';
}
$projectUuid = data_get($this->parameters, 'project_uuid');
- $project = Project::whereUuid($projectUuid)->firstOrFail();
+ $project = Project::ownedByCurrentTeam()->whereUuid($projectUuid)->firstOrFail();
$this->environments = $project->environments;
$this->selectedEnvironment = $this->environments->where('uuid', data_get($this->parameters, 'environment_uuid'))->firstOrFail()->name;
@@ -79,7 +79,7 @@ public function mount()
$this->type = $queryType;
$this->server_id = $queryServerId;
$this->destination_uuid = $queryDestination;
- $this->server = Server::find($queryServerId);
+ $this->server = Server::ownedByCurrentTeam()->find($queryServerId);
$this->current_step = 'select-postgresql-type';
}
} catch (\Exception $e) {
diff --git a/app/Livewire/Project/New/SimpleDockerfile.php b/app/Livewire/Project/New/SimpleDockerfile.php
index 9cc4fbbe2..1073157e6 100644
--- a/app/Livewire/Project/New/SimpleDockerfile.php
+++ b/app/Livewire/Project/New/SimpleDockerfile.php
@@ -45,8 +45,8 @@ public function submit()
}
$destination_class = $destination->getMorphClass();
- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
- $environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
+ $project = Project::ownedByCurrentTeam()->where('uuid', $this->parameters['project_uuid'])->firstOrFail();
+ $environment = $project->environments()->where('uuid', $this->parameters['environment_uuid'])->firstOrFail();
$port = get_port_from_dockerfile($this->dockerfile);
if (! $port) {
diff --git a/app/Livewire/Project/Service/Index.php b/app/Livewire/Project/Service/Index.php
index c77a3a516..cb2d977bc 100644
--- a/app/Livewire/Project/Service/Index.php
+++ b/app/Livewire/Project/Service/Index.php
@@ -51,9 +51,9 @@ class Index extends Component
public bool $excludeFromStatus = false;
- public ?int $publicPort = null;
+ public mixed $publicPort = null;
- public ?int $publicPortTimeout = 3600;
+ public mixed $publicPortTimeout = 3600;
public bool $isPublic = false;
@@ -91,7 +91,7 @@ class Index extends Component
'description' => 'nullable',
'image' => 'required',
'excludeFromStatus' => 'required|boolean',
- 'publicPort' => 'nullable|integer',
+ 'publicPort' => 'nullable|integer|min:1|max:65535',
'publicPortTimeout' => 'nullable|integer|min:1',
'isPublic' => 'required|boolean',
'isLogDrainEnabled' => 'required|boolean',
@@ -160,8 +160,8 @@ private function syncDatabaseData(bool $toModel = false): void
$this->serviceDatabase->description = $this->description;
$this->serviceDatabase->image = $this->image;
$this->serviceDatabase->exclude_from_status = $this->excludeFromStatus;
- $this->serviceDatabase->public_port = $this->publicPort;
- $this->serviceDatabase->public_port_timeout = $this->publicPortTimeout;
+ $this->serviceDatabase->public_port = $this->publicPort ?: null;
+ $this->serviceDatabase->public_port_timeout = $this->publicPortTimeout ?: null;
$this->serviceDatabase->is_public = $this->isPublic;
$this->serviceDatabase->is_log_drain_enabled = $this->isLogDrainEnabled;
} else {
diff --git a/app/Livewire/Project/Service/Storage.php b/app/Livewire/Project/Service/Storage.php
index 12d8bcbc3..433c2b13c 100644
--- a/app/Livewire/Project/Service/Storage.php
+++ b/app/Livewire/Project/Service/Storage.php
@@ -2,7 +2,10 @@
namespace App\Livewire\Project\Service;
+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;
@@ -49,7 +52,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;
}
@@ -101,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;
@@ -138,7 +141,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 +152,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 +189,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/Livewire/Project/Shared/EnvironmentVariable/Add.php b/app/Livewire/Project/Shared/EnvironmentVariable/Add.php
index 73d5393b0..c51b27b6a 100644
--- a/app/Livewire/Project/Shared/EnvironmentVariable/Add.php
+++ b/app/Livewire/Project/Shared/EnvironmentVariable/Add.php
@@ -71,6 +71,7 @@ public function availableSharedVariables(): array
'team' => [],
'project' => [],
'environment' => [],
+ 'server' => [],
];
// Early return if no team
@@ -126,6 +127,66 @@ public function availableSharedVariables(): array
}
}
+ // Get server variables
+ $serverUuid = data_get($this->parameters, 'server_uuid');
+ if ($serverUuid) {
+ // If we have a specific server_uuid, show variables for that server
+ $server = \App\Models\Server::where('team_id', $team->id)
+ ->where('uuid', $serverUuid)
+ ->first();
+
+ if ($server) {
+ try {
+ $this->authorize('view', $server);
+ $result['server'] = $server->environment_variables()
+ ->pluck('key')
+ ->toArray();
+ } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ // User not authorized to view server variables
+ }
+ }
+ } else {
+ // For application environment variables, try to use the application's destination server
+ $applicationUuid = data_get($this->parameters, 'application_uuid');
+ if ($applicationUuid) {
+ $application = \App\Models\Application::whereRelation('environment.project.team', 'id', $team->id)
+ ->where('uuid', $applicationUuid)
+ ->with('destination.server')
+ ->first();
+
+ if ($application && $application->destination && $application->destination->server) {
+ try {
+ $this->authorize('view', $application->destination->server);
+ $result['server'] = $application->destination->server->environment_variables()
+ ->pluck('key')
+ ->toArray();
+ } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ // User not authorized to view server variables
+ }
+ }
+ } else {
+ // For service environment variables, try to use the service's server
+ $serviceUuid = data_get($this->parameters, 'service_uuid');
+ if ($serviceUuid) {
+ $service = \App\Models\Service::whereRelation('environment.project.team', 'id', $team->id)
+ ->where('uuid', $serviceUuid)
+ ->with('server')
+ ->first();
+
+ if ($service && $service->server) {
+ try {
+ $this->authorize('view', $service->server);
+ $result['server'] = $service->server->environment_variables()
+ ->pluck('key')
+ ->toArray();
+ } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ // User not authorized to view server variables
+ }
+ }
+ }
+ }
+ }
+
return $result;
}
diff --git a/app/Livewire/Project/Shared/EnvironmentVariable/Show.php b/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
index c567d96aa..4e8521f27 100644
--- a/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
+++ b/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
@@ -219,6 +219,7 @@ public function availableSharedVariables(): array
'team' => [],
'project' => [],
'environment' => [],
+ 'server' => [],
];
// Early return if no team
@@ -274,6 +275,66 @@ public function availableSharedVariables(): array
}
}
+ // Get server variables
+ $serverUuid = data_get($this->parameters, 'server_uuid');
+ if ($serverUuid) {
+ // If we have a specific server_uuid, show variables for that server
+ $server = \App\Models\Server::where('team_id', $team->id)
+ ->where('uuid', $serverUuid)
+ ->first();
+
+ if ($server) {
+ try {
+ $this->authorize('view', $server);
+ $result['server'] = $server->environment_variables()
+ ->pluck('key')
+ ->toArray();
+ } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ // User not authorized to view server variables
+ }
+ }
+ } else {
+ // For application environment variables, try to use the application's destination server
+ $applicationUuid = data_get($this->parameters, 'application_uuid');
+ if ($applicationUuid) {
+ $application = \App\Models\Application::whereRelation('environment.project.team', 'id', $team->id)
+ ->where('uuid', $applicationUuid)
+ ->with('destination.server')
+ ->first();
+
+ if ($application && $application->destination && $application->destination->server) {
+ try {
+ $this->authorize('view', $application->destination->server);
+ $result['server'] = $application->destination->server->environment_variables()
+ ->pluck('key')
+ ->toArray();
+ } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ // User not authorized to view server variables
+ }
+ }
+ } else {
+ // For service environment variables, try to use the service's server
+ $serviceUuid = data_get($this->parameters, 'service_uuid');
+ if ($serviceUuid) {
+ $service = \App\Models\Service::whereRelation('environment.project.team', 'id', $team->id)
+ ->where('uuid', $serviceUuid)
+ ->with('server')
+ ->first();
+
+ if ($service && $service->server) {
+ try {
+ $this->authorize('view', $service->server);
+ $result['server'] = $service->server->environment_variables()
+ ->pluck('key')
+ ->toArray();
+ } catch (\Illuminate\Auth\Access\AuthorizationException $e) {
+ // User not authorized to view server variables
+ }
+ }
+ }
+ }
+ }
+
return $result;
}
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/GetLogs.php b/app/Livewire/Project/Shared/GetLogs.php
index 22605e1bb..d0121bdc5 100644
--- a/app/Livewire/Project/Shared/GetLogs.php
+++ b/app/Livewire/Project/Shared/GetLogs.php
@@ -16,7 +16,9 @@
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
+use App\Support\ValidationPatterns;
use Illuminate\Support\Facades\Process;
+use Livewire\Attributes\Locked;
use Livewire\Component;
class GetLogs extends Component
@@ -29,12 +31,16 @@ class GetLogs extends Component
public string $errors = '';
+ #[Locked]
public Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse|null $resource = null;
+ #[Locked]
public ServiceApplication|ServiceDatabase|null $servicesubtype = null;
+ #[Locked]
public Server $server;
+ #[Locked]
public ?string $container = null;
public ?string $displayName = null;
@@ -54,7 +60,7 @@ class GetLogs extends Component
public function mount()
{
if (! is_null($this->resource)) {
- if ($this->resource->getMorphClass() === \App\Models\Application::class) {
+ if ($this->resource->getMorphClass() === Application::class) {
$this->showTimeStamps = $this->resource->settings->is_include_timestamps;
} else {
if ($this->servicesubtype) {
@@ -63,7 +69,7 @@ public function mount()
$this->showTimeStamps = $this->resource->is_include_timestamps;
}
}
- if ($this->resource?->getMorphClass() === \App\Models\Application::class) {
+ if ($this->resource?->getMorphClass() === Application::class) {
if (str($this->container)->contains('-pr-')) {
$this->pull_request = 'Pull Request: '.str($this->container)->afterLast('-pr-')->beforeLast('_')->value();
}
@@ -74,11 +80,11 @@ public function mount()
public function instantSave()
{
if (! is_null($this->resource)) {
- if ($this->resource->getMorphClass() === \App\Models\Application::class) {
+ if ($this->resource->getMorphClass() === Application::class) {
$this->resource->settings->is_include_timestamps = $this->showTimeStamps;
$this->resource->settings->save();
}
- if ($this->resource->getMorphClass() === \App\Models\Service::class) {
+ if ($this->resource->getMorphClass() === Service::class) {
$serviceName = str($this->container)->beforeLast('-')->value();
$subType = $this->resource->applications()->where('name', $serviceName)->first();
if ($subType) {
@@ -118,10 +124,20 @@ public function toggleStreamLogs()
public function getLogs($refresh = false)
{
+ if (! Server::ownedByCurrentTeam()->where('id', $this->server->id)->exists()) {
+ $this->outputs = 'Unauthorized.';
+
+ return;
+ }
if (! $this->server->isFunctional()) {
return;
}
- if (! $refresh && ! $this->expandByDefault && ($this->resource?->getMorphClass() === \App\Models\Service::class || str($this->container)->contains('-pr-'))) {
+ if ($this->container && ! ValidationPatterns::isValidContainerName($this->container)) {
+ $this->outputs = 'Invalid container name.';
+
+ return;
+ }
+ if (! $refresh && ! $this->expandByDefault && ($this->resource?->getMorphClass() === Service::class || str($this->container)->contains('-pr-'))) {
return;
}
if ($this->numberOfLines <= 0 || is_null($this->numberOfLines)) {
@@ -194,9 +210,15 @@ public function copyLogs(): string
public function downloadAllLogs(): string
{
+ if (! Server::ownedByCurrentTeam()->where('id', $this->server->id)->exists()) {
+ return '';
+ }
if (! $this->server->isFunctional() || ! $this->container) {
return '';
}
+ if (! ValidationPatterns::isValidContainerName($this->container)) {
+ return '';
+ }
if ($this->showTimeStamps) {
if ($this->server->isSwarm()) {
diff --git a/app/Livewire/Project/Shared/ResourceLimits.php b/app/Livewire/Project/Shared/ResourceLimits.php
index 0b3840289..8a14dc10c 100644
--- a/app/Livewire/Project/Shared/ResourceLimits.php
+++ b/app/Livewire/Project/Shared/ResourceLimits.php
@@ -3,6 +3,7 @@
namespace App\Livewire\Project\Shared;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+use Illuminate\Validation\ValidationException;
use Livewire\Component;
class ResourceLimits extends Component
@@ -16,24 +17,24 @@ class ResourceLimits extends Component
public ?string $limitsCpuset = null;
- public ?int $limitsCpuShares = null;
+ public mixed $limitsCpuShares = null;
public string $limitsMemory;
public string $limitsMemorySwap;
- public int $limitsMemorySwappiness;
+ public mixed $limitsMemorySwappiness = 0;
public string $limitsMemoryReservation;
protected $rules = [
- 'limitsMemory' => 'required|string',
- 'limitsMemorySwap' => 'required|string',
+ 'limitsMemory' => ['required', 'string', 'regex:/^(0|\d+[bBkKmMgG])$/'],
+ 'limitsMemorySwap' => ['required', 'string', 'regex:/^(0|\d+[bBkKmMgG])$/'],
'limitsMemorySwappiness' => 'required|integer|min:0|max:100',
- 'limitsMemoryReservation' => 'required|string',
- 'limitsCpus' => 'nullable',
- 'limitsCpuset' => 'nullable',
- 'limitsCpuShares' => 'nullable',
+ 'limitsMemoryReservation' => ['required', 'string', 'regex:/^(0|\d+[bBkKmMgG])$/'],
+ 'limitsCpus' => ['nullable', 'regex:/^\d*\.?\d+$/'],
+ 'limitsCpuset' => ['nullable', 'regex:/^\d+([,-]\d+)*$/'],
+ 'limitsCpuShares' => 'nullable|integer|min:0',
];
protected $validationAttributes = [
@@ -46,6 +47,19 @@ class ResourceLimits extends Component
'limitsCpuShares' => 'cpu shares',
];
+ protected $messages = [
+ 'limitsMemory.regex' => 'Maximum Memory Limit must be a number followed by a unit (b, k, m, g). Example: 256m, 1g. Use 0 for unlimited.',
+ 'limitsMemorySwap.regex' => 'Maximum Swap Limit must be a number followed by a unit (b, k, m, g). Example: 256m, 1g. Use 0 for unlimited.',
+ 'limitsMemoryReservation.regex' => 'Soft Memory Limit must be a number followed by a unit (b, k, m, g). Example: 256m, 1g. Use 0 for unlimited.',
+ 'limitsCpus.regex' => 'Number of CPUs must be a number (integer or decimal). Example: 0.5, 2.',
+ 'limitsCpuset.regex' => 'CPU sets must be a comma-separated list of CPU numbers or ranges. Example: 0-2 or 0,1,3.',
+ 'limitsMemorySwappiness.integer' => 'Swappiness must be a whole number between 0 and 100.',
+ 'limitsMemorySwappiness.min' => 'Swappiness must be between 0 and 100.',
+ 'limitsMemorySwappiness.max' => 'Swappiness must be between 0 and 100.',
+ 'limitsCpuShares.integer' => 'CPU Weight must be a whole number.',
+ 'limitsCpuShares.min' => 'CPU Weight must be a positive number.',
+ ];
+
/**
* Sync data between component properties and model
*
@@ -57,10 +71,10 @@ private function syncData(bool $toModel = false): void
// Sync TO model (before save)
$this->resource->limits_cpus = $this->limitsCpus;
$this->resource->limits_cpuset = $this->limitsCpuset;
- $this->resource->limits_cpu_shares = $this->limitsCpuShares;
+ $this->resource->limits_cpu_shares = (int) $this->limitsCpuShares;
$this->resource->limits_memory = $this->limitsMemory;
$this->resource->limits_memory_swap = $this->limitsMemorySwap;
- $this->resource->limits_memory_swappiness = $this->limitsMemorySwappiness;
+ $this->resource->limits_memory_swappiness = (int) $this->limitsMemorySwappiness;
$this->resource->limits_memory_reservation = $this->limitsMemoryReservation;
} else {
// Sync FROM model (on load/refresh)
@@ -91,7 +105,7 @@ public function submit()
if (! $this->limitsMemorySwap) {
$this->limitsMemorySwap = '0';
}
- if (is_null($this->limitsMemorySwappiness)) {
+ if ($this->limitsMemorySwappiness === '' || is_null($this->limitsMemorySwappiness)) {
$this->limitsMemorySwappiness = 60;
}
if (! $this->limitsMemoryReservation) {
@@ -103,7 +117,7 @@ public function submit()
if ($this->limitsCpuset === '') {
$this->limitsCpuset = null;
}
- if (is_null($this->limitsCpuShares)) {
+ if ($this->limitsCpuShares === '' || is_null($this->limitsCpuShares)) {
$this->limitsCpuShares = 1024;
}
@@ -112,6 +126,12 @@ public function submit()
$this->syncData(true);
$this->resource->save();
$this->dispatch('success', 'Resource limits updated.');
+ } catch (ValidationException $e) {
+ foreach ($e->validator->errors()->all() as $message) {
+ $this->dispatch('error', $message);
+ }
+
+ return;
} catch (\Throwable $e) {
return handleError($e, $this);
}
diff --git a/app/Livewire/Project/Shared/ResourceOperations.php b/app/Livewire/Project/Shared/ResourceOperations.php
index e769e4bcb..f4813dd4c 100644
--- a/app/Livewire/Project/Shared/ResourceOperations.php
+++ b/app/Livewire/Project/Shared/ResourceOperations.php
@@ -7,9 +7,18 @@
use App\Actions\Service\StartService;
use App\Actions\Service\StopService;
use App\Jobs\VolumeCloneJob;
+use App\Models\Application;
use App\Models\Environment;
use App\Models\Project;
+use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDocker;
+use App\Models\StandaloneDragonfly;
+use App\Models\StandaloneKeydb;
+use App\Models\StandaloneMariadb;
+use App\Models\StandaloneMongodb;
+use App\Models\StandaloneMysql;
+use App\Models\StandalonePostgresql;
+use App\Models\StandaloneRedis;
use App\Models\SwarmDocker;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
@@ -60,7 +69,7 @@ public function cloneTo($destination_id)
$uuid = (string) new Cuid2;
$server = $new_destination->server;
- if ($this->resource->getMorphClass() === \App\Models\Application::class) {
+ if ($this->resource->getMorphClass() === Application::class) {
$new_resource = clone_application($this->resource, $new_destination, ['uuid' => $uuid], $this->cloneVolumeData);
$route = route('project.application.configuration', [
@@ -71,14 +80,14 @@ public function cloneTo($destination_id)
return redirect()->to($route);
} elseif (
- $this->resource->getMorphClass() === \App\Models\StandalonePostgresql::class ||
- $this->resource->getMorphClass() === \App\Models\StandaloneMongodb::class ||
- $this->resource->getMorphClass() === \App\Models\StandaloneMysql::class ||
- $this->resource->getMorphClass() === \App\Models\StandaloneMariadb::class ||
- $this->resource->getMorphClass() === \App\Models\StandaloneRedis::class ||
- $this->resource->getMorphClass() === \App\Models\StandaloneKeydb::class ||
- $this->resource->getMorphClass() === \App\Models\StandaloneDragonfly::class ||
- $this->resource->getMorphClass() === \App\Models\StandaloneClickhouse::class
+ $this->resource->getMorphClass() === StandalonePostgresql::class ||
+ $this->resource->getMorphClass() === StandaloneMongodb::class ||
+ $this->resource->getMorphClass() === StandaloneMysql::class ||
+ $this->resource->getMorphClass() === StandaloneMariadb::class ||
+ $this->resource->getMorphClass() === StandaloneRedis::class ||
+ $this->resource->getMorphClass() === StandaloneKeydb::class ||
+ $this->resource->getMorphClass() === StandaloneDragonfly::class ||
+ $this->resource->getMorphClass() === StandaloneClickhouse::class
) {
$uuid = (string) new Cuid2;
$new_resource = $this->resource->replicate([
@@ -133,6 +142,7 @@ public function cloneTo($destination_id)
'id',
'created_at',
'updated_at',
+ 'uuid',
])->fill([
'name' => $newName,
'resource_id' => $new_resource->id,
@@ -254,9 +264,9 @@ public function cloneTo($destination_id)
}
foreach ($new_resource->applications() as $application) {
- $application->update([
+ $application->fill([
'status' => 'exited',
- ]);
+ ])->save();
$persistentVolumes = $application->persistentStorages()->get();
foreach ($persistentVolumes as $volume) {
@@ -271,6 +281,7 @@ public function cloneTo($destination_id)
'id',
'created_at',
'updated_at',
+ 'uuid',
])->fill([
'name' => $newName,
'resource_id' => $application->id,
@@ -296,9 +307,9 @@ public function cloneTo($destination_id)
}
foreach ($new_resource->databases() as $database) {
- $database->update([
+ $database->fill([
'status' => 'exited',
- ]);
+ ])->save();
$persistentVolumes = $database->persistentStorages()->get();
foreach ($persistentVolumes as $volume) {
@@ -313,6 +324,7 @@ public function cloneTo($destination_id)
'id',
'created_at',
'updated_at',
+ 'uuid',
])->fill([
'name' => $newName,
'resource_id' => $database->id,
@@ -354,9 +366,9 @@ public function moveTo($environment_id)
try {
$this->authorize('update', $this->resource);
$new_environment = Environment::ownedByCurrentTeam()->findOrFail($environment_id);
- $this->resource->update([
+ $this->resource->fill([
'environment_id' => $environment_id,
- ]);
+ ])->save();
if ($this->resource->type() === 'application') {
$route = route('project.application.configuration', [
'project_uuid' => $new_environment->project->uuid,
diff --git a/app/Livewire/Project/Shared/ScheduledTask/Show.php b/app/Livewire/Project/Shared/ScheduledTask/Show.php
index 02c13a66c..882737f09 100644
--- a/app/Livewire/Project/Shared/ScheduledTask/Show.php
+++ b/app/Livewire/Project/Shared/ScheduledTask/Show.php
@@ -52,9 +52,15 @@ class Show extends Component
#[Locked]
public string $task_uuid;
- public function mount(string $task_uuid, string $project_uuid, string $environment_uuid, ?string $application_uuid = null, ?string $service_uuid = null)
+ public function mount()
{
try {
+ $task_uuid = request()->route('task_uuid');
+ $project_uuid = request()->route('project_uuid');
+ $environment_uuid = request()->route('environment_uuid');
+ $application_uuid = request()->route('application_uuid');
+ $service_uuid = request()->route('service_uuid');
+
$this->task_uuid = $task_uuid;
if ($application_uuid) {
$this->type = 'application';
@@ -105,6 +111,19 @@ public function syncData(bool $toModel = false)
}
}
+ public function toggleEnabled()
+ {
+ try {
+ $this->authorize('update', $this->resource);
+ $this->isEnabled = ! $this->isEnabled;
+ $this->task->enabled = $this->isEnabled;
+ $this->task->save();
+ $this->dispatch('success', $this->isEnabled ? 'Scheduled task enabled.' : 'Scheduled task disabled.');
+ } catch (\Exception $e) {
+ return handleError($e);
+ }
+ }
+
public function instantSave()
{
try {
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/Livewire/Server/Advanced.php b/app/Livewire/Server/Advanced.php
index dba1b4903..b39da5e5a 100644
--- a/app/Livewire/Server/Advanced.php
+++ b/app/Livewire/Server/Advanced.php
@@ -15,17 +15,17 @@ class Advanced extends Component
#[Validate(['string'])]
public string $serverDiskUsageCheckFrequency = '0 23 * * *';
- #[Validate(['integer', 'min:1', 'max:99'])]
- public int $serverDiskUsageNotificationThreshold = 50;
+ #[Validate(['required', 'integer', 'min:1', 'max:99'])]
+ public int|string $serverDiskUsageNotificationThreshold = 50;
- #[Validate(['integer', 'min:1'])]
- public int $concurrentBuilds = 1;
+ #[Validate(['required', 'integer', 'min:1'])]
+ public int|string $concurrentBuilds = 1;
- #[Validate(['integer', 'min:1'])]
- public int $dynamicTimeout = 1;
+ #[Validate(['required', 'integer', 'min:1'])]
+ public int|string $dynamicTimeout = 1;
- #[Validate(['integer', 'min:1'])]
- public int $deploymentQueueLimit = 25;
+ #[Validate(['required', 'integer', 'min:1'])]
+ public int|string $deploymentQueueLimit = 25;
public function mount(string $server_uuid)
{
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;
}
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/Proxy.php b/app/Livewire/Server/Proxy.php
index d5f30fca0..c2d8205ef 100644
--- a/app/Livewire/Server/Proxy.php
+++ b/app/Livewire/Server/Proxy.php
@@ -6,6 +6,7 @@
use App\Actions\Proxy\SaveProxyConfiguration;
use App\Enums\ProxyTypes;
use App\Models\Server;
+use App\Rules\SafeExternalUrl;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
@@ -41,9 +42,13 @@ public function getListeners()
];
}
- protected $rules = [
- 'generateExactLabels' => 'required|boolean',
- ];
+ protected function rules()
+ {
+ return [
+ 'generateExactLabels' => 'required|boolean',
+ 'redirectUrl' => ['nullable', new SafeExternalUrl],
+ ];
+ }
public function mount()
{
@@ -147,6 +152,7 @@ public function submit()
{
try {
$this->authorize('update', $this->server);
+ $this->validate();
SaveProxyConfiguration::run($this->server, $this->proxySettings);
$this->server->proxy->redirect_url = $this->redirectUrl;
$this->server->save();
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/Livewire/Server/Sentinel.php b/app/Livewire/Server/Sentinel.php
index dff379ae1..a4b35891b 100644
--- a/app/Livewire/Server/Sentinel.php
+++ b/app/Livewire/Server/Sentinel.php
@@ -25,13 +25,13 @@ class Sentinel extends Component
public ?string $sentinelUpdatedAt = null;
#[Validate(['required', 'integer', 'min:1'])]
- public int $sentinelMetricsRefreshRateSeconds;
+ public int|string $sentinelMetricsRefreshRateSeconds;
#[Validate(['required', 'integer', 'min:1'])]
- public int $sentinelMetricsHistoryDays;
+ public int|string $sentinelMetricsHistoryDays;
#[Validate(['required', 'integer', 'min:10'])]
- public int $sentinelPushIntervalSeconds;
+ public int|string $sentinelPushIntervalSeconds;
#[Validate(['nullable', 'url'])]
public ?string $sentinelCustomUrl = null;
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.
Check if you used the right extension (.yaml or .yml) in the compose file name.");
+ throw new RuntimeException("Docker Compose file not found at: $workdir$composeFile (branch: {$this->git_branch})
Check if you used the right extension (.yaml or .yml) in the compose file name.");
}
if (str($e->getMessage())->contains('fatal: repository') && str($e->getMessage())->contains('does not exist')) {
if ($this->deploymentType() === 'deploy_key') {
- throw new \RuntimeException('Your deploy key does not have access to the repository. Please check your deploy key and try again.');
+ throw new RuntimeException('Your deploy key does not have access to the repository. Please check your deploy key and try again.');
}
- throw new \RuntimeException('Repository does not exist. Please check your repository URL and try again.');
+ throw new RuntimeException('Repository does not exist. Please check your repository URL and try again.');
}
- throw new \RuntimeException($e->getMessage());
+ throw new RuntimeException('Failed to read the Docker Compose file from the repository.');
} finally {
// Cleanup only - restoration happens in catch block
$commands = collect([
@@ -1793,7 +1886,7 @@ public function loadComposeFile($isInit = false, ?string $restoreBaseDirectory =
$this->base_directory = $initialBaseDirectory;
$this->save();
- throw new \RuntimeException("Docker Compose file not found at: $workdir$composeFile (branch: {$this->git_branch})
Check if you used the right extension (.yaml or .yml) in the compose file name.");
+ throw new RuntimeException("Docker Compose file not found at: $workdir$composeFile (branch: {$this->git_branch})
diff --git a/resources/views/emails/server-force-disabled.blade.php b/resources/views/emails/server-force-disabled.blade.php
index 805df3296..4ab46b5a0 100644
--- a/resources/views/emails/server-force-disabled.blade.php
+++ b/resources/views/emails/server-force-disabled.blade.php
@@ -1,5 +1,5 @@
Your server ({{ $name }}) disabled because it is not paid! All automations and integrations are stopped.
- Please update your subscription to enable the server again [here](https://app.coolify.io/subscriptions).
+ Please update your subscription to enable the server again [here](https://app.coolify.io/subscription).
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/resources/views/layouts/base.blade.php b/resources/views/layouts/base.blade.php
index 2b4ca6054..33968ee32 100644
--- a/resources/views/layouts/base.blade.php
+++ b/resources/views/layouts/base.blade.php
@@ -203,30 +203,6 @@ function checkTheme() {
let checkHealthInterval = null;
let checkIfIamDeadInterval = null;
- function changePasswordFieldType(event) {
- let element = event.target
- for (let i = 0; i < 10; i++) {
- if (element.className === "relative") {
- break;
- }
- element = element.parentElement;
- }
- element = element.children[1];
- if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
- if (element.type === 'password') {
- element.type = 'text';
- if (element.disabled) return;
- element.classList.add('truncate');
- this.type = 'text';
- } else {
- element.type = 'password';
- if (element.disabled) return;
- element.classList.remove('truncate');
- this.type = 'password';
- }
- }
- }
-
function copyToClipboard(text) {
navigator?.clipboard?.writeText(text) && window.Livewire.dispatch('success', 'Copied to clipboard.');
}
@@ -326,4 +302,4 @@ function copyToClipboard(text) {