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 +
merge(['class' => 'alert alert-'.$type]) }}> + {{ $message }} +
+``` + +## 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 +
+ @csrf + +
+``` + +## 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
Content adapts to color scheme
-
+``` ## Common Patterns ### Flexbox Layout - + +```html
Left content
Right content
-
+``` ### Grid Layout - + +```html
Card 1
Card 2
Card 3
-
+``` ## 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 +
merge(['class' => 'alert alert-'.$type]) }}> + {{ $message }} +
+``` + +## 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 +
+ @csrf + +
+``` + +## 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
Content adapts to color scheme
-
+``` ## Common Patterns ### Flexbox Layout - + +```html
Left content
Right content
-
+``` ### Grid Layout - + +```html
Card 1
Card 2
Card 3
-
+``` ## 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 +
merge(['class' => 'alert alert-'.$type]) }}> + {{ $message }} +
+``` + +## 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 +
+ @csrf + +
+``` + +## 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
Content adapts to color scheme
-
+``` ## Common Patterns ### Flexbox Layout - + +```html
Left content
Right content
-
+``` ### Grid Layout - + +```html
Card 1
Card 2
Card 3
-
+``` ## Common Pitfalls diff --git a/.env.development.example b/.env.development.example index b0b15f324..594b89201 100644 --- a/.env.development.example +++ b/.env.development.example @@ -24,6 +24,10 @@ RAY_ENABLED=false # Enable Laravel Telescope for debugging TELESCOPE_ENABLED=false +# Enable Laravel Nightwatch monitoring +NIGHTWATCH_ENABLED=false +NIGHTWATCH_TOKEN= + # Selenium Driver URL for Dusk DUSK_DRIVER_URL=http://selenium:4444 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/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/README.md b/README.md index b7aefe16a..a5aa69343 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ ### Big Sponsors * [Arcjet](https://arcjet.com?ref=coolify.io) - Advanced web security and performance solutions * [BC Direct](https://bc.direct?ref=coolify.io) - Your trusted technology consulting partner * [Blacksmith](https://blacksmith.sh?ref=coolify.io) - Infrastructure automation platform -* [Brand.dev](https://brand.dev?ref=coolify.io) - API to personalize your product with logos, colors, and company info from any domain +* [Context.dev](https://context.dev?ref=coolify.io) - API to personalize your product with logos, colors, and company info from any domain * [ByteBase](https://www.bytebase.com?ref=coolify.io) - Database CI/CD and Security at Scale * [CodeRabbit](https://coderabbit.ai?ref=coolify.io) - Cut Code Review Time & Bugs in Half * [COMIT](https://comit.international?ref=coolify.io) - New York Times award–winning contractor @@ -90,6 +90,7 @@ ### Big Sponsors * [Logto](https://logto.io?ref=coolify.io) - The better identity infrastructure for developers * [Macarne](https://macarne.com?ref=coolify.io) - Best IP Transit & Carrier Ethernet Solutions for Simplified Network Connectivity * [Mobb](https://vibe.mobb.ai/?ref=coolify.io) - Secure Your AI-Generated Code to Unlock Dev Productivity +* [PetroSky Cloud](https://petrosky.io?ref=coolify.io) - Open source cloud deployment solutions * [PFGLabs](https://pfglabs.com?ref=coolify.io) - Build Real Projects with Golang * [Ramnode](https://ramnode.com/?ref=coolify.io) - High Performance Cloud VPS Hosting * [SaasyKit](https://saasykit.com?ref=coolify.io) - Complete SaaS starter kit for developers 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/Proxy/GetProxyConfiguration.php b/app/Actions/Proxy/GetProxyConfiguration.php index de44b476f..159f12252 100644 --- a/app/Actions/Proxy/GetProxyConfiguration.php +++ b/app/Actions/Proxy/GetProxyConfiguration.php @@ -2,10 +2,12 @@ namespace App\Actions\Proxy; +use App\Enums\ProxyTypes; use App\Models\Server; use App\Services\ProxyDashboardCacheService; use Illuminate\Support\Facades\Log; use Lorisleiva\Actions\Concerns\AsAction; +use Symfony\Component\Yaml\Yaml; class GetProxyConfiguration { @@ -24,6 +26,17 @@ public function handle(Server $server, bool $forceRegenerate = false): string // Primary source: database $proxy_configuration = $server->proxy->get('last_saved_proxy_configuration'); + // Validate stored config matches current proxy type + if (! empty(trim($proxy_configuration ?? ''))) { + if (! $this->configMatchesProxyType($proxyType, $proxy_configuration)) { + Log::warning('Stored proxy config does not match current proxy type, will regenerate', [ + 'server_id' => $server->id, + 'proxy_type' => $proxyType, + ]); + $proxy_configuration = null; + } + } + // Backfill: existing servers may not have DB config yet — read from disk once if (empty(trim($proxy_configuration ?? ''))) { $proxy_configuration = $this->backfillFromDisk($server); @@ -55,6 +68,29 @@ public function handle(Server $server, bool $forceRegenerate = false): string return $proxy_configuration; } + /** + * Check that the stored docker-compose YAML contains the expected service + * for the server's current proxy type. Returns false if the config belongs + * to a different proxy type (e.g. Traefik config on a CADDY server). + */ + private function configMatchesProxyType(string $proxyType, string $configuration): bool + { + try { + $yaml = Yaml::parse($configuration); + $services = data_get($yaml, 'services', []); + + return match ($proxyType) { + ProxyTypes::TRAEFIK->value => isset($services['traefik']), + ProxyTypes::CADDY->value => isset($services['caddy']), + ProxyTypes::NGINX->value => isset($services['nginx']), + default => true, + }; + } catch (\Throwable $e) { + // If YAML is unparseable, don't block — let the existing flow handle it + return true; + } + } + /** * Backfill: read config from disk for servers that predate DB storage. * Stores the result in the database so future reads skip SSH entirely. diff --git a/app/Actions/Server/InstallDocker.php b/app/Actions/Server/InstallDocker.php index 31e582c9b..2e08ec6ad 100644 --- a/app/Actions/Server/InstallDocker.php +++ b/app/Actions/Server/InstallDocker.php @@ -11,11 +11,8 @@ class InstallDocker { use AsAction; - private string $dockerVersion; - public function handle(Server $server) { - $this->dockerVersion = config('constants.docker.minimum_required_version'); $supported_os_type = $server->validateOS(); if (! $supported_os_type) { throw new \Exception('Server OS type is not supported for automated installation. Please install Docker manually before continuing: documentation.'); @@ -118,7 +115,7 @@ public function handle(Server $server) private function getDebianDockerInstallCommand(): string { - return "curl --max-time 300 --retry 3 https://releases.rancher.com/install-docker/{$this->dockerVersion}.sh | sh || curl --max-time 300 --retry 3 https://get.docker.com | sh -s -- --version {$this->dockerVersion} || (". + return 'curl -fsSL https://get.docker.com | sh || ('. '. /etc/os-release && '. 'install -m 0755 -d /etc/apt/keyrings && '. 'curl -fsSL https://download.docker.com/linux/${ID}/gpg -o /etc/apt/keyrings/docker.asc && '. @@ -131,7 +128,7 @@ private function getDebianDockerInstallCommand(): string private function getRhelDockerInstallCommand(): string { - return "curl https://releases.rancher.com/install-docker/{$this->dockerVersion}.sh | sh || curl https://get.docker.com | sh -s -- --version {$this->dockerVersion} || (". + return 'curl -fsSL https://get.docker.com | sh || ('. 'dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo && '. 'dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin && '. 'systemctl start docker && '. @@ -141,7 +138,7 @@ private function getRhelDockerInstallCommand(): string private function getSuseDockerInstallCommand(): string { - return "curl https://releases.rancher.com/install-docker/{$this->dockerVersion}.sh | sh || curl https://get.docker.com | sh -s -- --version {$this->dockerVersion} || (". + return 'curl -fsSL https://get.docker.com | sh || ('. 'zypper addrepo https://download.docker.com/linux/sles/docker-ce.repo && '. 'zypper refresh && '. 'zypper install -y --no-confirm docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin && '. @@ -152,10 +149,6 @@ private function getSuseDockerInstallCommand(): string private function getArchDockerInstallCommand(): string { - // Use -Syu to perform full system upgrade before installing Docker - // Partial upgrades (-Sy without -u) are discouraged on Arch Linux - // as they can lead to broken dependencies and system instability - // Use --needed to skip reinstalling packages that are already up-to-date (idempotent) return 'pacman -Syu --noconfirm --needed docker docker-compose && '. 'systemctl enable docker.service && '. 'systemctl start docker.service'; @@ -163,6 +156,6 @@ private function getArchDockerInstallCommand(): string private function getGenericDockerInstallCommand(): string { - return "curl --max-time 300 --retry 3 https://releases.rancher.com/install-docker/{$this->dockerVersion}.sh | sh || curl --max-time 300 --retry 3 https://get.docker.com | sh -s -- --version {$this->dockerVersion}"; + return 'curl -fsSL https://get.docker.com | sh'; } } 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/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/ScheduledJobDiagnostics.php b/app/Console/Commands/ScheduledJobDiagnostics.php new file mode 100644 index 000000000..77881284c --- /dev/null +++ b/app/Console/Commands/ScheduledJobDiagnostics.php @@ -0,0 +1,255 @@ +option('type'); + $serverFilter = $this->option('server'); + + $this->outputHeartbeat(); + + if (in_array($type, ['all', 'docker-cleanup'])) { + $this->inspectDockerCleanups($serverFilter); + } + + if (in_array($type, ['all', 'backups'])) { + $this->inspectBackups(); + } + + if (in_array($type, ['all', 'tasks'])) { + $this->inspectTasks(); + } + + if (in_array($type, ['all', 'server-jobs'])) { + $this->inspectServerJobs($serverFilter); + } + + return self::SUCCESS; + } + + private function outputHeartbeat(): void + { + $heartbeat = Cache::get('scheduled-job-manager:heartbeat'); + if ($heartbeat) { + $age = Carbon::parse($heartbeat)->diffForHumans(); + $this->info("Scheduler heartbeat: {$heartbeat} ({$age})"); + } else { + $this->error('Scheduler heartbeat: MISSING — ScheduledJobManager may not be running'); + } + $this->newLine(); + } + + private function inspectDockerCleanups(?string $serverFilter): void + { + $this->info('=== Docker Cleanup Jobs ==='); + + $servers = $this->getServers($serverFilter); + + $rows = []; + foreach ($servers as $server) { + $frequency = data_get($server->settings, 'docker_cleanup_frequency', '0 * * * *'); + if (isset(VALID_CRON_STRINGS[$frequency])) { + $frequency = VALID_CRON_STRINGS[$frequency]; + } + + $dedupKey = "docker-cleanup:{$server->id}"; + $cacheValue = Cache::get($dedupKey); + $timezone = data_get($server->settings, 'server_timezone', config('app.timezone')); + + if (validate_timezone($timezone) === false) { + $timezone = config('app.timezone'); + } + + $wouldFire = shouldRunCronNow($frequency, $timezone, $dedupKey); + + $lastExecution = DockerCleanupExecution::where('server_id', $server->id) + ->latest() + ->first(); + + $rows[] = [ + $server->id, + $server->name, + $timezone, + $frequency, + $dedupKey, + $cacheValue ?? '', + $wouldFire ? 'YES' : 'no', + $lastExecution ? $lastExecution->status.' @ '.$lastExecution->created_at : 'never', + ]; + } + + $this->table( + ['ID', 'Server', 'TZ', 'Frequency', 'Dedup Key', 'Cache Value', 'Would Fire', 'Last Execution'], + $rows + ); + $this->newLine(); + } + + private function inspectBackups(): void + { + $this->info('=== Scheduled Backups ==='); + + $backups = ScheduledDatabaseBackup::with(['database']) + ->where('enabled', true) + ->get(); + + $rows = []; + foreach ($backups as $backup) { + $server = $backup->server(); + $frequency = $backup->frequency; + if (isset(VALID_CRON_STRINGS[$frequency])) { + $frequency = VALID_CRON_STRINGS[$frequency]; + } + + $dedupKey = "scheduled-backup:{$backup->id}"; + $cacheValue = Cache::get($dedupKey); + $timezone = $server ? data_get($server->settings, 'server_timezone', config('app.timezone')) : config('app.timezone'); + + if (validate_timezone($timezone) === false) { + $timezone = config('app.timezone'); + } + + $wouldFire = shouldRunCronNow($frequency, $timezone, $dedupKey); + + $rows[] = [ + $backup->id, + $backup->database_type ?? 'unknown', + $server?->name ?? 'N/A', + $frequency, + $cacheValue ?? '', + $wouldFire ? 'YES' : 'no', + ]; + } + + $this->table( + ['Backup ID', 'DB Type', 'Server', 'Frequency', 'Cache Value', 'Would Fire'], + $rows + ); + $this->newLine(); + } + + private function inspectTasks(): void + { + $this->info('=== Scheduled Tasks ==='); + + $tasks = ScheduledTask::with(['service', 'application']) + ->where('enabled', true) + ->get(); + + $rows = []; + foreach ($tasks as $task) { + $server = $task->server(); + $frequency = $task->frequency; + if (isset(VALID_CRON_STRINGS[$frequency])) { + $frequency = VALID_CRON_STRINGS[$frequency]; + } + + $dedupKey = "scheduled-task:{$task->id}"; + $cacheValue = Cache::get($dedupKey); + $timezone = $server ? data_get($server->settings, 'server_timezone', config('app.timezone')) : config('app.timezone'); + + if (validate_timezone($timezone) === false) { + $timezone = config('app.timezone'); + } + + $wouldFire = shouldRunCronNow($frequency, $timezone, $dedupKey); + + $rows[] = [ + $task->id, + $task->name, + $server?->name ?? 'N/A', + $frequency, + $cacheValue ?? '', + $wouldFire ? 'YES' : 'no', + ]; + } + + $this->table( + ['Task ID', 'Name', 'Server', 'Frequency', 'Cache Value', 'Would Fire'], + $rows + ); + $this->newLine(); + } + + private function inspectServerJobs(?string $serverFilter): void + { + $this->info('=== Server Manager Jobs ==='); + + $servers = $this->getServers($serverFilter); + + $rows = []; + foreach ($servers as $server) { + $timezone = data_get($server->settings, 'server_timezone', config('app.timezone')); + if (validate_timezone($timezone) === false) { + $timezone = config('app.timezone'); + } + + $dedupKeys = [ + "sentinel-restart:{$server->id}" => '0 0 * * *', + "server-patch-check:{$server->id}" => '0 0 * * 0', + "server-check:{$server->id}" => isCloud() ? '*/5 * * * *' : '* * * * *', + "server-storage-check:{$server->id}" => data_get($server->settings, 'server_disk_usage_check_frequency', '0 23 * * *'), + ]; + + foreach ($dedupKeys as $dedupKey => $frequency) { + if (isset(VALID_CRON_STRINGS[$frequency])) { + $frequency = VALID_CRON_STRINGS[$frequency]; + } + + $cacheValue = Cache::get($dedupKey); + $wouldFire = shouldRunCronNow($frequency, $timezone, $dedupKey); + + $rows[] = [ + $server->id, + $server->name, + $dedupKey, + $frequency, + $cacheValue ?? '', + $wouldFire ? 'YES' : 'no', + ]; + } + } + + $this->table( + ['Server ID', 'Server', 'Dedup Key', 'Frequency', 'Cache Value', 'Would Fire'], + $rows + ); + $this->newLine(); + } + + private function getServers(?string $serverFilter): \Illuminate\Support\Collection + { + $query = Server::with('settings')->where('ip', '!=', '1.2.3.4'); + + if ($serverFilter) { + $query->where('id', $serverFilter); + } + + if (isCloud()) { + $servers = $query->whereRelation('team.subscription', 'stripe_invoice_paid', true)->get(); + $own = Team::find(0)?->servers()->with('settings')->get() ?? collect(); + + return $servers->merge($own); + } + + return $query->get(); + } +} 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 3444f9f14..ad1f50ea2 100644 --- a/app/Http/Controllers/Api/ApplicationsController.php +++ b/app/Http/Controllers/Api/ApplicationsController.php @@ -11,6 +11,8 @@ use App\Models\Application; use App\Models\EnvironmentVariable; use App\Models\GithubApp; +use App\Models\LocalFileVolume; +use App\Models\LocalPersistentVolume; use App\Models\PrivateKey; use App\Models\Project; use App\Models\Server; @@ -18,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; @@ -1000,7 +1003,7 @@ private function create_application(Request $request, $type) $this->authorize('create', Application::class); $return = validateIncomingRequest($request); - if ($return instanceof \Illuminate\Http\JsonResponse) { + if ($return instanceof JsonResponse) { return $return; } $allowedFields = ['project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'type', 'name', 'description', 'is_static', 'is_spa', 'is_auto_deploy_enabled', 'is_force_https_enabled', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'private_key_uuid', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'custom_network_aliases', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_type', 'health_check_command', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'redirect', 'github_app_uuid', 'instant_deploy', 'dockerfile', 'dockerfile_location', 'docker_compose_location', 'docker_compose_raw', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'watch_paths', 'use_build_server', 'static_image', 'custom_nginx_configuration', 'is_http_basic_auth_enabled', 'http_basic_auth_username', 'http_basic_auth_password', 'connect_to_docker_network', 'force_domain_override', 'autogenerate_domain', 'is_container_label_escape_enabled']; @@ -1148,7 +1151,7 @@ private function create_application(Request $request, $type) $request->offsetSet('name', generate_application_name($request->git_repository, $request->git_branch)); } $return = $this->validateDataApplications($request, $server); - if ($return instanceof \Illuminate\Http\JsonResponse) { + if ($return instanceof JsonResponse) { return $return; } @@ -1343,7 +1346,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(); @@ -1571,7 +1574,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(); @@ -1740,7 +1743,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)) { @@ -1848,7 +1851,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 @@ -1972,7 +1975,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)) { @@ -2458,7 +2461,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; } @@ -2528,7 +2531,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); @@ -2954,7 +2957,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(); @@ -3155,7 +3158,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(); @@ -4026,9 +4029,10 @@ public function storages(Request $request): JsonResponse mediaType: 'application/json', schema: new OA\Schema( type: 'object', - required: ['id', 'type'], + required: ['type'], properties: [ - 'id' => ['type' => 'integer', 'description' => 'The ID of the storage.'], + 'uuid' => ['type' => 'string', 'description' => 'The UUID of the storage (preferred).'], + 'id' => ['type' => 'integer', 'description' => 'The ID of the storage (deprecated, use uuid instead).'], 'type' => ['type' => 'string', 'enum' => ['persistent', 'file'], 'description' => 'The type of storage: persistent or file.'], 'is_preview_suffix_enabled' => ['type' => 'boolean', 'description' => 'Whether to add -pr-N suffix for preview deployments.'], 'name' => ['type' => 'string', 'description' => 'The volume name (persistent only, not allowed for read-only storages).'], @@ -4074,11 +4078,11 @@ public function update_storage(Request $request): JsonResponse } $return = validateIncomingRequest($request); - if ($return instanceof \Illuminate\Http\JsonResponse) { + if ($return instanceof JsonResponse) { return $return; } - $application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first(); + $application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->route('uuid'))->first(); if (! $application) { return response()->json([ @@ -4089,16 +4093,17 @@ public function update_storage(Request $request): JsonResponse $this->authorize('update', $application); $validator = customApiValidator($request->all(), [ - 'id' => 'required|integer', + 'uuid' => 'string', + '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', ]); - $allAllowedFields = ['id', 'type', 'is_preview_suffix_enabled', 'name', 'mount_path', 'host_path', 'content']; + $allAllowedFields = ['uuid', 'id', 'type', 'is_preview_suffix_enabled', 'name', 'mount_path', 'host_path', 'content']; $extraFields = array_diff(array_keys($request->all()), $allAllowedFields); if ($validator->fails() || ! empty($extraFields)) { $errors = $validator->errors(); @@ -4114,10 +4119,23 @@ public function update_storage(Request $request): JsonResponse ], 422); } + $storageUuid = $request->input('uuid'); + $storageId = $request->input('id'); + + if (! $storageUuid && ! $storageId) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['uuid' => 'Either uuid or id is required.'], + ], 422); + } + + $lookupField = $storageUuid ? 'uuid' : 'id'; + $lookupValue = $storageUuid ?? $storageId; + if ($request->type === 'persistent') { - $storage = $application->persistentStorages->where('id', $request->id)->first(); + $storage = $application->persistentStorages->where($lookupField, $lookupValue)->first(); } else { - $storage = $application->fileStorages->where('id', $request->id)->first(); + $storage = $application->fileStorages->where($lookupField, $lookupValue)->first(); } if (! $storage) { @@ -4183,4 +4201,257 @@ public function update_storage(Request $request): JsonResponse return response()->json($storage); } + + #[OA\Post( + summary: 'Create Storage', + description: 'Create a persistent storage or file storage for an application.', + path: '/applications/{uuid}/storages', + operationId: 'create-storage-by-application-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Applications'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the application.', + required: true, + schema: new OA\Schema(type: 'string') + ), + ], + requestBody: new OA\RequestBody( + required: true, + content: [ + new OA\MediaType( + mediaType: 'application/json', + schema: new OA\Schema( + type: 'object', + required: ['type', 'mount_path'], + properties: [ + 'type' => ['type' => 'string', 'enum' => ['persistent', 'file'], 'description' => 'The type of storage.'], + 'name' => ['type' => 'string', 'description' => 'Volume name (persistent only, required for persistent).'], + 'mount_path' => ['type' => 'string', 'description' => 'The container mount path.'], + 'host_path' => ['type' => 'string', 'nullable' => true, 'description' => 'The host path (persistent only, optional).'], + 'content' => ['type' => 'string', 'nullable' => true, 'description' => 'File content (file only, optional).'], + 'is_directory' => ['type' => 'boolean', 'description' => 'Whether this is a directory mount (file only, default false).'], + 'fs_path' => ['type' => 'string', 'description' => 'Host directory path (required when is_directory is true).'], + ], + additionalProperties: false, + ), + ), + ], + ), + responses: [ + new OA\Response( + response: 201, + description: 'Storage created.', + content: new OA\JsonContent(type: 'object'), + ), + new OA\Response(response: 401, ref: '#/components/responses/401'), + new OA\Response(response: 400, ref: '#/components/responses/400'), + new OA\Response(response: 404, ref: '#/components/responses/404'), + new OA\Response(response: 422, ref: '#/components/responses/422'), + ] + )] + public function create_storage(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + if (is_null($teamId)) { + return invalidTokenResponse(); + } + + $return = validateIncomingRequest($request); + if ($return instanceof JsonResponse) { + return $return; + } + + $application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first(); + if (! $application) { + return response()->json(['message' => 'Application not found.'], 404); + } + + $this->authorize('update', $application); + + $validator = customApiValidator($request->all(), [ + 'type' => 'required|string|in:persistent,file', + 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN], + 'mount_path' => 'required|string', + 'host_path' => 'string|nullable', + 'content' => 'string|nullable', + 'is_directory' => 'boolean', + 'fs_path' => 'string', + ]); + + $allAllowedFields = ['type', 'name', 'mount_path', 'host_path', 'content', 'is_directory', 'fs_path']; + $extraFields = array_diff(array_keys($request->all()), $allAllowedFields); + if ($validator->fails() || ! empty($extraFields)) { + $errors = $validator->errors(); + if (! empty($extraFields)) { + foreach ($extraFields as $field) { + $errors->add($field, 'This field is not allowed.'); + } + } + + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => $errors, + ], 422); + } + + if ($request->type === 'persistent') { + if (! $request->name) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['name' => 'The name field is required for persistent storages.'], + ], 422); + } + + $typeSpecificInvalidFields = array_intersect(['content', 'is_directory', 'fs_path'], array_keys($request->all())); + if (! empty($typeSpecificInvalidFields)) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => collect($typeSpecificInvalidFields) + ->mapWithKeys(fn ($field) => [$field => "Field '{$field}' is not valid for type 'persistent'."]), + ], 422); + } + + $storage = LocalPersistentVolume::create([ + 'name' => $application->uuid.'-'.$request->name, + 'mount_path' => $request->mount_path, + 'host_path' => $request->host_path, + 'resource_id' => $application->id, + 'resource_type' => $application->getMorphClass(), + ]); + + return response()->json($storage, 201); + } + + // File storage + $typeSpecificInvalidFields = array_intersect(['name', 'host_path'], array_keys($request->all())); + if (! empty($typeSpecificInvalidFields)) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => collect($typeSpecificInvalidFields) + ->mapWithKeys(fn ($field) => [$field => "Field '{$field}' is not valid for type 'file'."]), + ], 422); + } + + $isDirectory = $request->boolean('is_directory', false); + + if ($isDirectory) { + if (! $request->fs_path) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['fs_path' => 'The fs_path field is required for directory mounts.'], + ], 422); + } + + $fsPath = str($request->fs_path)->trim()->start('/')->value(); + $mountPath = str($request->mount_path)->trim()->start('/')->value(); + + validateShellSafePath($fsPath, 'storage source path'); + validateShellSafePath($mountPath, 'storage destination path'); + + $storage = LocalFileVolume::create([ + 'fs_path' => $fsPath, + 'mount_path' => $mountPath, + 'is_directory' => true, + 'resource_id' => $application->id, + 'resource_type' => get_class($application), + ]); + } else { + $mountPath = str($request->mount_path)->trim()->start('/')->value(); + + validateShellSafePath($mountPath, 'file storage path'); + + $fsPath = application_configuration_dir().'/'.$application->uuid.$mountPath; + + $storage = LocalFileVolume::create([ + 'fs_path' => $fsPath, + 'mount_path' => $mountPath, + 'content' => $request->content, + 'is_directory' => false, + 'resource_id' => $application->id, + 'resource_type' => get_class($application), + ]); + } + + return response()->json($storage, 201); + } + + #[OA\Delete( + summary: 'Delete Storage', + description: 'Delete a persistent storage or file storage by application UUID.', + path: '/applications/{uuid}/storages/{storage_uuid}', + operationId: 'delete-storage-by-application-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Applications'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the application.', + required: true, + schema: new OA\Schema(type: 'string') + ), + new OA\Parameter( + name: 'storage_uuid', + in: 'path', + description: 'UUID of the storage.', + required: true, + schema: new OA\Schema(type: 'string') + ), + ], + responses: [ + new OA\Response(response: 200, description: 'Storage deleted.', content: new OA\JsonContent( + properties: [new OA\Property(property: 'message', type: 'string')], + )), + new OA\Response(response: 401, ref: '#/components/responses/401'), + new OA\Response(response: 400, ref: '#/components/responses/400'), + new OA\Response(response: 404, ref: '#/components/responses/404'), + new OA\Response(response: 422, ref: '#/components/responses/422'), + ] + )] + public function delete_storage(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + if (is_null($teamId)) { + return invalidTokenResponse(); + } + + $application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first(); + if (! $application) { + return response()->json(['message' => 'Application not found.'], 404); + } + + $this->authorize('update', $application); + + $storageUuid = $request->route('storage_uuid'); + + $storage = $application->persistentStorages->where('uuid', $storageUuid)->first(); + if (! $storage) { + $storage = $application->fileStorages->where('uuid', $storageUuid)->first(); + } + + if (! $storage) { + return response()->json(['message' => 'Storage not found.'], 404); + } + + if ($storage->shouldBeReadOnlyInUI()) { + return response()->json([ + 'message' => 'This storage is read-only (managed by docker-compose or service definition) and cannot be deleted.', + ], 422); + } + + if ($storage instanceof LocalFileVolume) { + $storage->deleteStorageOnServer(); + } + + $storage->delete(); + + return response()->json(['message' => 'Storage deleted.']); + } } diff --git a/app/Http/Controllers/Api/DatabasesController.php b/app/Http/Controllers/Api/DatabasesController.php index 6ad18d872..660ed4529 100644 --- a/app/Http/Controllers/Api/DatabasesController.php +++ b/app/Http/Controllers/Api/DatabasesController.php @@ -12,11 +12,15 @@ use App\Jobs\DatabaseBackupJob; use App\Jobs\DeleteResourceJob; use App\Models\EnvironmentVariable; +use App\Models\LocalFileVolume; +use App\Models\LocalPersistentVolume; use App\Models\Project; use App\Models\S3Storage; 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; use OpenApi\Attributes as OA; @@ -331,7 +335,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(), [ @@ -682,7 +686,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; } @@ -789,6 +793,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(); @@ -899,7 +915,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(), [ @@ -994,6 +1010,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) { @@ -1563,7 +1591,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; } @@ -3298,4 +3326,523 @@ public function delete_env_by_uuid(Request $request) return response()->json(['message' => 'Environment variable deleted.']); } + + #[OA\Get( + summary: 'List Storages', + description: 'List all persistent storages and file storages by database UUID.', + path: '/databases/{uuid}/storages', + operationId: 'list-storages-by-database-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Databases'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the database.', + required: true, + schema: new OA\Schema( + type: 'string', + ) + ), + ], + responses: [ + new OA\Response( + response: 200, + description: 'All storages by database UUID.', + content: new OA\JsonContent( + properties: [ + new OA\Property(property: 'persistent_storages', type: 'array', items: new OA\Items(type: 'object')), + new OA\Property(property: 'file_storages', type: 'array', items: new OA\Items(type: 'object')), + ], + ), + ), + new OA\Response( + response: 401, + ref: '#/components/responses/401', + ), + new OA\Response( + response: 400, + ref: '#/components/responses/400', + ), + new OA\Response( + response: 404, + ref: '#/components/responses/404', + ), + ] + )] + public function storages(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + if (is_null($teamId)) { + return invalidTokenResponse(); + } + + $database = queryDatabaseByUuidWithinTeam($request->uuid, $teamId); + if (! $database) { + return response()->json(['message' => 'Database not found.'], 404); + } + + $this->authorize('view', $database); + + $persistentStorages = $database->persistentStorages->sortBy('id')->values(); + $fileStorages = $database->fileStorages->sortBy('id')->values(); + + return response()->json([ + 'persistent_storages' => $persistentStorages, + 'file_storages' => $fileStorages, + ]); + } + + #[OA\Post( + summary: 'Create Storage', + description: 'Create a persistent storage or file storage for a database.', + path: '/databases/{uuid}/storages', + operationId: 'create-storage-by-database-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Databases'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the database.', + required: true, + schema: new OA\Schema(type: 'string') + ), + ], + requestBody: new OA\RequestBody( + required: true, + content: [ + new OA\MediaType( + mediaType: 'application/json', + schema: new OA\Schema( + type: 'object', + required: ['type', 'mount_path'], + properties: [ + 'type' => ['type' => 'string', 'enum' => ['persistent', 'file'], 'description' => 'The type of storage.'], + 'name' => ['type' => 'string', 'description' => 'Volume name (persistent only, required for persistent).'], + 'mount_path' => ['type' => 'string', 'description' => 'The container mount path.'], + 'host_path' => ['type' => 'string', 'nullable' => true, 'description' => 'The host path (persistent only, optional).'], + 'content' => ['type' => 'string', 'nullable' => true, 'description' => 'File content (file only, optional).'], + 'is_directory' => ['type' => 'boolean', 'description' => 'Whether this is a directory mount (file only, default false).'], + 'fs_path' => ['type' => 'string', 'description' => 'Host directory path (required when is_directory is true).'], + ], + additionalProperties: false, + ), + ), + ], + ), + responses: [ + new OA\Response( + response: 201, + description: 'Storage created.', + content: new OA\JsonContent(type: 'object'), + ), + new OA\Response(response: 401, ref: '#/components/responses/401'), + new OA\Response(response: 400, ref: '#/components/responses/400'), + new OA\Response(response: 404, ref: '#/components/responses/404'), + new OA\Response(response: 422, ref: '#/components/responses/422'), + ] + )] + public function create_storage(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + if (is_null($teamId)) { + return invalidTokenResponse(); + } + + $return = validateIncomingRequest($request); + if ($return instanceof JsonResponse) { + return $return; + } + + $database = queryDatabaseByUuidWithinTeam($request->uuid, $teamId); + if (! $database) { + return response()->json(['message' => 'Database not found.'], 404); + } + + $this->authorize('update', $database); + + $validator = customApiValidator($request->all(), [ + 'type' => 'required|string|in:persistent,file', + 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN], + 'mount_path' => 'required|string', + 'host_path' => 'string|nullable', + 'content' => 'string|nullable', + 'is_directory' => 'boolean', + 'fs_path' => 'string', + ]); + + $allAllowedFields = ['type', 'name', 'mount_path', 'host_path', 'content', 'is_directory', 'fs_path']; + $extraFields = array_diff(array_keys($request->all()), $allAllowedFields); + if ($validator->fails() || ! empty($extraFields)) { + $errors = $validator->errors(); + if (! empty($extraFields)) { + foreach ($extraFields as $field) { + $errors->add($field, 'This field is not allowed.'); + } + } + + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => $errors, + ], 422); + } + + if ($request->type === 'persistent') { + if (! $request->name) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['name' => 'The name field is required for persistent storages.'], + ], 422); + } + + $typeSpecificInvalidFields = array_intersect(['content', 'is_directory', 'fs_path'], array_keys($request->all())); + if (! empty($typeSpecificInvalidFields)) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => collect($typeSpecificInvalidFields) + ->mapWithKeys(fn ($field) => [$field => "Field '{$field}' is not valid for type 'persistent'."]), + ], 422); + } + + $storage = LocalPersistentVolume::create([ + 'name' => $database->uuid.'-'.$request->name, + 'mount_path' => $request->mount_path, + 'host_path' => $request->host_path, + 'resource_id' => $database->id, + 'resource_type' => $database->getMorphClass(), + ]); + + return response()->json($storage, 201); + } + + // File storage + $typeSpecificInvalidFields = array_intersect(['name', 'host_path'], array_keys($request->all())); + if (! empty($typeSpecificInvalidFields)) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => collect($typeSpecificInvalidFields) + ->mapWithKeys(fn ($field) => [$field => "Field '{$field}' is not valid for type 'file'."]), + ], 422); + } + + $isDirectory = $request->boolean('is_directory', false); + + if ($isDirectory) { + if (! $request->fs_path) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['fs_path' => 'The fs_path field is required for directory mounts.'], + ], 422); + } + + $fsPath = str($request->fs_path)->trim()->start('/')->value(); + $mountPath = str($request->mount_path)->trim()->start('/')->value(); + + validateShellSafePath($fsPath, 'storage source path'); + validateShellSafePath($mountPath, 'storage destination path'); + + $storage = LocalFileVolume::create([ + 'fs_path' => $fsPath, + 'mount_path' => $mountPath, + 'is_directory' => true, + 'resource_id' => $database->id, + 'resource_type' => get_class($database), + ]); + } else { + $mountPath = str($request->mount_path)->trim()->start('/')->value(); + + validateShellSafePath($mountPath, 'file storage path'); + + $fsPath = database_configuration_dir().'/'.$database->uuid.$mountPath; + + $storage = LocalFileVolume::create([ + 'fs_path' => $fsPath, + 'mount_path' => $mountPath, + 'content' => $request->content, + 'is_directory' => false, + 'resource_id' => $database->id, + 'resource_type' => get_class($database), + ]); + } + + return response()->json($storage, 201); + } + + #[OA\Patch( + summary: 'Update Storage', + description: 'Update a persistent storage or file storage by database UUID.', + path: '/databases/{uuid}/storages', + operationId: 'update-storage-by-database-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Databases'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the database.', + required: true, + schema: new OA\Schema( + type: 'string', + ) + ), + ], + requestBody: new OA\RequestBody( + description: 'Storage updated. For read-only storages (from docker-compose or services), only is_preview_suffix_enabled can be updated.', + required: true, + content: [ + new OA\MediaType( + mediaType: 'application/json', + schema: new OA\Schema( + type: 'object', + required: ['type'], + properties: [ + 'uuid' => ['type' => 'string', 'description' => 'The UUID of the storage (preferred).'], + 'id' => ['type' => 'integer', 'description' => 'The ID of the storage (deprecated, use uuid instead).'], + 'type' => ['type' => 'string', 'enum' => ['persistent', 'file'], 'description' => 'The type of storage: persistent or file.'], + 'is_preview_suffix_enabled' => ['type' => 'boolean', 'description' => 'Whether to add -pr-N suffix for preview deployments.'], + 'name' => ['type' => 'string', 'description' => 'The volume name (persistent only, not allowed for read-only storages).'], + 'mount_path' => ['type' => 'string', 'description' => 'The container mount path (not allowed for read-only storages).'], + 'host_path' => ['type' => 'string', 'nullable' => true, 'description' => 'The host path (persistent only, not allowed for read-only storages).'], + 'content' => ['type' => 'string', 'nullable' => true, 'description' => 'The file content (file only, not allowed for read-only storages).'], + ], + additionalProperties: false, + ), + ), + ], + ), + responses: [ + new OA\Response( + response: 200, + description: 'Storage updated.', + content: new OA\JsonContent(type: 'object'), + ), + new OA\Response( + response: 401, + ref: '#/components/responses/401', + ), + new OA\Response( + response: 400, + ref: '#/components/responses/400', + ), + new OA\Response( + response: 404, + ref: '#/components/responses/404', + ), + new OA\Response( + response: 422, + ref: '#/components/responses/422', + ), + ] + )] + public function update_storage(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + + if (is_null($teamId)) { + return invalidTokenResponse(); + } + + $return = validateIncomingRequest($request); + if ($return instanceof JsonResponse) { + return $return; + } + + $database = queryDatabaseByUuidWithinTeam($request->route('uuid'), $teamId); + if (! $database) { + return response()->json(['message' => 'Database not found.'], 404); + } + + $this->authorize('update', $database); + + $validator = customApiValidator($request->all(), [ + 'uuid' => 'string', + 'id' => 'integer', + 'type' => 'required|string|in:persistent,file', + 'is_preview_suffix_enabled' => 'boolean', + 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN], + 'mount_path' => 'string', + 'host_path' => 'string|nullable', + 'content' => 'string|nullable', + ]); + + $allAllowedFields = ['uuid', 'id', 'type', 'is_preview_suffix_enabled', 'name', 'mount_path', 'host_path', 'content']; + $extraFields = array_diff(array_keys($request->all()), $allAllowedFields); + if ($validator->fails() || ! empty($extraFields)) { + $errors = $validator->errors(); + if (! empty($extraFields)) { + foreach ($extraFields as $field) { + $errors->add($field, 'This field is not allowed.'); + } + } + + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => $errors, + ], 422); + } + + $storageUuid = $request->input('uuid'); + $storageId = $request->input('id'); + + if (! $storageUuid && ! $storageId) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['uuid' => 'Either uuid or id is required.'], + ], 422); + } + + $lookupField = $storageUuid ? 'uuid' : 'id'; + $lookupValue = $storageUuid ?? $storageId; + + if ($request->type === 'persistent') { + $storage = $database->persistentStorages->where($lookupField, $lookupValue)->first(); + } else { + $storage = $database->fileStorages->where($lookupField, $lookupValue)->first(); + } + + if (! $storage) { + return response()->json([ + 'message' => 'Storage not found.', + ], 404); + } + + $isReadOnly = $storage->shouldBeReadOnlyInUI(); + $editableOnlyFields = ['name', 'mount_path', 'host_path', 'content']; + $requestedEditableFields = array_intersect($editableOnlyFields, array_keys($request->all())); + + if ($isReadOnly && ! empty($requestedEditableFields)) { + return response()->json([ + 'message' => 'This storage is read-only (managed by docker-compose or service definition). Only is_preview_suffix_enabled can be updated.', + 'read_only_fields' => array_values($requestedEditableFields), + ], 422); + } + + // Reject fields that don't apply to the given storage type + if (! $isReadOnly) { + $typeSpecificInvalidFields = $request->type === 'persistent' + ? array_intersect(['content'], array_keys($request->all())) + : array_intersect(['name', 'host_path'], array_keys($request->all())); + + if (! empty($typeSpecificInvalidFields)) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => collect($typeSpecificInvalidFields) + ->mapWithKeys(fn ($field) => [$field => "Field '{$field}' is not valid for type '{$request->type}'."]), + ], 422); + } + } + + // Always allowed + if ($request->has('is_preview_suffix_enabled')) { + $storage->is_preview_suffix_enabled = $request->is_preview_suffix_enabled; + } + + // Only for editable storages + if (! $isReadOnly) { + if ($request->type === 'persistent') { + if ($request->has('name')) { + $storage->name = $request->name; + } + if ($request->has('mount_path')) { + $storage->mount_path = $request->mount_path; + } + if ($request->has('host_path')) { + $storage->host_path = $request->host_path; + } + } else { + if ($request->has('mount_path')) { + $storage->mount_path = $request->mount_path; + } + if ($request->has('content')) { + $storage->content = $request->content; + } + } + } + + $storage->save(); + + return response()->json($storage); + } + + #[OA\Delete( + summary: 'Delete Storage', + description: 'Delete a persistent storage or file storage by database UUID.', + path: '/databases/{uuid}/storages/{storage_uuid}', + operationId: 'delete-storage-by-database-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Databases'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the database.', + required: true, + schema: new OA\Schema(type: 'string') + ), + new OA\Parameter( + name: 'storage_uuid', + in: 'path', + description: 'UUID of the storage.', + required: true, + schema: new OA\Schema(type: 'string') + ), + ], + responses: [ + new OA\Response(response: 200, description: 'Storage deleted.', content: new OA\JsonContent( + properties: [new OA\Property(property: 'message', type: 'string')], + )), + new OA\Response(response: 401, ref: '#/components/responses/401'), + new OA\Response(response: 400, ref: '#/components/responses/400'), + new OA\Response(response: 404, ref: '#/components/responses/404'), + new OA\Response(response: 422, ref: '#/components/responses/422'), + ] + )] + public function delete_storage(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + if (is_null($teamId)) { + return invalidTokenResponse(); + } + + $database = queryDatabaseByUuidWithinTeam($request->uuid, $teamId); + if (! $database) { + return response()->json(['message' => 'Database not found.'], 404); + } + + $this->authorize('update', $database); + + $storageUuid = $request->route('storage_uuid'); + + $storage = $database->persistentStorages->where('uuid', $storageUuid)->first(); + if (! $storage) { + $storage = $database->fileStorages->where('uuid', $storageUuid)->first(); + } + + if (! $storage) { + return response()->json(['message' => 'Storage not found.'], 404); + } + + if ($storage->shouldBeReadOnlyInUI()) { + return response()->json([ + 'message' => 'This storage is read-only (managed by docker-compose or service definition) and cannot be deleted.', + ], 422); + } + + if ($storage instanceof LocalFileVolume) { + $storage->deleteStorageOnServer(); + } + + $storage->delete(); + + return response()->json(['message' => 'Storage deleted.']); + } } 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/HetznerController.php b/app/Http/Controllers/Api/HetznerController.php index 2645c2df1..ed91b4475 100644 --- a/app/Http/Controllers/Api/HetznerController.php +++ b/app/Http/Controllers/Api/HetznerController.php @@ -586,7 +586,8 @@ public function createServer(Request $request) } // Check server limit - if (Team::serverLimitReached()) { + $team = Team::find($teamId); + if (Team::serverLimitReached($team)) { return response()->json(['message' => 'Server limit reached for your subscription.'], 400); } diff --git a/app/Http/Controllers/Api/ServersController.php b/app/Http/Controllers/Api/ServersController.php index da94521a8..2ef95ce8b 100644 --- a/app/Http/Controllers/Api/ServersController.php +++ b/app/Http/Controllers/Api/ServersController.php @@ -290,7 +290,11 @@ public function domains_by_server(Request $request) if (is_null($teamId)) { return invalidTokenResponse(); } - $uuid = $request->get('uuid'); + $server = ModelsServer::whereTeamId($teamId)->whereUuid($request->uuid)->first(); + if (is_null($server)) { + return response()->json(['message' => 'Server not found.'], 404); + } + $uuid = $request->query('uuid'); if ($uuid) { $application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $uuid)->first(); if (! $application) { @@ -301,7 +305,9 @@ public function domains_by_server(Request $request) } $projects = Project::where('team_id', $teamId)->get(); $domains = collect(); - $applications = $projects->pluck('applications')->flatten(); + $applications = $projects->pluck('applications')->flatten()->filter(function ($application) use ($server) { + return $application->destination?->server?->id === $server->id; + }); $settings = instanceSettings(); if ($applications->count() > 0) { foreach ($applications as $application) { @@ -341,7 +347,9 @@ public function domains_by_server(Request $request) } } } - $services = $projects->pluck('services')->flatten(); + $services = $projects->pluck('services')->flatten()->filter(function ($service) use ($server) { + return $service->server_id === $server->id; + }); if ($services->count() > 0) { foreach ($services as $service) { $service_applications = $service->applications; @@ -354,7 +362,8 @@ public function domains_by_server(Request $request) })->filter(function (Stringable $fqdn) { return $fqdn->isNotEmpty(); }); - if ($ip === 'host.docker.internal') { + $serviceIp = $server->ip; + if ($serviceIp === 'host.docker.internal') { if ($settings->public_ipv4) { $domains->push([ 'domain' => $fqdn, @@ -370,13 +379,13 @@ public function domains_by_server(Request $request) if (! $settings->public_ipv4 && ! $settings->public_ipv6) { $domains->push([ 'domain' => $fqdn, - 'ip' => $ip, + 'ip' => $serviceIp, ]); } } else { $domains->push([ 'domain' => $fqdn, - 'ip' => $ip, + 'ip' => $serviceIp, ]); } } diff --git a/app/Http/Controllers/Api/ServicesController.php b/app/Http/Controllers/Api/ServicesController.php index 4caee26dd..fbf4b9e56 100644 --- a/app/Http/Controllers/Api/ServicesController.php +++ b/app/Http/Controllers/Api/ServicesController.php @@ -8,9 +8,13 @@ use App\Http\Controllers\Controller; use App\Jobs\DeleteResourceJob; use App\Models\EnvironmentVariable; +use App\Models\LocalFileVolume; +use App\Models\LocalPersistentVolume; 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; use OpenApi\Attributes as OA; @@ -299,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 = [ @@ -922,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; } @@ -1849,4 +1853,609 @@ public function action_restart(Request $request) 200 ); } + + #[OA\Get( + summary: 'List Storages', + description: 'List all persistent storages and file storages by service UUID.', + path: '/services/{uuid}/storages', + operationId: 'list-storages-by-service-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Services'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the service.', + required: true, + schema: new OA\Schema( + type: 'string', + ) + ), + ], + responses: [ + new OA\Response( + response: 200, + description: 'All storages by service UUID.', + content: new OA\JsonContent( + properties: [ + new OA\Property(property: 'persistent_storages', type: 'array', items: new OA\Items(type: 'object')), + new OA\Property(property: 'file_storages', type: 'array', items: new OA\Items(type: 'object')), + ], + ), + ), + new OA\Response( + response: 401, + ref: '#/components/responses/401', + ), + new OA\Response( + response: 400, + ref: '#/components/responses/400', + ), + new OA\Response( + response: 404, + ref: '#/components/responses/404', + ), + ] + )] + public function storages(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + if (is_null($teamId)) { + return invalidTokenResponse(); + } + $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first(); + + if (! $service) { + return response()->json([ + 'message' => 'Service not found.', + ], 404); + } + + $this->authorize('view', $service); + + $persistentStorages = collect(); + $fileStorages = collect(); + + foreach ($service->applications as $app) { + $persistentStorages = $persistentStorages->merge( + $app->persistentStorages->map(fn ($s) => $s->setAttribute('resource_uuid', $app->uuid)->setAttribute('resource_type', 'application')) + ); + $fileStorages = $fileStorages->merge( + $app->fileStorages->map(fn ($s) => $s->setAttribute('resource_uuid', $app->uuid)->setAttribute('resource_type', 'application')) + ); + } + foreach ($service->databases as $db) { + $persistentStorages = $persistentStorages->merge( + $db->persistentStorages->map(fn ($s) => $s->setAttribute('resource_uuid', $db->uuid)->setAttribute('resource_type', 'database')) + ); + $fileStorages = $fileStorages->merge( + $db->fileStorages->map(fn ($s) => $s->setAttribute('resource_uuid', $db->uuid)->setAttribute('resource_type', 'database')) + ); + } + + return response()->json([ + 'persistent_storages' => $persistentStorages->sortBy('id')->values(), + 'file_storages' => $fileStorages->sortBy('id')->values(), + ]); + } + + #[OA\Post( + summary: 'Create Storage', + description: 'Create a persistent storage or file storage for a service sub-resource.', + path: '/services/{uuid}/storages', + operationId: 'create-storage-by-service-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Services'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the service.', + required: true, + schema: new OA\Schema(type: 'string') + ), + ], + requestBody: new OA\RequestBody( + required: true, + content: [ + new OA\MediaType( + mediaType: 'application/json', + schema: new OA\Schema( + type: 'object', + required: ['type', 'mount_path', 'resource_uuid'], + properties: [ + 'type' => ['type' => 'string', 'enum' => ['persistent', 'file'], 'description' => 'The type of storage.'], + 'resource_uuid' => ['type' => 'string', 'description' => 'UUID of the service application or database sub-resource.'], + 'name' => ['type' => 'string', 'description' => 'Volume name (persistent only, required for persistent).'], + 'mount_path' => ['type' => 'string', 'description' => 'The container mount path.'], + 'host_path' => ['type' => 'string', 'nullable' => true, 'description' => 'The host path (persistent only, optional).'], + 'content' => ['type' => 'string', 'nullable' => true, 'description' => 'File content (file only, optional).'], + 'is_directory' => ['type' => 'boolean', 'description' => 'Whether this is a directory mount (file only, default false).'], + 'fs_path' => ['type' => 'string', 'description' => 'Host directory path (required when is_directory is true).'], + ], + additionalProperties: false, + ), + ), + ], + ), + responses: [ + new OA\Response( + response: 201, + description: 'Storage created.', + content: new OA\JsonContent(type: 'object'), + ), + new OA\Response(response: 401, ref: '#/components/responses/401'), + new OA\Response(response: 400, ref: '#/components/responses/400'), + new OA\Response(response: 404, ref: '#/components/responses/404'), + new OA\Response(response: 422, ref: '#/components/responses/422'), + ] + )] + public function create_storage(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + if (is_null($teamId)) { + return invalidTokenResponse(); + } + + $return = validateIncomingRequest($request); + if ($return instanceof JsonResponse) { + return $return; + } + + $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first(); + if (! $service) { + return response()->json(['message' => 'Service not found.'], 404); + } + + $this->authorize('update', $service); + + $validator = customApiValidator($request->all(), [ + 'type' => 'required|string|in:persistent,file', + 'resource_uuid' => 'required|string', + 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN], + 'mount_path' => 'required|string', + 'host_path' => 'string|nullable', + 'content' => 'string|nullable', + 'is_directory' => 'boolean', + 'fs_path' => 'string', + ]); + + $allAllowedFields = ['type', 'resource_uuid', 'name', 'mount_path', 'host_path', 'content', 'is_directory', 'fs_path']; + $extraFields = array_diff(array_keys($request->all()), $allAllowedFields); + if ($validator->fails() || ! empty($extraFields)) { + $errors = $validator->errors(); + if (! empty($extraFields)) { + foreach ($extraFields as $field) { + $errors->add($field, 'This field is not allowed.'); + } + } + + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => $errors, + ], 422); + } + + $subResource = $service->applications()->where('uuid', $request->resource_uuid)->first(); + if (! $subResource) { + $subResource = $service->databases()->where('uuid', $request->resource_uuid)->first(); + } + if (! $subResource) { + return response()->json(['message' => 'Service resource not found.'], 404); + } + + if ($request->type === 'persistent') { + if (! $request->name) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['name' => 'The name field is required for persistent storages.'], + ], 422); + } + + $typeSpecificInvalidFields = array_intersect(['content', 'is_directory', 'fs_path'], array_keys($request->all())); + if (! empty($typeSpecificInvalidFields)) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => collect($typeSpecificInvalidFields) + ->mapWithKeys(fn ($field) => [$field => "Field '{$field}' is not valid for type 'persistent'."]), + ], 422); + } + + $storage = LocalPersistentVolume::create([ + 'name' => $subResource->uuid.'-'.$request->name, + 'mount_path' => $request->mount_path, + 'host_path' => $request->host_path, + 'resource_id' => $subResource->id, + 'resource_type' => $subResource->getMorphClass(), + ]); + + return response()->json($storage, 201); + } + + // File storage + $typeSpecificInvalidFields = array_intersect(['name', 'host_path'], array_keys($request->all())); + if (! empty($typeSpecificInvalidFields)) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => collect($typeSpecificInvalidFields) + ->mapWithKeys(fn ($field) => [$field => "Field '{$field}' is not valid for type 'file'."]), + ], 422); + } + + $isDirectory = $request->boolean('is_directory', false); + + if ($isDirectory) { + if (! $request->fs_path) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['fs_path' => 'The fs_path field is required for directory mounts.'], + ], 422); + } + + $fsPath = str($request->fs_path)->trim()->start('/')->value(); + $mountPath = str($request->mount_path)->trim()->start('/')->value(); + + validateShellSafePath($fsPath, 'storage source path'); + validateShellSafePath($mountPath, 'storage destination path'); + + $storage = LocalFileVolume::create([ + 'fs_path' => $fsPath, + 'mount_path' => $mountPath, + 'is_directory' => true, + 'resource_id' => $subResource->id, + 'resource_type' => get_class($subResource), + ]); + } else { + $mountPath = str($request->mount_path)->trim()->start('/')->value(); + + validateShellSafePath($mountPath, 'file storage path'); + + $fsPath = service_configuration_dir().'/'.$service->uuid.$mountPath; + + $storage = LocalFileVolume::create([ + 'fs_path' => $fsPath, + 'mount_path' => $mountPath, + 'content' => $request->content, + 'is_directory' => false, + 'resource_id' => $subResource->id, + 'resource_type' => get_class($subResource), + ]); + } + + return response()->json($storage, 201); + } + + #[OA\Patch( + summary: 'Update Storage', + description: 'Update a persistent storage or file storage by service UUID.', + path: '/services/{uuid}/storages', + operationId: 'update-storage-by-service-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Services'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the service.', + required: true, + schema: new OA\Schema( + type: 'string', + ) + ), + ], + requestBody: new OA\RequestBody( + description: 'Storage updated. For read-only storages (from docker-compose or services), only is_preview_suffix_enabled can be updated.', + required: true, + content: [ + new OA\MediaType( + mediaType: 'application/json', + schema: new OA\Schema( + type: 'object', + required: ['type'], + properties: [ + 'uuid' => ['type' => 'string', 'description' => 'The UUID of the storage (preferred).'], + 'id' => ['type' => 'integer', 'description' => 'The ID of the storage (deprecated, use uuid instead).'], + 'type' => ['type' => 'string', 'enum' => ['persistent', 'file'], 'description' => 'The type of storage: persistent or file.'], + 'is_preview_suffix_enabled' => ['type' => 'boolean', 'description' => 'Whether to add -pr-N suffix for preview deployments.'], + 'name' => ['type' => 'string', 'description' => 'The volume name (persistent only, not allowed for read-only storages).'], + 'mount_path' => ['type' => 'string', 'description' => 'The container mount path (not allowed for read-only storages).'], + 'host_path' => ['type' => 'string', 'nullable' => true, 'description' => 'The host path (persistent only, not allowed for read-only storages).'], + 'content' => ['type' => 'string', 'nullable' => true, 'description' => 'The file content (file only, not allowed for read-only storages).'], + ], + additionalProperties: false, + ), + ), + ], + ), + responses: [ + new OA\Response( + response: 200, + description: 'Storage updated.', + content: new OA\JsonContent(type: 'object'), + ), + new OA\Response( + response: 401, + ref: '#/components/responses/401', + ), + new OA\Response( + response: 400, + ref: '#/components/responses/400', + ), + new OA\Response( + response: 404, + ref: '#/components/responses/404', + ), + new OA\Response( + response: 422, + ref: '#/components/responses/422', + ), + ] + )] + public function update_storage(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + + if (is_null($teamId)) { + return invalidTokenResponse(); + } + + $return = validateIncomingRequest($request); + if ($return instanceof JsonResponse) { + return $return; + } + + $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->route('uuid'))->first(); + + if (! $service) { + return response()->json([ + 'message' => 'Service not found.', + ], 404); + } + + $this->authorize('update', $service); + + $validator = customApiValidator($request->all(), [ + 'uuid' => 'string', + 'id' => 'integer', + 'type' => 'required|string|in:persistent,file', + 'is_preview_suffix_enabled' => 'boolean', + 'name' => ['string', 'regex:'.ValidationPatterns::VOLUME_NAME_PATTERN], + 'mount_path' => 'string', + 'host_path' => 'string|nullable', + 'content' => 'string|nullable', + ]); + + $allAllowedFields = ['uuid', 'id', 'type', 'is_preview_suffix_enabled', 'name', 'mount_path', 'host_path', 'content']; + $extraFields = array_diff(array_keys($request->all()), $allAllowedFields); + if ($validator->fails() || ! empty($extraFields)) { + $errors = $validator->errors(); + if (! empty($extraFields)) { + foreach ($extraFields as $field) { + $errors->add($field, 'This field is not allowed.'); + } + } + + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => $errors, + ], 422); + } + + $storageUuid = $request->input('uuid'); + $storageId = $request->input('id'); + + if (! $storageUuid && ! $storageId) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['uuid' => 'Either uuid or id is required.'], + ], 422); + } + + $lookupField = $storageUuid ? 'uuid' : 'id'; + $lookupValue = $storageUuid ?? $storageId; + + $storage = null; + if ($request->type === 'persistent') { + foreach ($service->applications as $app) { + $storage = $app->persistentStorages->where($lookupField, $lookupValue)->first(); + if ($storage) { + break; + } + } + if (! $storage) { + foreach ($service->databases as $db) { + $storage = $db->persistentStorages->where($lookupField, $lookupValue)->first(); + if ($storage) { + break; + } + } + } + } else { + foreach ($service->applications as $app) { + $storage = $app->fileStorages->where($lookupField, $lookupValue)->first(); + if ($storage) { + break; + } + } + if (! $storage) { + foreach ($service->databases as $db) { + $storage = $db->fileStorages->where($lookupField, $lookupValue)->first(); + if ($storage) { + break; + } + } + } + } + + if (! $storage) { + return response()->json([ + 'message' => 'Storage not found.', + ], 404); + } + + $isReadOnly = $storage->shouldBeReadOnlyInUI(); + $editableOnlyFields = ['name', 'mount_path', 'host_path', 'content']; + $requestedEditableFields = array_intersect($editableOnlyFields, array_keys($request->all())); + + if ($isReadOnly && ! empty($requestedEditableFields)) { + return response()->json([ + 'message' => 'This storage is read-only (managed by docker-compose or service definition). Only is_preview_suffix_enabled can be updated.', + 'read_only_fields' => array_values($requestedEditableFields), + ], 422); + } + + // Reject fields that don't apply to the given storage type + if (! $isReadOnly) { + $typeSpecificInvalidFields = $request->type === 'persistent' + ? array_intersect(['content'], array_keys($request->all())) + : array_intersect(['name', 'host_path'], array_keys($request->all())); + + if (! empty($typeSpecificInvalidFields)) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => collect($typeSpecificInvalidFields) + ->mapWithKeys(fn ($field) => [$field => "Field '{$field}' is not valid for type '{$request->type}'."]), + ], 422); + } + } + + // Always allowed + if ($request->has('is_preview_suffix_enabled')) { + $storage->is_preview_suffix_enabled = $request->is_preview_suffix_enabled; + } + + // Only for editable storages + if (! $isReadOnly) { + if ($request->type === 'persistent') { + if ($request->has('name')) { + $storage->name = $request->name; + } + if ($request->has('mount_path')) { + $storage->mount_path = $request->mount_path; + } + if ($request->has('host_path')) { + $storage->host_path = $request->host_path; + } + } else { + if ($request->has('mount_path')) { + $storage->mount_path = $request->mount_path; + } + if ($request->has('content')) { + $storage->content = $request->content; + } + } + } + + $storage->save(); + + return response()->json($storage); + } + + #[OA\Delete( + summary: 'Delete Storage', + description: 'Delete a persistent storage or file storage by service UUID.', + path: '/services/{uuid}/storages/{storage_uuid}', + operationId: 'delete-storage-by-service-uuid', + security: [ + ['bearerAuth' => []], + ], + tags: ['Services'], + parameters: [ + new OA\Parameter( + name: 'uuid', + in: 'path', + description: 'UUID of the service.', + required: true, + schema: new OA\Schema(type: 'string') + ), + new OA\Parameter( + name: 'storage_uuid', + in: 'path', + description: 'UUID of the storage.', + required: true, + schema: new OA\Schema(type: 'string') + ), + ], + responses: [ + new OA\Response(response: 200, description: 'Storage deleted.', content: new OA\JsonContent( + properties: [new OA\Property(property: 'message', type: 'string')], + )), + new OA\Response(response: 401, ref: '#/components/responses/401'), + new OA\Response(response: 400, ref: '#/components/responses/400'), + new OA\Response(response: 404, ref: '#/components/responses/404'), + new OA\Response(response: 422, ref: '#/components/responses/422'), + ] + )] + public function delete_storage(Request $request): JsonResponse + { + $teamId = getTeamIdFromToken(); + if (is_null($teamId)) { + return invalidTokenResponse(); + } + + $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first(); + if (! $service) { + return response()->json(['message' => 'Service not found.'], 404); + } + + $this->authorize('update', $service); + + $storageUuid = $request->route('storage_uuid'); + + $storage = null; + foreach ($service->applications as $app) { + $storage = $app->persistentStorages->where('uuid', $storageUuid)->first(); + if ($storage) { + break; + } + } + if (! $storage) { + foreach ($service->databases as $db) { + $storage = $db->persistentStorages->where('uuid', $storageUuid)->first(); + if ($storage) { + break; + } + } + } + if (! $storage) { + foreach ($service->applications as $app) { + $storage = $app->fileStorages->where('uuid', $storageUuid)->first(); + if ($storage) { + break; + } + } + } + if (! $storage) { + foreach ($service->databases as $db) { + $storage = $db->fileStorages->where('uuid', $storageUuid)->first(); + if ($storage) { + break; + } + } + } + + if (! $storage) { + return response()->json(['message' => 'Storage not found.'], 404); + } + + if ($storage->shouldBeReadOnlyInUI()) { + return response()->json([ + 'message' => 'This storage is read-only (managed by docker-compose or service definition) and cannot be deleted.', + ], 422); + } + + if ($storage instanceof LocalFileVolume) { + $storage->deleteStorageOnServer(); + } + + $storage->delete(); + + return response()->json(['message' => 'Storage deleted.']); + } } 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/Http/Controllers/Webhook/Github.php b/app/Http/Controllers/Webhook/Github.php index e5a5b746e..fe49369ea 100644 --- a/app/Http/Controllers/Webhook/Github.php +++ b/app/Http/Controllers/Webhook/Github.php @@ -55,6 +55,9 @@ public function manual(Request $request) $after_sha = data_get($payload, 'after', data_get($payload, 'pull_request.head.sha')); $author_association = data_get($payload, 'pull_request.author_association'); } + if (! in_array($x_github_event, ['push', 'pull_request'])) { + return response("Nothing to do. Event '$x_github_event' is not supported."); + } if (! $branch) { return response('Nothing to do. No branch found in the request.'); } @@ -246,6 +249,9 @@ public function normal(Request $request) $after_sha = data_get($payload, 'after', data_get($payload, 'pull_request.head.sha')); $author_association = data_get($payload, 'pull_request.author_association'); } + if (! in_array($x_github_event, ['push', 'pull_request'])) { + return response("Nothing to do. Event '$x_github_event' is not supported."); + } if (! $id || ! $branch) { return response('Nothing to do. No id or branch found.'); } diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php index e30af5cc7..785e8c8e3 100644 --- a/app/Jobs/ApplicationDeploymentJob.php +++ b/app/Jobs/ApplicationDeploymentJob.php @@ -19,6 +19,7 @@ use App\Models\SwarmDocker; use App\Notifications\Application\DeploymentFailed; use App\Notifications\Application\DeploymentSuccess; +use App\Support\ValidationPatterns; use App\Traits\EnvironmentVariableAnalyzer; use App\Traits\ExecuteRemoteCommand; use Carbon\Carbon; @@ -317,7 +318,7 @@ public function handle(): void if ($this->application->dockerfile_target_build) { $target = $this->application->dockerfile_target_build; - if (! preg_match(\App\Support\ValidationPatterns::DOCKER_TARGET_PATTERN, $target)) { + if (! preg_match(ValidationPatterns::DOCKER_TARGET_PATTERN, $target)) { throw new \RuntimeException('Invalid dockerfile_target_build: contains forbidden characters.'); } $this->buildTarget = " --target {$target} "; @@ -451,7 +452,7 @@ private function detectBuildKitCapabilities(): void $this->application_deployment_queue->addLogEntry("Docker on {$serverName} does not support build secrets. Using traditional build arguments."); } } - } catch (\Exception $e) { + } catch (Exception $e) { $this->dockerBuildkitSupported = false; $this->dockerSecretsSupported = false; $this->application_deployment_queue->addLogEntry("Could not detect BuildKit capabilities on {$serverName}: {$e->getMessage()}"); @@ -491,7 +492,7 @@ private function post_deployment() // Then handle side effects - these should not fail the deployment try { GetContainersStatus::dispatch($this->server); - } catch (\Exception $e) { + } catch (Exception $e) { \Log::warning('Failed to dispatch GetContainersStatus for deployment '.$this->deployment_uuid.': '.$e->getMessage()); } @@ -499,7 +500,7 @@ private function post_deployment() if ($this->application->is_github_based()) { try { ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::FINISHED); - } catch (\Exception $e) { + } catch (Exception $e) { \Log::warning('Failed to dispatch PR update for deployment '.$this->deployment_uuid.': '.$e->getMessage()); } } @@ -507,13 +508,13 @@ private function post_deployment() try { $this->run_post_deployment_command(); - } catch (\Exception $e) { + } catch (Exception $e) { \Log::warning('Post deployment command failed for '.$this->deployment_uuid.': '.$e->getMessage()); } try { $this->application->isConfigurationChanged(true); - } catch (\Exception $e) { + } catch (Exception $e) { \Log::warning('Failed to mark configuration as changed for deployment '.$this->deployment_uuid.': '.$e->getMessage()); } } @@ -695,7 +696,7 @@ private function deploy_docker_compose_buildpack() } // Inject build arguments after build subcommand if not using build secrets - if (! $this->application->settings->use_build_secrets && $this->build_args instanceof \Illuminate\Support\Collection && $this->build_args->isNotEmpty()) { + if (! $this->application->settings->use_build_secrets && $this->build_args instanceof Collection && $this->build_args->isNotEmpty()) { $build_args_string = $this->build_args->implode(' '); // Inject build args right after 'build' subcommand (not at the end) @@ -733,7 +734,7 @@ private function deploy_docker_compose_buildpack() $command .= " --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} build --pull"; } - if (! $this->application->settings->use_build_secrets && $this->build_args instanceof \Illuminate\Support\Collection && $this->build_args->isNotEmpty()) { + if (! $this->application->settings->use_build_secrets && $this->build_args instanceof Collection && $this->build_args->isNotEmpty()) { $build_args_string = $this->build_args->implode(' '); $command .= " {$build_args_string}"; $this->application_deployment_queue->addLogEntry('Adding build arguments to Docker Compose build command.'); @@ -783,7 +784,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 +802,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 +819,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 +835,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(); } @@ -1333,6 +1334,22 @@ private function generate_runtime_environment_variables() foreach ($runtime_environment_variables_preview as $env) { $envs->push($env->key.'='.$env->real_value); } + + // 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->real_value); + } + } + // 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()) { @@ -2112,7 +2129,7 @@ private function set_coolify_variables() private function check_git_if_build_needed() { - if (is_object($this->source) && $this->source->getMorphClass() === \App\Models\GithubApp::class && $this->source->is_public === false) { + if (is_object($this->source) && $this->source->getMorphClass() === GithubApp::class && $this->source->is_public === false) { $repository = githubApi($this->source, "repos/{$this->customRepository}"); $data = data_get($repository, 'data'); $repository_project_id = data_get($data, 'id'); @@ -2334,13 +2351,13 @@ private function nixpacks_build_cmd() $this->generate_nixpacks_env_variables(); $nixpacks_command = "nixpacks plan -f json {$this->env_nixpacks_args}"; if ($this->application->build_command) { - $nixpacks_command .= " --build-cmd \"{$this->application->build_command}\""; + $nixpacks_command .= ' --build-cmd '.escapeShellValue($this->application->build_command); } if ($this->application->start_command) { - $nixpacks_command .= " --start-cmd \"{$this->application->start_command}\""; + $nixpacks_command .= ' --start-cmd '.escapeShellValue($this->application->start_command); } if ($this->application->install_command) { - $nixpacks_command .= " --install-cmd \"{$this->application->install_command}\""; + $nixpacks_command .= ' --install-cmd '.escapeShellValue($this->application->install_command); } $nixpacks_command .= " {$this->workdir}"; @@ -2353,13 +2370,15 @@ private function generate_nixpacks_env_variables() if ($this->pull_request_id === 0) { foreach ($this->application->nixpacks_environment_variables as $env) { if (! is_null($env->real_value) && $env->real_value !== '') { - $this->env_nixpacks_args->push("--env {$env->key}={$env->real_value}"); + $value = ($env->is_literal || $env->is_multiline) ? trim($env->real_value, "'") : $env->real_value; + $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 !== '') { - $this->env_nixpacks_args->push("--env {$env->key}={$env->real_value}"); + $value = ($env->is_literal || $env->is_multiline) ? trim($env->real_value, "'") : $env->real_value; + $this->env_nixpacks_args->push('--env '.escapeShellValue("{$env->key}={$value}")); } } } @@ -2369,7 +2388,7 @@ private function generate_nixpacks_env_variables() $coolify_envs->each(function ($value, $key) { // Only add environment variables with non-null and non-empty values if (! is_null($value) && $value !== '') { - $this->env_nixpacks_args->push("--env {$key}={$value}"); + $this->env_nixpacks_args->push('--env '.escapeShellValue("{$key}={$value}")); } }); @@ -2946,7 +2965,7 @@ private function build_image() } // Always convert build_args Collection to string for command interpolation - $this->build_args = $this->build_args instanceof \Illuminate\Support\Collection + $this->build_args = $this->build_args instanceof Collection ? $this->build_args->implode(' ') : (string) $this->build_args; @@ -3947,7 +3966,7 @@ private function add_build_secrets_to_compose($composeFile) $composeFile['services'] = $services; $existingSecrets = data_get($composeFile, 'secrets', []); - if ($existingSecrets instanceof \Illuminate\Support\Collection) { + if ($existingSecrets instanceof Collection) { $existingSecrets = $existingSecrets->toArray(); } $composeFile['secrets'] = array_replace($existingSecrets, $secrets); @@ -3959,7 +3978,7 @@ private function add_build_secrets_to_compose($composeFile) private function validatePathField(string $value, string $fieldName): string { - if (! preg_match(\App\Support\ValidationPatterns::FILE_PATH_PATTERN, $value)) { + if (! preg_match(ValidationPatterns::FILE_PATH_PATTERN, $value)) { throw new \RuntimeException("Invalid {$fieldName}: contains forbidden characters."); } if (str_contains($value, '..')) { @@ -3971,7 +3990,7 @@ private function validatePathField(string $value, string $fieldName): string private function validateShellSafeCommand(string $value, string $fieldName): string { - if (! preg_match(\App\Support\ValidationPatterns::SHELL_SAFE_COMMAND_PATTERN, $value)) { + if (! preg_match(ValidationPatterns::SHELL_SAFE_COMMAND_PATTERN, $value)) { throw new \RuntimeException("Invalid {$fieldName}: contains forbidden shell characters."); } @@ -3980,7 +3999,7 @@ private function validateShellSafeCommand(string $value, string $fieldName): str private function validateContainerName(string $value): string { - if (! preg_match(\App\Support\ValidationPatterns::CONTAINER_NAME_PATTERN, $value)) { + if (! preg_match(ValidationPatterns::CONTAINER_NAME_PATTERN, $value)) { throw new \RuntimeException('Invalid container name: contains forbidden characters.'); } @@ -4011,7 +4030,10 @@ private function run_pre_deployment_command() // members can set these commands, and execution is scoped to the application's own container. // The single-quote escaping here prevents breaking out of the sh -c wrapper, but does not // restrict the command itself. Container names are validated separately via validateContainerName(). - $cmd = "sh -c '".str_replace("'", "'\''", $this->application->pre_deployment_command)."'"; + // Newlines are normalized to spaces to prevent injection via SSH heredoc transport + // (matches the pattern used for health_check_command at line ~2824). + $preCommand = str_replace(["\r\n", "\r", "\n"], ' ', $this->application->pre_deployment_command); + $cmd = "sh -c '".str_replace("'", "'\''", $preCommand)."'"; $exec = "docker exec {$containerName} {$cmd}"; $this->execute_remote_command( [ @@ -4043,7 +4065,9 @@ private function run_post_deployment_command() if ($containers->count() == 1 || str_starts_with($containerName, $this->application->post_deployment_command_container.'-'.$this->application->uuid)) { // Security: post_deployment_command is intentionally treated as arbitrary shell input. // See the equivalent comment in run_pre_deployment_command() for the full security rationale. - $cmd = "sh -c '".str_replace("'", "'\''", $this->application->post_deployment_command)."'"; + // Newlines are normalized to spaces to prevent injection via SSH heredoc transport. + $postCommand = str_replace(["\r\n", "\r", "\n"], ' ', $this->application->post_deployment_command); + $cmd = "sh -c '".str_replace("'", "'\''", $postCommand)."'"; $exec = "docker exec {$containerName} {$cmd}"; try { $this->execute_remote_command( diff --git a/app/Jobs/DatabaseBackupJob.php b/app/Jobs/DatabaseBackupJob.php index b55c324be..7f1feaa21 100644 --- a/app/Jobs/DatabaseBackupJob.php +++ b/app/Jobs/DatabaseBackupJob.php @@ -91,7 +91,7 @@ public function handle(): void return; } - if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) { + if (data_get($this->backup, 'database_type') === ServiceDatabase::class) { $this->database = data_get($this->backup, 'database'); $this->server = $this->database->service->server; $this->s3 = $this->backup->s3; @@ -119,7 +119,7 @@ public function handle(): void return; } - if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) { + if (data_get($this->backup, 'database_type') === ServiceDatabase::class) { $databaseType = $this->database->databaseType(); $serviceUuid = $this->database->service->uuid; $serviceName = str($this->database->service->name)->slug(); @@ -241,7 +241,7 @@ public function handle(): void } } - } catch (\Throwable $e) { + } catch (Throwable $e) { // Continue without env vars - will be handled in backup_standalone_mongodb method } } @@ -388,7 +388,7 @@ public function handle(): void } else { throw new \Exception('Local backup file is empty or was not created'); } - } catch (\Throwable $e) { + } catch (Throwable $e) { // Local backup failed if ($this->backup_log) { $this->backup_log->update([ @@ -399,7 +399,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 +423,7 @@ public function handle(): void deleteBackupsLocally($this->backup_location, $this->server); $localStorageDeleted = true; } - } catch (\Throwable $e) { + } catch (Throwable $e) { // S3 upload failed but local backup succeeded $s3UploadError = $e->getMessage(); } @@ -439,18 +447,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 +489,23 @@ private function backup_standalone_mongodb(string $databaseWithCollections): voi // For service-based MongoDB, try to build URL from environment variables if (filled($this->mongo_root_username) && filled($this->mongo_root_password)) { // Use container name instead of server IP for service-based MongoDB - $url = "mongodb://{$this->mongo_root_username}:{$this->mongo_root_password}@{$this->container_name}:27017"; + // URL-encode credentials to prevent URI injection + $encodedUser = rawurlencode($this->mongo_root_username); + $encodedPass = rawurlencode($this->mongo_root_password); + $url = "mongodb://{$encodedUser}:{$encodedPass}@{$this->container_name}:27017"; } else { // If no environment variables are available, throw an exception throw new \Exception('MongoDB credentials not found. Ensure MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD environment variables are available in the container.'); } } Log::info('MongoDB backup URL configured', ['has_url' => filled($url), 'using_env_vars' => blank($this->database->internal_db_url)]); + $escapedUrl = escapeshellarg($url); if ($databaseWithCollections === 'all') { $commands[] = 'mkdir -p '.$this->backup_dir; if (str($this->database->image)->startsWith('mongo:4')) { - $commands[] = "docker exec $this->container_name mongodump --uri=\"$url\" --gzip --archive > $this->backup_location"; + $commands[] = "docker exec $this->container_name mongodump --uri=$escapedUrl --gzip --archive > $this->backup_location"; } else { - $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --gzip --archive > $this->backup_location"; + $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$escapedUrl --gzip --archive > $this->backup_location"; } } else { if (str($databaseWithCollections)->contains(':')) { @@ -502,15 +523,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 +548,7 @@ private function backup_standalone_mongodb(string $databaseWithCollections): voi if ($this->backup_output === '') { $this->backup_output = null; } - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->add_to_error_output($e->getMessage()); throw $e; } @@ -531,15 +560,16 @@ private function backup_standalone_postgresql(string $database): void $commands[] = 'mkdir -p '.$this->backup_dir; $backupCommand = 'docker exec'; if ($this->postgres_password) { - $backupCommand .= " -e PGPASSWORD=\"{$this->postgres_password}\""; + $backupCommand .= ' -e PGPASSWORD='.escapeshellarg($this->postgres_password); } + $escapedUsername = escapeshellarg($this->database->postgres_user); if ($this->backup->dump_all) { - $backupCommand .= " $this->container_name pg_dumpall --username {$this->database->postgres_user} | gzip > $this->backup_location"; + $backupCommand .= " $this->container_name pg_dumpall --username $escapedUsername | gzip > $this->backup_location"; } else { // Validate and escape database name to prevent command injection validateShellSafePath($database, 'database name'); $escapedDatabase = escapeshellarg($database); - $backupCommand .= " $this->container_name pg_dump --format=custom --no-acl --no-owner --username {$this->database->postgres_user} $escapedDatabase > $this->backup_location"; + $backupCommand .= " $this->container_name pg_dump --format=custom --no-acl --no-owner --username $escapedUsername $escapedDatabase > $this->backup_location"; } $commands[] = $backupCommand; @@ -548,7 +578,7 @@ private function backup_standalone_postgresql(string $database): void if ($this->backup_output === '') { $this->backup_output = null; } - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->add_to_error_output($e->getMessage()); throw $e; } @@ -558,20 +588,21 @@ private function backup_standalone_mysql(string $database): void { try { $commands[] = 'mkdir -p '.$this->backup_dir; + $escapedPassword = escapeshellarg($this->database->mysql_root_password); if ($this->backup->dump_all) { - $commands[] = "docker exec $this->container_name mysqldump -u root -p\"{$this->database->mysql_root_password}\" --all-databases --single-transaction --quick --lock-tables=false --compress | gzip > $this->backup_location"; + $commands[] = "docker exec $this->container_name mysqldump -u root -p$escapedPassword --all-databases --single-transaction --quick --lock-tables=false --compress | gzip > $this->backup_location"; } else { // Validate and escape database name to prevent command injection validateShellSafePath($database, 'database name'); $escapedDatabase = escapeshellarg($database); - $commands[] = "docker exec $this->container_name mysqldump -u root -p\"{$this->database->mysql_root_password}\" $escapedDatabase > $this->backup_location"; + $commands[] = "docker exec $this->container_name mysqldump -u root -p$escapedPassword $escapedDatabase > $this->backup_location"; } $this->backup_output = instant_remote_process($commands, $this->server, true, false, $this->timeout, disableMultiplexing: true); $this->backup_output = trim($this->backup_output); if ($this->backup_output === '') { $this->backup_output = null; } - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->add_to_error_output($e->getMessage()); throw $e; } @@ -581,20 +612,21 @@ private function backup_standalone_mariadb(string $database): void { try { $commands[] = 'mkdir -p '.$this->backup_dir; + $escapedPassword = escapeshellarg($this->database->mariadb_root_password); if ($this->backup->dump_all) { - $commands[] = "docker exec $this->container_name mariadb-dump -u root -p\"{$this->database->mariadb_root_password}\" --all-databases --single-transaction --quick --lock-tables=false --compress > $this->backup_location"; + $commands[] = "docker exec $this->container_name mariadb-dump -u root -p$escapedPassword --all-databases --single-transaction --quick --lock-tables=false --compress > $this->backup_location"; } else { // Validate and escape database name to prevent command injection validateShellSafePath($database, 'database name'); $escapedDatabase = escapeshellarg($database); - $commands[] = "docker exec $this->container_name mariadb-dump -u root -p\"{$this->database->mariadb_root_password}\" $escapedDatabase > $this->backup_location"; + $commands[] = "docker exec $this->container_name mariadb-dump -u root -p$escapedPassword $escapedDatabase > $this->backup_location"; } $this->backup_output = instant_remote_process($commands, $this->server, true, false, $this->timeout, disableMultiplexing: true); $this->backup_output = trim($this->backup_output); if ($this->backup_output === '') { $this->backup_output = null; } - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->add_to_error_output($e->getMessage()); throw $e; } @@ -641,7 +673,7 @@ private function upload_to_s3(): void $bucket = $this->s3->bucket; $endpoint = $this->s3->endpoint; $this->s3->testConnection(shouldSave: true); - if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) { + if (data_get($this->backup, 'database_type') === ServiceDatabase::class) { $network = $this->database->service->destination->network; } else { $network = $this->database->destination->network; @@ -676,7 +708,7 @@ private function upload_to_s3(): void instant_remote_process($commands, $this->server, true, false, null, disableMultiplexing: true); $this->s3_uploaded = true; - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->s3_uploaded = false; $this->add_to_error_output($e->getMessage()); throw $e; @@ -710,20 +742,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/DockerCleanupJob.php b/app/Jobs/DockerCleanupJob.php index a8a3cb159..16f3d88ad 100644 --- a/app/Jobs/DockerCleanupJob.php +++ b/app/Jobs/DockerCleanupJob.php @@ -46,14 +46,20 @@ public function __construct( public function handle(): void { try { - if (! $this->server->isFunctional()) { - return; - } - $this->execution_log = DockerCleanupExecution::create([ 'server_id' => $this->server->id, ]); + if (! $this->server->isFunctional()) { + $this->execution_log->update([ + 'status' => 'failed', + 'message' => 'Server is not functional (unreachable, unusable, or disabled)', + 'finished_at' => Carbon::now()->toImmutable(), + ]); + + return; + } + $this->usageBefore = $this->server->getDiskUsage(); if ($this->manualCleanup || $this->server->settings->force_docker_cleanup) { diff --git a/app/Jobs/ScheduledJobManager.php b/app/Jobs/ScheduledJobManager.php index ebcd229ed..71829ea41 100644 --- a/app/Jobs/ScheduledJobManager.php +++ b/app/Jobs/ScheduledJobManager.php @@ -6,7 +6,6 @@ use App\Models\ScheduledTask; use App\Models\Server; use App\Models\Team; -use Cron\CronExpression; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; @@ -185,7 +184,7 @@ private function processScheduledBackups(): void $frequency = VALID_CRON_STRINGS[$frequency]; } - if ($this->shouldRunNow($frequency, $serverTimezone, "scheduled-backup:{$backup->id}")) { + if (shouldRunCronNow($frequency, $serverTimezone, "scheduled-backup:{$backup->id}", $this->executionTime)) { DatabaseBackupJob::dispatch($backup); $this->dispatchedCount++; Log::channel('scheduled')->info('Backup dispatched', [ @@ -239,7 +238,7 @@ private function processScheduledTasks(): void $frequency = VALID_CRON_STRINGS[$frequency]; } - if (! $this->shouldRunNow($frequency, $serverTimezone, "scheduled-task:{$task->id}")) { + if (! shouldRunCronNow($frequency, $serverTimezone, "scheduled-task:{$task->id}", $this->executionTime)) { continue; } @@ -336,51 +335,6 @@ private function getTaskRuntimeSkipReason(ScheduledTask $task): ?string return null; } - /** - * Determine if a cron schedule should run now. - * - * When a dedupKey is provided, uses getPreviousRunDate() + last-dispatch tracking - * instead of isDue(). This is resilient to queue delays — even if the job is delayed - * by minutes, it still catches the missed cron window. Without dedupKey, falls back - * to simple isDue() check. - */ - private function shouldRunNow(string $frequency, string $timezone, ?string $dedupKey = null): bool - { - $cron = new CronExpression($frequency); - $baseTime = $this->executionTime ?? Carbon::now(); - $executionTime = $baseTime->copy()->setTimezone($timezone); - - // No dedup key → simple isDue check - if ($dedupKey === null) { - return $cron->isDue($executionTime); - } - - // Get the most recent time this cron was due (including current minute) - $previousDue = Carbon::instance($cron->getPreviousRunDate($executionTime, allowCurrentDate: true)); - - $lastDispatched = Cache::get($dedupKey); - - if ($lastDispatched === null) { - // First run after restart or cache loss: only fire if actually due right now. - // Seed the cache so subsequent runs can use tolerance/catch-up logic. - $isDue = $cron->isDue($executionTime); - if ($isDue) { - Cache::put($dedupKey, $executionTime->toIso8601String(), 86400); - } - - return $isDue; - } - - // Subsequent runs: fire if there's been a due time since last dispatch - if ($previousDue->gt(Carbon::parse($lastDispatched))) { - Cache::put($dedupKey, $executionTime->toIso8601String(), 86400); - - return true; - } - - return false; - } - private function processDockerCleanups(): void { // Get all servers that need cleanup checks @@ -411,7 +365,7 @@ private function processDockerCleanups(): void } // Use the frozen execution time for consistent evaluation - if ($this->shouldRunNow($frequency, $serverTimezone, "docker-cleanup:{$server->id}")) { + if (shouldRunCronNow($frequency, $serverTimezone, "docker-cleanup:{$server->id}", $this->executionTime)) { DockerCleanupJob::dispatch( $server, false, 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/ServerManagerJob.php b/app/Jobs/ServerManagerJob.php index d56ff0a8c..3f748f0ca 100644 --- a/app/Jobs/ServerManagerJob.php +++ b/app/Jobs/ServerManagerJob.php @@ -5,7 +5,6 @@ use App\Models\InstanceSettings; use App\Models\Server; use App\Models\Team; -use Cron\CronExpression; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; @@ -14,7 +13,6 @@ use Illuminate\Queue\SerializesModels; use Illuminate\Support\Carbon; use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; class ServerManagerJob implements ShouldBeEncrypted, ShouldQueue @@ -81,7 +79,7 @@ private function getServers(): Collection private function dispatchConnectionChecks(Collection $servers): void { - if ($this->shouldRunNow($this->checkFrequency, dedupKey: 'server-connection-checks')) { + if (shouldRunCronNow($this->checkFrequency, $this->instanceTimezone, 'server-connection-checks', $this->executionTime)) { $servers->each(function (Server $server) { try { // Skip SSH connection check if Sentinel is healthy — its heartbeat already proves connectivity @@ -130,13 +128,13 @@ private function processServerTasks(Server $server): void if ($sentinelOutOfSync) { // Dispatch ServerCheckJob if Sentinel is out of sync - if ($this->shouldRunNow($this->checkFrequency, $serverTimezone, "server-check:{$server->id}")) { + if (shouldRunCronNow($this->checkFrequency, $serverTimezone, "server-check:{$server->id}", $this->executionTime)) { ServerCheckJob::dispatch($server); } } $isSentinelEnabled = $server->isSentinelEnabled(); - $shouldRestartSentinel = $isSentinelEnabled && $this->shouldRunNow('0 0 * * *', $serverTimezone, "sentinel-restart:{$server->id}"); + $shouldRestartSentinel = $isSentinelEnabled && shouldRunCronNow('0 0 * * *', $serverTimezone, "sentinel-restart:{$server->id}", $this->executionTime); // Dispatch Sentinel restart if due (daily for Sentinel-enabled servers) if ($shouldRestartSentinel) { @@ -150,7 +148,7 @@ private function processServerTasks(Server $server): void if (isset(VALID_CRON_STRINGS[$serverDiskUsageCheckFrequency])) { $serverDiskUsageCheckFrequency = VALID_CRON_STRINGS[$serverDiskUsageCheckFrequency]; } - $shouldRunStorageCheck = $this->shouldRunNow($serverDiskUsageCheckFrequency, $serverTimezone, "server-storage-check:{$server->id}"); + $shouldRunStorageCheck = shouldRunCronNow($serverDiskUsageCheckFrequency, $serverTimezone, "server-storage-check:{$server->id}", $this->executionTime); if ($shouldRunStorageCheck) { ServerStorageCheckJob::dispatch($server); @@ -158,7 +156,7 @@ private function processServerTasks(Server $server): void } // Dispatch ServerPatchCheckJob if due (weekly) - $shouldRunPatchCheck = $this->shouldRunNow('0 0 * * 0', $serverTimezone, "server-patch-check:{$server->id}"); + $shouldRunPatchCheck = shouldRunCronNow('0 0 * * 0', $serverTimezone, "server-patch-check:{$server->id}", $this->executionTime); if ($shouldRunPatchCheck) { // Weekly on Sunday at midnight ServerPatchCheckJob::dispatch($server); @@ -167,45 +165,4 @@ 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 if a cron schedule should run now. - * - * When a dedupKey is provided, uses getPreviousRunDate() + last-dispatch tracking - * instead of isDue(). This is resilient to queue delays — even if the job is delayed - * by minutes, it still catches the missed cron window. - */ - private function shouldRunNow(string $frequency, ?string $timezone = null, ?string $dedupKey = null): bool - { - $cron = new CronExpression($frequency); - - // Use the frozen execution time, not the current time - $baseTime = $this->executionTime ?? Carbon::now(); - $executionTime = $baseTime->copy()->setTimezone($timezone ?? config('app.timezone')); - - if ($dedupKey === null) { - return $cron->isDue($executionTime); - } - - $previousDue = Carbon::instance($cron->getPreviousRunDate($executionTime, allowCurrentDate: true)); - - $lastDispatched = Cache::get($dedupKey); - - if ($lastDispatched === null) { - $isDue = $cron->isDue($executionTime); - if ($isDue) { - Cache::put($dedupKey, $executionTime->toIso8601String(), 86400); - } - - return $isDue; - } - - if ($previousDue->gt(Carbon::parse($lastDispatched))) { - Cache::put($dedupKey, $executionTime->toIso8601String(), 86400); - - return true; - } - - return false; - } } diff --git a/app/Jobs/StripeProcessJob.php b/app/Jobs/StripeProcessJob.php index f5d52f29c..3485ffe32 100644 --- a/app/Jobs/StripeProcessJob.php +++ b/app/Jobs/StripeProcessJob.php @@ -73,25 +73,15 @@ public function handle(): void // send_internal_notification("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}."); throw new \RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}."); } - $subscription = Subscription::where('team_id', $teamId)->first(); - if ($subscription) { - // send_internal_notification('Old subscription activated for team: '.$teamId); - $subscription->update([ + Subscription::updateOrCreate( + ['team_id' => $teamId], + [ 'stripe_subscription_id' => $subscriptionId, 'stripe_customer_id' => $customerId, 'stripe_invoice_paid' => true, 'stripe_past_due' => false, - ]); - } else { - // send_internal_notification('New subscription for team: '.$teamId); - Subscription::create([ - 'team_id' => $teamId, - 'stripe_subscription_id' => $subscriptionId, - 'stripe_customer_id' => $customerId, - 'stripe_invoice_paid' => true, - 'stripe_past_due' => false, - ]); - } + ] + ); break; case 'invoice.paid': $customerId = data_get($data, 'customer'); @@ -227,18 +217,14 @@ public function handle(): void // send_internal_notification("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}."); throw new \RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}."); } - $subscription = Subscription::where('team_id', $teamId)->first(); - if ($subscription) { - // send_internal_notification("Subscription already exists for team: {$teamId}"); - throw new \RuntimeException("Subscription already exists for team: {$teamId}"); - } else { - Subscription::create([ - 'team_id' => $teamId, + Subscription::updateOrCreate( + ['team_id' => $teamId], + [ 'stripe_subscription_id' => $subscriptionId, 'stripe_customer_id' => $customerId, 'stripe_invoice_paid' => false, - ]); - } + ] + ); break; case 'customer.subscription.updated': $teamId = data_get($data, 'metadata.team_id'); @@ -254,20 +240,19 @@ public function handle(): void $subscription = Subscription::where('stripe_customer_id', $customerId)->first(); if (! $subscription) { if ($status === 'incomplete_expired') { - // send_internal_notification('Subscription incomplete expired'); throw new \RuntimeException('Subscription incomplete expired'); } - if ($teamId) { - $subscription = Subscription::create([ - 'team_id' => $teamId, + if (! $teamId) { + throw new \RuntimeException('No subscription and team id found'); + } + $subscription = Subscription::firstOrCreate( + ['team_id' => $teamId], + [ 'stripe_subscription_id' => $subscriptionId, 'stripe_customer_id' => $customerId, 'stripe_invoice_paid' => false, - ]); - } else { - // send_internal_notification('No subscription and team id found'); - throw new \RuntimeException('No subscription and team id found'); - } + ] + ); } $cancelAtPeriodEnd = data_get($data, 'cancel_at_period_end'); $feedback = data_get($data, 'cancellation_details.feedback'); 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/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/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..5c186af70 100644 --- a/app/Livewire/Project/Application/General.php +++ b/app/Livewire/Project/Application/General.php @@ -3,11 +3,14 @@ namespace App\Livewire\Project\Application; use App\Actions\Application\GenerateConfig; +use App\Jobs\ApplicationDeploymentJob; use App\Models\Application; use App\Support\ValidationPatterns; +use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Collection; use Livewire\Component; +use Livewire\Features\SupportEvents\Event; use Spatie\Url\Url; use Visus\Cuid2\Cuid2; @@ -194,9 +197,9 @@ protected function messages(): array 'baseDirectory.regex' => 'The base directory must be a valid path starting with / and containing only safe characters.', 'publishDirectory.regex' => 'The publish directory must be a valid path starting with / and containing only safe characters.', 'dockerfileTargetBuild.regex' => 'The Dockerfile target build must contain only alphanumeric characters, dots, hyphens, and underscores.', - 'dockerComposeCustomStartCommand.regex' => 'The Docker Compose start command contains invalid characters. Shell operators like ;, &, |, $, and backticks are not allowed.', - 'dockerComposeCustomBuildCommand.regex' => 'The Docker Compose build command contains invalid characters. Shell operators like ;, &, |, $, and backticks are not allowed.', - 'customDockerRunOptions.regex' => 'The custom Docker run options contain invalid characters. Shell operators like ;, &, |, $, and backticks are not allowed.', + 'dockerComposeCustomStartCommand.regex' => 'The Docker Compose start command contains invalid characters. Shell operators like ;, |, $, and backticks are not allowed.', + 'dockerComposeCustomBuildCommand.regex' => 'The Docker Compose build command contains invalid characters. Shell operators like ;, |, $, and backticks are not allowed.', + 'customDockerRunOptions.regex' => 'The custom Docker run options contain invalid characters. Shell operators like ;, |, $, and backticks are not allowed.', 'preDeploymentCommandContainer.regex' => 'The pre-deployment command container name must contain only alphanumeric characters, dots, hyphens, and underscores.', 'postDeploymentCommandContainer.regex' => 'The post-deployment command container name must contain only alphanumeric characters, dots, hyphens, and underscores.', 'name.required' => 'The Name field is required.', @@ -288,7 +291,7 @@ public function mount() $this->authorize('update', $this->application); $this->application->fqdn = null; $this->application->settings->save(); - } catch (\Illuminate\Auth\Access\AuthorizationException $e) { + } catch (AuthorizationException $e) { // User doesn't have update permission, just continue without saving } } @@ -309,7 +312,7 @@ public function mount() $this->customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n"); $this->application->custom_labels = base64_encode($this->customLabels); $this->application->save(); - } catch (\Illuminate\Auth\Access\AuthorizationException $e) { + } catch (AuthorizationException $e) { // User doesn't have update permission, just use existing labels // $this->customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n"); } @@ -321,7 +324,7 @@ public function mount() $this->authorize('update', $this->application); $this->initLoadingCompose = true; $this->dispatch('info', 'Loading docker compose file.'); - } catch (\Illuminate\Auth\Access\AuthorizationException $e) { + } catch (AuthorizationException $e) { // User doesn't have update permission, skip loading compose file } } @@ -587,7 +590,7 @@ public function updatedBuildPack() // Check if user has permission to update try { $this->authorize('update', $this->application); - } catch (\Illuminate\Auth\Access\AuthorizationException $e) { + } catch (AuthorizationException $e) { // User doesn't have permission, revert the change and return $this->application->refresh(); $this->syncData(); @@ -612,7 +615,7 @@ public function updatedBuildPack() $this->fqdn = null; $this->application->fqdn = null; $this->application->settings->save(); - } catch (\Illuminate\Auth\Access\AuthorizationException $e) { + } catch (AuthorizationException $e) { // User doesn't have update permission, just continue without saving } } @@ -809,7 +812,7 @@ public function submit($showToaster = true) restoreBaseDirectory: $oldBaseDirectory, restoreDockerComposeLocation: $oldDockerComposeLocation ); - if ($compose_return instanceof \Livewire\Features\SupportEvents\Event) { + if ($compose_return instanceof Event) { // Validation failed - restore original values to component properties $this->baseDirectory = $oldBaseDirectory; $this->dockerComposeLocation = $oldDockerComposeLocation; @@ -939,7 +942,7 @@ public function getDockerComposeBuildCommandPreviewProperty(): string $command = injectDockerComposeFlags( $this->dockerComposeCustomBuildCommand, ".{$normalizedBase}{$this->dockerComposeLocation}", - \App\Jobs\ApplicationDeploymentJob::BUILD_TIME_ENV_PATH + ApplicationDeploymentJob::BUILD_TIME_ENV_PATH ); // Inject build args if not using build secrets diff --git a/app/Livewire/Project/Database/BackupEdit.php b/app/Livewire/Project/Database/BackupEdit.php index c24e2a3f1..0fff2bd03 100644 --- a/app/Livewire/Project/Database/BackupEdit.php +++ b/app/Livewire/Project/Database/BackupEdit.php @@ -105,21 +105,9 @@ public function syncData(bool $toModel = false) $this->backup->s3_storage_id = $this->s3StorageId; // Validate databases_to_backup to prevent command injection + // Handles all formats including MongoDB's "db:col1,col2|db2:col3" if (filled($this->databasesToBackup)) { - $databases = str($this->databasesToBackup)->explode(','); - foreach ($databases as $index => $db) { - $dbName = trim($db); - try { - validateShellSafePath($dbName, 'database name'); - } catch (\Exception $e) { - // Provide specific error message indicating which database failed validation - $position = $index + 1; - throw new \Exception( - "Database #{$position} ('{$dbName}') validation failed: ". - $e->getMessage() - ); - } - } + validateDatabasesBackupInput($this->databasesToBackup); } $this->backup->databases_to_backup = $this->databasesToBackup; diff --git a/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/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/Show.php b/app/Livewire/Project/Shared/EnvironmentVariable/Show.php index 2a18be13c..c567d96aa 100644 --- a/app/Livewire/Project/Shared/EnvironmentVariable/Show.php +++ b/app/Livewire/Project/Shared/EnvironmentVariable/Show.php @@ -98,6 +98,9 @@ public function getResourceProperty() public function refresh() { + if (! $this->env->exists || ! $this->env->fresh()) { + return; + } $this->syncData(); $this->checkEnvs(); } diff --git a/app/Livewire/Project/Shared/ExecuteContainerCommand.php b/app/Livewire/Project/Shared/ExecuteContainerCommand.php index df12b1d9c..4ea5e12db 100644 --- a/app/Livewire/Project/Shared/ExecuteContainerCommand.php +++ b/app/Livewire/Project/Shared/ExecuteContainerCommand.php @@ -5,6 +5,7 @@ use App\Models\Application; use App\Models\Server; use App\Models\Service; +use App\Support\ValidationPatterns; use Illuminate\Support\Collection; use Livewire\Attributes\On; use Livewire\Component; @@ -181,7 +182,7 @@ public function connectToContainer() } try { // Validate container name format - if (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $this->selected_container)) { + if (! ValidationPatterns::isValidContainerName($this->selected_container)) { throw new \InvalidArgumentException('Invalid container name format'); } diff --git a/app/Livewire/Project/Shared/Terminal.php b/app/Livewire/Project/Shared/Terminal.php index ae68b2354..bbc2b3e66 100644 --- a/app/Livewire/Project/Shared/Terminal.php +++ b/app/Livewire/Project/Shared/Terminal.php @@ -4,6 +4,7 @@ use App\Helpers\SshMultiplexingHelper; use App\Models\Server; +use App\Support\ValidationPatterns; use Livewire\Attributes\On; use Livewire\Component; @@ -36,7 +37,7 @@ public function sendTerminalCommand($isContainer, $identifier, $serverUuid) if ($isContainer) { // Validate container identifier format (alphanumeric, dashes, and underscores only) - if (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $identifier)) { + if (! ValidationPatterns::isValidContainerName($identifier)) { throw new \InvalidArgumentException('Invalid container identifier format'); } diff --git a/app/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.

Check this documentation for further help.

Error: '.$error); + $sanitizedError = htmlspecialchars($error ?? '', ENT_QUOTES, 'UTF-8'); + $this->dispatch('error', 'Server is not reachable.

Check this documentation for further help.

Error: '.$sanitizedError); return; } 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/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.

Error: '.$sanitizedError.'
'; $this->server->update([ 'validation_logs' => $this->error, ]); diff --git a/app/Livewire/Settings/Updates.php b/app/Livewire/Settings/Updates.php index 01a67c38c..a200ef689 100644 --- a/app/Livewire/Settings/Updates.php +++ b/app/Livewire/Settings/Updates.php @@ -25,6 +25,9 @@ class Updates extends Component public function mount() { + if (! isInstanceAdmin()) { + return redirect()->route('dashboard'); + } if (! isCloud()) { $this->server = Server::findOrFail(0); } diff --git a/app/Livewire/Source/Github/Change.php b/app/Livewire/Source/Github/Change.php index 17323fdec..d6537069c 100644 --- a/app/Livewire/Source/Github/Change.php +++ b/app/Livewire/Source/Github/Change.php @@ -5,6 +5,7 @@ use App\Jobs\GithubAppPermissionJob; use App\Models\GithubApp; use App\Models\PrivateKey; +use App\Rules\SafeExternalUrl; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Http; use Lcobucci\JWT\Configuration; @@ -71,24 +72,27 @@ class Change extends Component public $privateKeys; - protected $rules = [ - 'name' => 'required|string', - 'organization' => 'nullable|string', - 'apiUrl' => 'required|string', - 'htmlUrl' => 'required|string', - 'customUser' => 'required|string', - 'customPort' => 'required|int', - 'appId' => 'nullable|int', - 'installationId' => 'nullable|int', - 'clientId' => 'nullable|string', - 'clientSecret' => 'nullable|string', - 'webhookSecret' => 'nullable|string', - 'isSystemWide' => 'required|bool', - 'contents' => 'nullable|string', - 'metadata' => 'nullable|string', - 'pullRequests' => 'nullable|string', - 'privateKeyId' => 'nullable|int', - ]; + protected function rules(): array + { + return [ + 'name' => 'required|string', + 'organization' => 'nullable|string', + 'apiUrl' => ['required', 'string', 'url', new SafeExternalUrl], + 'htmlUrl' => ['required', 'string', 'url', new SafeExternalUrl], + 'customUser' => 'required|string', + 'customPort' => 'required|int', + 'appId' => 'nullable|int', + 'installationId' => 'nullable|int', + 'clientId' => 'nullable|string', + 'clientSecret' => 'nullable|string', + 'webhookSecret' => 'nullable|string', + 'isSystemWide' => 'required|bool', + 'contents' => 'nullable|string', + 'metadata' => 'nullable|string', + 'pullRequests' => 'nullable|string', + 'privateKeyId' => 'nullable|int', + ]; + } public function boot() { diff --git a/app/Livewire/Source/Github/Create.php b/app/Livewire/Source/Github/Create.php index 4ece6a92f..ec2ba3f08 100644 --- a/app/Livewire/Source/Github/Create.php +++ b/app/Livewire/Source/Github/Create.php @@ -3,6 +3,7 @@ namespace App\Livewire\Source\Github; use App\Models\GithubApp; +use App\Rules\SafeExternalUrl; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; @@ -37,8 +38,8 @@ public function createGitHubApp() $this->validate([ 'name' => 'required|string', 'organization' => 'nullable|string', - 'api_url' => 'required|string', - 'html_url' => 'required|string', + 'api_url' => ['required', 'string', 'url', new SafeExternalUrl], + 'html_url' => ['required', 'string', 'url', new SafeExternalUrl], 'custom_user' => 'required|string', 'custom_port' => 'required|int', 'is_system_wide' => 'required|bool', diff --git a/app/Livewire/Subscription/PricingPlans.php b/app/Livewire/Subscription/PricingPlans.php index 6b2d3fb36..6e1b85404 100644 --- a/app/Livewire/Subscription/PricingPlans.php +++ b/app/Livewire/Subscription/PricingPlans.php @@ -11,6 +11,12 @@ class PricingPlans extends Component { public function subscribeStripe($type) { + if (currentTeam()->subscription?->stripe_invoice_paid) { + $this->dispatch('error', 'Team already has an active subscription.'); + + return; + } + Stripe::setApiKey(config('subscription.stripe_api_key')); $priceId = match ($type) { diff --git a/app/Models/Application.php b/app/Models/Application.php index 4cc2dcf74..c446052b3 100644 --- a/app/Models/Application.php +++ b/app/Models/Application.php @@ -390,7 +390,7 @@ public function deleteVolumes() } $server = data_get($this, 'destination.server'); foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } } diff --git a/app/Models/ApplicationPreview.php b/app/Models/ApplicationPreview.php index 3b7bf3030..b8a8a5a85 100644 --- a/app/Models/ApplicationPreview.php +++ b/app/Models/ApplicationPreview.php @@ -37,7 +37,7 @@ protected static function booted() $persistentStorages = $preview->persistentStorages()->get() ?? collect(); if ($persistentStorages->count() > 0) { foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } } diff --git a/app/Models/EnvironmentVariable.php b/app/Models/EnvironmentVariable.php index cf60d5ab5..5acd4c1e4 100644 --- a/app/Models/EnvironmentVariable.php +++ b/app/Models/EnvironmentVariable.php @@ -32,6 +32,11 @@ )] class EnvironmentVariable extends BaseModel { + protected $attributes = [ + 'is_runtime' => true, + 'is_buildtime' => true, + ]; + protected $fillable = [ // Core identification 'key', diff --git a/app/Models/LocalFileVolume.php b/app/Models/LocalFileVolume.php index da58ed2f9..b954a1dd5 100644 --- a/app/Models/LocalFileVolume.php +++ b/app/Models/LocalFileVolume.php @@ -3,6 +3,7 @@ namespace App\Models; use App\Events\FileStorageChanged; +use App\Jobs\ServerStorageSaveJob; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; use Symfony\Component\Yaml\Yaml; @@ -27,7 +28,7 @@ protected static function booted() { static::created(function (LocalFileVolume $fileVolume) { $fileVolume->load(['service']); - dispatch(new \App\Jobs\ServerStorageSaveJob($fileVolume)); + dispatch(new ServerStorageSaveJob($fileVolume)); }); } @@ -129,15 +130,22 @@ public function saveStorageOnServer() $server = $this->resource->destination->server; } $commands = collect([]); + + // Validate fs_path early before any shell interpolation + validateShellSafePath($this->fs_path, 'storage path'); + $escapedFsPath = escapeshellarg($this->fs_path); + $escapedWorkdir = escapeshellarg($workdir); + if ($this->is_directory) { - $commands->push("mkdir -p $this->fs_path > /dev/null 2>&1 || true"); - $commands->push("mkdir -p $workdir > /dev/null 2>&1 || true"); - $commands->push("cd $workdir"); + $commands->push("mkdir -p {$escapedFsPath} > /dev/null 2>&1 || true"); + $commands->push("mkdir -p {$escapedWorkdir} > /dev/null 2>&1 || true"); + $commands->push("cd {$escapedWorkdir}"); } if (str($this->fs_path)->startsWith('.') || str($this->fs_path)->startsWith('/') || str($this->fs_path)->startsWith('~')) { $parent_dir = str($this->fs_path)->beforeLast('/'); if ($parent_dir != '') { - $commands->push("mkdir -p $parent_dir > /dev/null 2>&1 || true"); + $escapedParentDir = escapeshellarg($parent_dir); + $commands->push("mkdir -p {$escapedParentDir} > /dev/null 2>&1 || true"); } } $path = data_get_str($this, 'fs_path'); @@ -147,7 +155,7 @@ public function saveStorageOnServer() $path = $workdir.$path; } - // Validate and escape path to prevent command injection + // Validate and escape resolved path (may differ from fs_path if relative) validateShellSafePath($path, 'storage path'); $escapedPath = escapeshellarg($path); diff --git a/app/Models/LocalPersistentVolume.php b/app/Models/LocalPersistentVolume.php index 1721f4afe..9d539f8ec 100644 --- a/app/Models/LocalPersistentVolume.php +++ b/app/Models/LocalPersistentVolume.php @@ -3,10 +3,9 @@ namespace App\Models; use Illuminate\Database\Eloquent\Casts\Attribute; -use Illuminate\Database\Eloquent\Model; use Symfony\Component\Yaml\Yaml; -class LocalPersistentVolume extends Model +class LocalPersistentVolume extends BaseModel { protected $guarded = []; diff --git a/app/Models/Server.php b/app/Models/Server.php index 527c744a5..00843b3da 100644 --- a/app/Models/Server.php +++ b/app/Models/Server.php @@ -11,7 +11,9 @@ use App\Events\ServerReachabilityChanged; use App\Helpers\SslHelper; use App\Jobs\CheckAndStartSentinelJob; +use App\Jobs\CheckTraefikVersionForServerJob; use App\Jobs\RegenerateSslCertJob; +use App\Livewire\Server\Proxy; use App\Notifications\Server\Reachable; use App\Notifications\Server\Unreachable; use App\Services\ConfigurationRepository; @@ -77,8 +79,8 @@ * - Traefik image uses the 'latest' tag (no fixed version tracking) * - No Traefik version detected on the server * - * @see \App\Jobs\CheckTraefikVersionForServerJob Where this data is populated - * @see \App\Livewire\Server\Proxy Where this data is read and displayed + * @see CheckTraefikVersionForServerJob Where this data is populated + * @see Proxy Where this data is read and displayed */ #[OA\Schema( description: 'Server model', @@ -267,6 +269,13 @@ public static function flushIdentityMap(): void use HasSafeStringAttribute; + public function setValidationLogsAttribute($value): void + { + $this->attributes['validation_logs'] = $value !== null + ? \Stevebauman\Purify\Facades\Purify::config('validation_logs')->clean($value) + : null; + } + public function type() { return 'server'; @@ -719,17 +728,17 @@ public function definedResources() public function stopUnmanaged($id) { - return instant_remote_process(["docker stop -t 0 $id"], $this); + return instant_remote_process(['docker stop -t 0 '.escapeshellarg($id)], $this); } public function restartUnmanaged($id) { - return instant_remote_process(["docker restart $id"], $this); + return instant_remote_process(['docker restart '.escapeshellarg($id)], $this); } public function startUnmanaged($id) { - return instant_remote_process(["docker start $id"], $this); + return instant_remote_process(['docker start '.escapeshellarg($id)], $this); } public function getContainers() @@ -1460,7 +1469,7 @@ public function url() public function restartContainer(string $containerName) { - return instant_remote_process(['docker restart '.$containerName], $this, false); + return instant_remote_process(['docker restart '.escapeshellarg($containerName)], $this, false); } public function changeProxy(string $proxyType, bool $async = true) @@ -1471,6 +1480,9 @@ public function changeProxy(string $proxyType, bool $async = true) if ($validProxyTypes->contains(str($proxyType)->lower())) { $this->proxy->set('type', str($proxyType)->upper()); $this->proxy->set('status', 'exited'); + $this->proxy->set('last_saved_proxy_configuration', null); + $this->proxy->set('last_saved_settings', null); + $this->proxy->set('last_applied_settings', null); $this->save(); if ($this->proxySet()) { if ($async) { diff --git a/app/Models/StandaloneClickhouse.php b/app/Models/StandaloneClickhouse.php index 33f32dd59..143aadb6a 100644 --- a/app/Models/StandaloneClickhouse.php +++ b/app/Models/StandaloneClickhouse.php @@ -135,7 +135,7 @@ public function deleteVolumes() } $server = data_get($this, 'destination.server'); foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } diff --git a/app/Models/StandaloneDragonfly.php b/app/Models/StandaloneDragonfly.php index 074c5b509..c823c305b 100644 --- a/app/Models/StandaloneDragonfly.php +++ b/app/Models/StandaloneDragonfly.php @@ -135,7 +135,7 @@ public function deleteVolumes() } $server = data_get($this, 'destination.server'); foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } diff --git a/app/Models/StandaloneKeydb.php b/app/Models/StandaloneKeydb.php index 23b4c65e6..f286e8538 100644 --- a/app/Models/StandaloneKeydb.php +++ b/app/Models/StandaloneKeydb.php @@ -135,7 +135,7 @@ public function deleteVolumes() } $server = data_get($this, 'destination.server'); foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } diff --git a/app/Models/StandaloneMariadb.php b/app/Models/StandaloneMariadb.php index 4d4b84776..efa62353c 100644 --- a/app/Models/StandaloneMariadb.php +++ b/app/Models/StandaloneMariadb.php @@ -136,7 +136,7 @@ public function deleteVolumes() } $server = data_get($this, 'destination.server'); foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } diff --git a/app/Models/StandaloneMongodb.php b/app/Models/StandaloneMongodb.php index b5401dd2c..9418ebc21 100644 --- a/app/Models/StandaloneMongodb.php +++ b/app/Models/StandaloneMongodb.php @@ -141,7 +141,7 @@ public function deleteVolumes() } $server = data_get($this, 'destination.server'); foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } diff --git a/app/Models/StandaloneMysql.php b/app/Models/StandaloneMysql.php index 0b144575c..2b7e9f2b6 100644 --- a/app/Models/StandaloneMysql.php +++ b/app/Models/StandaloneMysql.php @@ -136,7 +136,7 @@ public function deleteVolumes() } $server = data_get($this, 'destination.server'); foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } diff --git a/app/Models/StandalonePostgresql.php b/app/Models/StandalonePostgresql.php index 92b2efd31..cea600236 100644 --- a/app/Models/StandalonePostgresql.php +++ b/app/Models/StandalonePostgresql.php @@ -114,7 +114,7 @@ public function deleteVolumes() } $server = data_get($this, 'destination.server'); foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } diff --git a/app/Models/StandaloneRedis.php b/app/Models/StandaloneRedis.php index 352d27cfd..0e904ab31 100644 --- a/app/Models/StandaloneRedis.php +++ b/app/Models/StandaloneRedis.php @@ -140,7 +140,7 @@ public function deleteVolumes() } $server = data_get($this, 'destination.server'); foreach ($persistentStorages as $storage) { - instant_remote_process(["docker volume rm -f $storage->name"], $server, false); + instant_remote_process(['docker volume rm -f '.escapeshellarg($storage->name)], $server, false); } } diff --git a/app/Models/Team.php b/app/Models/Team.php index 10b22b4e1..5a7b377b6 100644 --- a/app/Models/Team.php +++ b/app/Models/Team.php @@ -89,10 +89,13 @@ protected static function booted() }); } - public static function serverLimitReached() + public static function serverLimitReached(?Team $team = null) { - $serverLimit = Team::serverLimit(); - $team = currentTeam(); + $team = $team ?? currentTeam(); + if (! $team) { + return true; + } + $serverLimit = Team::serverLimit($team); $servers = $team->servers->count(); return $servers >= $serverLimit; @@ -109,19 +112,23 @@ public function subscriptionPastOverDue() public function serverOverflow() { - if ($this->serverLimit() < $this->servers->count()) { + if (Team::serverLimit($this) < $this->servers->count()) { return true; } return false; } - public static function serverLimit() + public static function serverLimit(?Team $team = null) { - if (currentTeam()->id === 0 && isDev()) { + $team = $team ?? currentTeam(); + if (! $team) { + return 0; + } + if ($team->id === 0 && isDev()) { return 9999999; } - $team = Team::find(currentTeam()->id); + $team = Team::find($team->id); if (! $team) { return 0; } diff --git a/app/Models/User.php b/app/Models/User.php index 4561cddb2..7c68657e7 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -395,7 +395,7 @@ public function canAccessSystemResources(): bool public function requestEmailChange(string $newEmail): void { // Generate 6-digit code - $code = sprintf('%06d', mt_rand(0, 999999)); + $code = sprintf('%06d', random_int(0, 999999)); // Set expiration using config value $expiryMinutes = config('constants.email_change.verification_code_expiry_minutes', 10); diff --git a/app/Notifications/TransactionalEmails/ResetPassword.php b/app/Notifications/TransactionalEmails/ResetPassword.php index 179c8d948..511818e21 100644 --- a/app/Notifications/TransactionalEmails/ResetPassword.php +++ b/app/Notifications/TransactionalEmails/ResetPassword.php @@ -67,9 +67,12 @@ protected function resetUrl($notifiable) return call_user_func(static::$createUrlCallback, $notifiable, $this->token); } - return url(route('password.reset', [ + $path = route('password.reset', [ 'token' => $this->token, 'email' => $notifiable->getEmailForPasswordReset(), - ], false)); + ], false); + + // Use server-side config (FQDN / public IP) instead of request host + return rtrim(base_url(), '/').$path; } } diff --git a/app/Rules/SafeExternalUrl.php b/app/Rules/SafeExternalUrl.php new file mode 100644 index 000000000..41299d6c1 --- /dev/null +++ b/app/Rules/SafeExternalUrl.php @@ -0,0 +1,81 @@ + $attribute, + 'url' => $value, + 'host' => $host, + 'ip' => request()->ip(), + 'user_id' => auth()->id(), + ]); + $fail('The :attribute must not point to internal hosts.'); + + return; + } + + // Resolve hostname to IP and block private/reserved ranges + $ip = gethostbyname($host); + + // gethostbyname returns the original hostname on failure (e.g. unresolvable) + if ($ip === $host && ! filter_var($host, FILTER_VALIDATE_IP)) { + $fail('The :attribute host could not be resolved.'); + + return; + } + + if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { + Log::warning('External URL resolves to private or reserved IP', [ + 'attribute' => $attribute, + 'url' => $value, + 'host' => $host, + 'resolved_ip' => $ip, + 'ip' => request()->ip(), + 'user_id' => auth()->id(), + ]); + $fail('The :attribute must not point to a private or reserved IP address.'); + + return; + } + } +} diff --git a/app/Rules/SafeWebhookUrl.php b/app/Rules/SafeWebhookUrl.php new file mode 100644 index 000000000..fbeb406af --- /dev/null +++ b/app/Rules/SafeWebhookUrl.php @@ -0,0 +1,95 @@ + $attribute, + 'host' => $host, + 'ip' => request()->ip(), + 'user_id' => auth()->id(), + ]); + $fail('The :attribute must not point to localhost or internal hosts.'); + + return; + } + + // Block loopback (127.0.0.0/8) and link-local/metadata (169.254.0.0/16) when IP is provided directly + if (filter_var($host, FILTER_VALIDATE_IP) && ($this->isLoopback($host) || $this->isLinkLocal($host))) { + Log::warning('Webhook URL points to blocked IP range', [ + 'attribute' => $attribute, + 'host' => $host, + 'ip' => request()->ip(), + 'user_id' => auth()->id(), + ]); + $fail('The :attribute must not point to loopback or link-local addresses.'); + + return; + } + } + + private function isLoopback(string $ip): bool + { + // 127.0.0.0/8, 0.0.0.0 + if ($ip === '0.0.0.0' || str_starts_with($ip, '127.')) { + return true; + } + + // IPv6 loopback + $normalized = @inet_pton($ip); + + return $normalized !== false && $normalized === inet_pton('::1'); + } + + private function isLinkLocal(string $ip): bool + { + // 169.254.0.0/16 — covers cloud metadata at 169.254.169.254 + if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + return false; + } + + $long = ip2long($ip); + + return $long !== false && ($long >> 16) === (ip2long('169.254.0.0') >> 16); + } +} diff --git a/app/Rules/ValidHostname.php b/app/Rules/ValidHostname.php index b6b2b8d32..89b68663b 100644 --- a/app/Rules/ValidHostname.php +++ b/app/Rules/ValidHostname.php @@ -62,12 +62,15 @@ public function validate(string $attribute, mixed $value, Closure $fail): void // Ignore errors when facades are not available (e.g., in unit tests) } - $fail('The :attribute contains invalid characters. Only lowercase letters (a-z), numbers (0-9), hyphens (-), and dots (.) are allowed.'); + $fail('The :attribute contains invalid characters. Only letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.) are allowed.'); return; } } + // Normalize to lowercase for validation (RFC 1123 hostnames are case-insensitive) + $hostname = strtolower($hostname); + // Additional validation: hostname should not start or end with a dot if (str_starts_with($hostname, '.') || str_ends_with($hostname, '.')) { $fail('The :attribute cannot start or end with a dot.'); @@ -100,9 +103,9 @@ public function validate(string $attribute, mixed $value, Closure $fail): void return; } - // Check if label contains only valid characters (lowercase letters, digits, hyphens) + // Check if label contains only valid characters (letters, digits, hyphens) if (! preg_match('/^[a-z0-9-]+$/', $label)) { - $fail('The :attribute contains invalid characters. Only lowercase letters (a-z), numbers (0-9), hyphens (-), and dots (.) are allowed.'); + $fail('The :attribute contains invalid characters. Only letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.) are allowed.'); return; } diff --git a/app/Support/ValidationPatterns.php b/app/Support/ValidationPatterns.php index fdf2b12a6..7084b4cc2 100644 --- a/app/Support/ValidationPatterns.php +++ b/app/Support/ValidationPatterns.php @@ -10,7 +10,7 @@ class ValidationPatterns /** * Pattern for names excluding all dangerous characters */ - public const NAME_PATTERN = '/^[\p{L}\p{M}\p{N}\s\-_.@\/&]+$/u'; + public const NAME_PATTERN = '/^[\p{L}\p{M}\p{N}\s\-_.@\/&()#,:+]+$/u'; /** * Pattern for descriptions excluding all dangerous characters with some additional allowed characters @@ -37,11 +37,20 @@ class ValidationPatterns /** * Pattern for shell-safe command strings (docker compose commands, docker run options) - * Blocks dangerous shell metacharacters: ; & | ` $ ( ) > < newlines and carriage returns - * Also blocks backslashes, single quotes, and double quotes to prevent escape-sequence attacks + * Blocks dangerous shell metacharacters: ; | ` $ ( ) > < newlines and carriage returns + * Allows & for command chaining (&&) which is common in multi-step build commands + * Allows double quotes for build args with spaces (e.g. --build-arg KEY="value") + * Blocks backslashes and single quotes to prevent escape-sequence attacks * Uses [ \t] instead of \s to explicitly exclude \n and \r (which act as command separators) */ - public const SHELL_SAFE_COMMAND_PATTERN = '/^[a-zA-Z0-9 \t._\-\/=:@,+\[\]{}#%^~]+$/'; + public const SHELL_SAFE_COMMAND_PATTERN = '/^[a-zA-Z0-9 \t._\-\/=:@,+\[\]{}#%^~&"]+$/'; + + /** + * Pattern for Docker volume names + * Must start with alphanumeric, followed by alphanumeric, dots, hyphens, or underscores + * Matches Docker's volume naming rules + */ + public const VOLUME_NAME_PATTERN = '/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/'; /** * Pattern for Docker container names @@ -96,7 +105,7 @@ public static function descriptionRules(bool $required = false, int $maxLength = public static function nameMessages(): array { return [ - 'name.regex' => 'The name may only contain letters (including Unicode), numbers, spaces, and these characters: - _ . / @ &', + 'name.regex' => 'The name may only contain letters (including Unicode), numbers, spaces, and these characters: - _ . / @ & ( ) # , : +', 'name.min' => 'The name must be at least :min characters.', 'name.max' => 'The name may not be greater than :max characters.', ]; @@ -155,6 +164,36 @@ public static function shellSafeCommandRules(int $maxLength = 1000): array return ['nullable', 'string', 'max:'.$maxLength, 'regex:'.self::SHELL_SAFE_COMMAND_PATTERN]; } + /** + * Get validation rules for Docker volume name fields + */ + public static function volumeNameRules(bool $required = true, int $maxLength = 255): array + { + $rules = []; + + if ($required) { + $rules[] = 'required'; + } else { + $rules[] = 'nullable'; + } + + $rules[] = 'string'; + $rules[] = "max:$maxLength"; + $rules[] = 'regex:'.self::VOLUME_NAME_PATTERN; + + return $rules; + } + + /** + * Get validation messages for volume name fields + */ + public static function volumeNameMessages(string $field = 'name'): array + { + return [ + "{$field}.regex" => 'The volume name must start with an alphanumeric character and contain only alphanumeric characters, dots, hyphens, and underscores.', + ]; + } + /** * Get validation rules for container name fields */ @@ -163,6 +202,14 @@ public static function containerNameRules(int $maxLength = 255): array return ['string', 'max:'.$maxLength, 'regex:'.self::CONTAINER_NAME_PATTERN]; } + /** + * Check if a string is a valid Docker container name. + */ + public static function isValidContainerName(string $name): bool + { + return preg_match(self::CONTAINER_NAME_PATTERN, $name) === 1; + } + /** * Get combined validation messages for both name and description fields */ diff --git a/app/Traits/ExecuteRemoteCommand.php b/app/Traits/ExecuteRemoteCommand.php index 72e0adde8..bb252148a 100644 --- a/app/Traits/ExecuteRemoteCommand.php +++ b/app/Traits/ExecuteRemoteCommand.php @@ -78,6 +78,7 @@ public function execute_remote_command(...$commands) $customType = data_get($single_command, 'type'); $ignore_errors = data_get($single_command, 'ignore_errors', false); $append = data_get($single_command, 'append', true); + $command_hidden = data_get($single_command, 'command_hidden', false); $this->save = data_get($single_command, 'save'); if ($this->server->isNonRoot()) { if (str($command)->startsWith('docker exec')) { @@ -102,7 +103,7 @@ public function execute_remote_command(...$commands) while ($attempt < $maxRetries && ! $commandExecuted) { try { - $this->executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors); + $this->executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors, $command_hidden); $commandExecuted = true; } catch (\RuntimeException|DeploymentException $e) { $lastError = $e; @@ -152,10 +153,14 @@ public function execute_remote_command(...$commands) /** * Execute the actual command with process handling */ - private function executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors) + private function executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors, $command_hidden = false) { + if ($command_hidden && isset($this->application_deployment_queue)) { + $this->application_deployment_queue->addLogEntry('[CMD]: '.$this->redact_sensitive_info($command), hidden: true); + } + $remote_command = SshMultiplexingHelper::generateSshCommand($this->server, $command); - $process = Process::timeout(config('constants.ssh.command_timeout'))->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append) { + $process = Process::timeout(config('constants.ssh.command_timeout'))->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append, $command_hidden) { $output = str($output)->trim(); if ($output->startsWith('╔')) { $output = "\n".$output; @@ -165,9 +170,9 @@ private function executeCommandWithProcess($command, $hidden, $customType, $appe $sanitized_output = sanitize_utf8_text($output); $new_log_entry = [ - 'command' => $this->redact_sensitive_info($command), + 'command' => $command_hidden ? null : $this->redact_sensitive_info($command), 'output' => $this->redact_sensitive_info($sanitized_output), - 'type' => $customType ?? $type === 'err' ? 'stderr' : 'stdout', + 'type' => $customType ?? ($type === 'err' ? 'stderr' : 'stdout'), 'timestamp' => Carbon::now('UTC'), 'hidden' => $hidden, 'batch' => static::$batch_counter, diff --git a/boost.json b/boost.json index 34b67ce76..13914521e 100644 --- a/boost.json +++ b/boost.json @@ -6,18 +6,23 @@ "opencode" ], "guidelines": true, - "herd_mcp": false, "mcp": true, + "nightwatch_mcp": false, "packages": [ "laravel/fortify", - "spatie/laravel-ray" + "spatie/laravel-ray", + "lorisleiva/laravel-actions" ], "sail": false, "skills": [ + "laravel-best-practices", + "configuring-horizon", + "socialite-development", "livewire-development", "pest-testing", "tailwindcss-development", - "developing-with-fortify", + "fortify-development", + "laravel-actions", "debugging-output-and-previewing-html-using-ray" ] } diff --git a/bootstrap/helpers/docker.php b/bootstrap/helpers/docker.php index 7b74392cf..5905ed3c1 100644 --- a/bootstrap/helpers/docker.php +++ b/bootstrap/helpers/docker.php @@ -137,6 +137,11 @@ function checkMinimumDockerEngineVersion($dockerVersion) return $dockerVersion; } +function escapeShellValue(string $value): string +{ + return "'".str_replace("'", "'\\''", $value)."'"; +} + function executeInDocker(string $containerId, string $command) { $escapedCommand = str_replace("'", "'\\''", $command); diff --git a/bootstrap/helpers/parsers.php b/bootstrap/helpers/parsers.php index cd4928d63..4ca693fcb 100644 --- a/bootstrap/helpers/parsers.php +++ b/bootstrap/helpers/parsers.php @@ -990,16 +990,17 @@ function applicationParser(Application $resource, int $pull_request_id = 0, ?int } if ($key->value() === $parsedValue->value()) { // Simple variable reference (e.g. DATABASE_URL: ${DATABASE_URL}) - // Use firstOrCreate to avoid overwriting user-saved values on redeploy - $envVar = $resource->environment_variables()->firstOrCreate([ + // Ensure the variable exists in DB for .env generation and UI display + $resource->environment_variables()->firstOrCreate([ 'key' => $key, 'resourceable_type' => get_class($resource), 'resourceable_id' => $resource->id, ], [ 'is_preview' => false, ]); - // Add the variable to the environment using the saved DB value - $environment[$key->value()] = $envVar->value; + // Keep the ${VAR} reference in compose — Docker Compose resolves from .env at deploy time. + // Do NOT replace with DB value: if user updates env var without re-parsing compose, + // a stale resolved value in environment: would override the correct .env value. } else { if ($value->startsWith('$')) { $isRequired = false; @@ -2341,8 +2342,8 @@ function serviceParser(Service $resource): Collection } if ($key->value() === $parsedValue->value()) { // Simple variable reference (e.g. DATABASE_URL: ${DATABASE_URL}) - // Use firstOrCreate to avoid overwriting user-saved values on redeploy - $envVar = $resource->environment_variables()->firstOrCreate([ + // Ensure the variable exists in DB for .env generation and UI display + $resource->environment_variables()->firstOrCreate([ 'key' => $key, 'resourceable_type' => get_class($resource), 'resourceable_id' => $resource->id, @@ -2350,8 +2351,9 @@ function serviceParser(Service $resource): Collection 'is_preview' => false, 'comment' => $envComments[$originalKey] ?? null, ]); - // Add the variable to the environment using the saved DB value - $environment[$key->value()] = $envVar->value; + // Keep the ${VAR} reference in compose — Docker Compose resolves from .env at deploy time. + // Do NOT replace with DB value: if user updates env var without re-parsing compose, + // a stale resolved value in environment: would override the correct .env value. } else { if ($value->startsWith('$')) { $isRequired = false; diff --git a/bootstrap/helpers/remoteProcess.php b/bootstrap/helpers/remoteProcess.php index f819df380..2544719fc 100644 --- a/bootstrap/helpers/remoteProcess.php +++ b/bootstrap/helpers/remoteProcess.php @@ -1,9 +1,10 @@ teams->pluck('id'); if (! $teams->contains($server->team_id) && ! $teams->contains(0)) { - throw new \Exception('User is not part of the team that owns this server'); + throw new Exception('User is not part of the team that owns this server'); } } SshMultiplexingHelper::ensureMultiplexedConnection($server); - return resolve(PrepareCoolifyTask::class, [ - 'remoteProcessArgs' => new CoolifyTaskArgs( - server_uuid: $server->uuid, - command: $command_string, - type: $type, - type_uuid: $type_uuid, - model: $model, - ignore_errors: $ignore_errors, - call_event_on_finish: $callEventOnFinish, - call_event_data: $callEventData, - ), - ])(); + $properties = [ + 'server_uuid' => $server->uuid, + 'command' => $command_string, + 'type' => $type, + 'type_uuid' => $type_uuid, + 'status' => ProcessStatus::QUEUED->value, + 'team_id' => $server->team_id, + ]; + + $activityLog = activity() + ->withProperties($properties) + ->event($type); + + if ($model) { + $activityLog->performedOn($model); + } + + $activity = $activityLog->log('[]'); + + dispatch(new CoolifyTask( + activity: $activity, + ignore_errors: $ignore_errors, + call_event_on_finish: $callEventOnFinish, + call_event_data: $callEventData, + )); + + $activity->refresh(); + + return $activity; } function instant_scp(string $source, string $dest, Server $server, $throwError = true) { - return \App\Helpers\SshRetryHandler::retry( + return SshRetryHandler::retry( function () use ($source, $dest, $server) { $scp_command = SshMultiplexingHelper::generateScpCommand($server, $source, $dest); $process = Process::timeout(config('constants.ssh.command_timeout'))->run($scp_command); @@ -92,7 +110,7 @@ function instant_remote_process_with_timeout(Collection|array $command, Server $ } $command_string = implode("\n", $command); - return \App\Helpers\SshRetryHandler::retry( + return SshRetryHandler::retry( function () use ($server, $command_string) { $sshCommand = SshMultiplexingHelper::generateSshCommand($server, $command_string); $process = Process::timeout(30)->run($sshCommand); @@ -128,7 +146,7 @@ function instant_remote_process(Collection|array $command, Server $server, bool $command_string = implode("\n", $command); $effectiveTimeout = $timeout ?? config('constants.ssh.command_timeout'); - return \App\Helpers\SshRetryHandler::retry( + return SshRetryHandler::retry( function () use ($server, $command_string, $effectiveTimeout, $disableMultiplexing) { $sshCommand = SshMultiplexingHelper::generateSshCommand($server, $command_string, $disableMultiplexing); $process = Process::timeout($effectiveTimeout)->run($sshCommand); @@ -170,9 +188,9 @@ function excludeCertainErrors(string $errorOutput, ?int $exitCode = null) if ($ignored) { // TODO: Create new exception and disable in sentry - throw new \RuntimeException($errorMessage, $exitCode); + throw new RuntimeException($errorMessage, $exitCode); } - throw new \RuntimeException($errorMessage, $exitCode); + throw new RuntimeException($errorMessage, $exitCode); } function decode_remote_command_output(?ApplicationDeploymentQueue $application_deployment_queue = null, bool $includeAll = false): Collection @@ -194,7 +212,7 @@ function decode_remote_command_output(?ApplicationDeploymentQueue $application_d associative: true, flags: JSON_THROW_ON_ERROR ); - } catch (\JsonException $e) { + } catch (JsonException $e) { // If JSON decoding fails, try to clean up the logs and retry try { // Ensure valid UTF-8 encoding @@ -204,7 +222,7 @@ function decode_remote_command_output(?ApplicationDeploymentQueue $application_d associative: true, flags: JSON_THROW_ON_ERROR ); - } catch (\JsonException $e) { + } catch (JsonException $e) { // If it still fails, return empty collection to prevent crashes return collect([]); } @@ -353,7 +371,7 @@ function checkRequiredCommands(Server $server) } try { instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'apt update && apt install -y {$command}'"], $server); - } catch (\Throwable) { + } catch (Throwable) { break; } $commandFound = instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'command -v {$command}'"], $server, false); diff --git a/bootstrap/helpers/shared.php b/bootstrap/helpers/shared.php index e81d2a467..cd773f6a9 100644 --- a/bootstrap/helpers/shared.php +++ b/bootstrap/helpers/shared.php @@ -16,6 +16,7 @@ use App\Models\Service; use App\Models\ServiceApplication; use App\Models\ServiceDatabase; +use App\Models\SharedEnvironmentVariable; use App\Models\StandaloneClickhouse; use App\Models\StandaloneDragonfly; use App\Models\StandaloneKeydb; @@ -28,8 +29,10 @@ use App\Models\User; use Carbon\CarbonImmutable; use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\UniqueConstraintViolationException; use Illuminate\Process\Pool; +use Illuminate\Support\Carbon; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; @@ -49,10 +52,14 @@ use Lcobucci\JWT\Signer\Hmac\Sha256; use Lcobucci\JWT\Signer\Key\InMemory; use Lcobucci\JWT\Token\Builder; +use Livewire\Component; +use Nubs\RandomNameGenerator\All; +use Nubs\RandomNameGenerator\Alliteration; use phpseclib3\Crypt\EC; use phpseclib3\Crypt\RSA; use Poliander\Cron\CronExpression; use PurplePixie\PhpDns\DNSQuery; +use PurplePixie\PhpDns\DNSTypes; use Spatie\Url\Url; use Symfony\Component\Yaml\Yaml; use Visus\Cuid2\Cuid2; @@ -116,7 +123,7 @@ function sanitize_string(?string $input = null): ?string * @param string $context Descriptive name for error messages (e.g., 'volume source', 'service name') * @return string The validated input (unchanged if valid) * - * @throws \Exception If dangerous characters are detected + * @throws Exception If dangerous characters are detected */ function validateShellSafePath(string $input, string $context = 'path'): string { @@ -138,7 +145,7 @@ function validateShellSafePath(string $input, string $context = 'path'): string // Check for dangerous characters foreach ($dangerousChars as $char => $description) { if (str_contains($input, $char)) { - throw new \Exception( + throw new Exception( "Invalid {$context}: contains forbidden character '{$char}' ({$description}). ". 'Shell metacharacters are not allowed for security reasons.' ); @@ -148,6 +155,59 @@ function validateShellSafePath(string $input, string $context = 'path'): string return $input; } +/** + * Validate that a databases_to_backup input string is safe from command injection. + * + * Supports all database formats: + * - PostgreSQL/MySQL/MariaDB: "db1,db2,db3" + * - MongoDB: "db1:col1,col2|db2:col3,col4" + * + * Validates each database name AND collection name individually against shell metacharacters. + * + * @param string $input The databases_to_backup string + * @return string The validated input + * + * @throws Exception If any component contains dangerous characters + */ +function validateDatabasesBackupInput(string $input): string +{ + // Split by pipe (MongoDB multi-db separator) + $databaseEntries = explode('|', $input); + + foreach ($databaseEntries as $entry) { + $entry = trim($entry); + if ($entry === '' || $entry === 'all' || $entry === '*') { + continue; + } + + if (str_contains($entry, ':')) { + // MongoDB format: dbname:collection1,collection2 + $databaseName = str($entry)->before(':')->value(); + $collections = str($entry)->after(':')->explode(','); + + validateShellSafePath($databaseName, 'database name'); + + foreach ($collections as $collection) { + $collection = trim($collection); + if ($collection !== '') { + validateShellSafePath($collection, 'collection name'); + } + } + } else { + // Simple format: just a database name (may contain commas for non-Mongo) + $databases = explode(',', $entry); + foreach ($databases as $db) { + $db = trim($db); + if ($db !== '' && $db !== 'all' && $db !== '*') { + validateShellSafePath($db, 'database name'); + } + } + } + } + + return $input; +} + /** * Validate that a string is a safe git ref (commit SHA, branch name, tag, or HEAD). * @@ -158,7 +218,7 @@ function validateShellSafePath(string $input, string $context = 'path'): string * @param string $context Descriptive name for error messages * @return string The validated input (trimmed) * - * @throws \Exception If the input contains disallowed characters + * @throws Exception If the input contains disallowed characters */ function validateGitRef(string $input, string $context = 'git ref'): string { @@ -170,12 +230,12 @@ function validateGitRef(string $input, string $context = 'git ref'): string // Must not start with a hyphen (git flag injection) if (str_starts_with($input, '-')) { - throw new \Exception("Invalid {$context}: must not start with a hyphen."); + throw new Exception("Invalid {$context}: must not start with a hyphen."); } // Allow only alphanumeric characters, dots, hyphens, underscores, and slashes if (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9._\-\/]*$/', $input)) { - throw new \Exception("Invalid {$context}: contains disallowed characters. Only alphanumeric characters, dots, hyphens, underscores, and slashes are allowed."); + throw new Exception("Invalid {$context}: contains disallowed characters. Only alphanumeric characters, dots, hyphens, underscores, and slashes are allowed."); } return $input; @@ -229,7 +289,7 @@ function refreshSession(?Team $team = null): void }); session(['currentTeam' => $team]); } -function handleError(?Throwable $error = null, ?Livewire\Component $livewire = null, ?string $customErrorMessage = null) +function handleError(?Throwable $error = null, ?Component $livewire = null, ?string $customErrorMessage = null) { if ($error instanceof TooManyRequestsException) { if (isset($livewire)) { @@ -246,7 +306,7 @@ function handleError(?Throwable $error = null, ?Livewire\Component $livewire = n return 'Duplicate entry found. Please use a different name.'; } - if ($error instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { + if ($error instanceof ModelNotFoundException) { abort(404); } @@ -276,7 +336,7 @@ function get_latest_sentinel_version(): string $versions = $response->json(); return data_get($versions, 'coolify.sentinel.version'); - } catch (\Throwable) { + } catch (Throwable) { return '0.0.0'; } } @@ -286,7 +346,7 @@ function get_latest_version_of_coolify(): string $versions = get_versions_data(); return data_get($versions, 'coolify.v4.version', '0.0.0'); - } catch (\Throwable $e) { + } catch (Throwable $e) { return '0.0.0'; } @@ -294,9 +354,9 @@ function get_latest_version_of_coolify(): string function generate_random_name(?string $cuid = null): string { - $generator = new \Nubs\RandomNameGenerator\All( + $generator = new All( [ - new \Nubs\RandomNameGenerator\Alliteration, + new Alliteration, ] ); if (is_null($cuid)) { @@ -339,7 +399,18 @@ function generate_application_name(string $git_repository, string $git_branch, ? $cuid = new Cuid2; } - return Str::kebab("$git_repository:$git_branch-$cuid"); + $repo_name = str_contains($git_repository, '/') ? last(explode('/', $git_repository)) : $git_repository; + + $name = Str::kebab("$repo_name:$git_branch-$cuid"); + + // Strip characters not allowed by NAME_PATTERN + $name = preg_replace('/[^\p{L}\p{M}\p{N}\s\-_.@\/&()#,:+]+/u', '', $name); + + if (empty($name) || mb_strlen($name) < 3) { + return generate_random_name($cuid); + } + + return $name; } /** @@ -384,7 +455,7 @@ function getFqdnWithoutPort(string $fqdn) $path = $url->getPath(); return "$scheme://$host$path"; - } catch (\Throwable) { + } catch (Throwable) { return $fqdn; } } @@ -414,13 +485,13 @@ function base_url(bool $withPort = true): string } if ($settings->public_ipv6) { if ($withPort) { - return "http://$settings->public_ipv6:$port"; + return "http://[$settings->public_ipv6]:$port"; } - return "http://$settings->public_ipv6"; + return "http://[$settings->public_ipv6]"; } - return url('/'); + return config('app.url'); } function isSubscribed() @@ -466,6 +537,36 @@ function validate_cron_expression($expression_to_validate): bool return $isValid; } +/** + * Determine if a cron schedule should run now, with deduplication. + * + * Uses getPreviousRunDate() + last-dispatch tracking to be resilient to queue delays. + * Even if the job runs minutes late, it still catches the missed cron window. + * Without a dedupKey, falls back to a simple isDue() check. + */ +function shouldRunCronNow(string $frequency, string $timezone, ?string $dedupKey = null, ?Carbon $executionTime = null): bool +{ + $cron = new Cron\CronExpression($frequency); + $executionTime = ($executionTime ?? Carbon::now())->copy()->setTimezone($timezone); + + if ($dedupKey === null) { + return $cron->isDue($executionTime); + } + + $previousDue = Carbon::instance($cron->getPreviousRunDate($executionTime, allowCurrentDate: true)); + $lastDispatched = Cache::get($dedupKey); + + $shouldFire = $lastDispatched === null + ? $cron->isDue($executionTime) + : $previousDue->gt(Carbon::parse($lastDispatched)); + + // Always write: seeds on first miss, refreshes on dispatch. + // 30-day static TTL covers all intervals; orphan keys self-clean. + Cache::put($dedupKey, ($shouldFire ? $executionTime : $previousDue)->toIso8601String(), 2592000); + + return $shouldFire; +} + function validate_timezone(string $timezone): bool { return in_array($timezone, timezone_identifiers_list()); @@ -838,7 +939,7 @@ function get_service_templates(bool $force = false): Collection $services = $response->json(); return collect($services); - } catch (\Throwable) { + } catch (Throwable) { $services = File::get(base_path('templates/'.config('constants.services.file_name'))); return collect(json_decode($services))->sortKeys(); @@ -861,7 +962,7 @@ function getResourceByUuid(string $uuid, ?int $teamId = null) } // ServiceDatabase has a different relationship path: service->environment->project->team_id - if ($resource instanceof \App\Models\ServiceDatabase) { + if ($resource instanceof ServiceDatabase) { if ($resource->service?->environment?->project?->team_id === $teamId) { return $resource; } @@ -987,7 +1088,7 @@ function generateGitManualWebhook($resource, $type) if ($resource->source_id !== 0 && ! is_null($resource->source_id)) { return null; } - if ($resource->getMorphClass() === \App\Models\Application::class) { + if ($resource->getMorphClass() === Application::class) { $baseUrl = base_url(); return Url::fromString($baseUrl)."/webhooks/source/$type/events/manual"; @@ -1008,11 +1109,11 @@ function sanitizeLogsForExport(string $text): string function getTopLevelNetworks(Service|Application $resource) { - if ($resource->getMorphClass() === \App\Models\Service::class) { + if ($resource->getMorphClass() === Service::class) { if ($resource->docker_compose_raw) { try { $yaml = Yaml::parse($resource->docker_compose_raw); - } catch (\Exception $e) { + } catch (Exception $e) { // If the docker-compose.yml file is not valid, we will return the network name as the key $topLevelNetworks = collect([ $resource->uuid => [ @@ -1075,10 +1176,10 @@ function getTopLevelNetworks(Service|Application $resource) return $topLevelNetworks->keys(); } - } elseif ($resource->getMorphClass() === \App\Models\Application::class) { + } elseif ($resource->getMorphClass() === Application::class) { try { $yaml = Yaml::parse($resource->docker_compose_raw); - } catch (\Exception $e) { + } catch (Exception $e) { // If the docker-compose.yml file is not valid, we will return the network name as the key $topLevelNetworks = collect([ $resource->uuid => [ @@ -1385,7 +1486,7 @@ function validateDNSEntry(string $fqdn, Server $server) $ip = $server->ip; } $found_matching_ip = false; - $type = \PurplePixie\PhpDns\DNSTypes::NAME_A; + $type = DNSTypes::NAME_A; foreach ($dns_servers as $dns_server) { try { $query = new DNSQuery($dns_server); @@ -1406,7 +1507,7 @@ function validateDNSEntry(string $fqdn, Server $server) } } } - } catch (\Exception) { + } catch (Exception) { } } @@ -1588,7 +1689,7 @@ function get_public_ips() } InstanceSettings::get()->update(['public_ipv4' => $ipv4]); } - } catch (\Exception $e) { + } catch (Exception $e) { echo "Error: {$e->getMessage()}\n"; } try { @@ -1603,7 +1704,7 @@ function get_public_ips() } InstanceSettings::get()->update(['public_ipv6' => $ipv6]); } - } catch (\Throwable $e) { + } catch (Throwable $e) { echo "Error: {$e->getMessage()}\n"; } } @@ -1701,15 +1802,15 @@ function customApiValidator(Collection|array $item, array $rules) } function parseDockerComposeFile(Service|Application $resource, bool $isNew = false, int $pull_request_id = 0, ?int $preview_id = null) { - if ($resource->getMorphClass() === \App\Models\Service::class) { + if ($resource->getMorphClass() === Service::class) { if ($resource->docker_compose_raw) { // Extract inline comments from raw YAML before Symfony parser discards them $envComments = extractYamlEnvironmentComments($resource->docker_compose_raw); try { $yaml = Yaml::parse($resource->docker_compose_raw); - } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + } catch (Exception $e) { + throw new RuntimeException($e->getMessage()); } $allServices = get_service_templates(); $topLevelVolumes = collect(data_get($yaml, 'volumes', [])); @@ -2473,10 +2574,10 @@ function parseDockerComposeFile(Service|Application $resource, bool $isNew = fal } else { return collect([]); } - } elseif ($resource->getMorphClass() === \App\Models\Application::class) { + } elseif ($resource->getMorphClass() === Application::class) { try { $yaml = Yaml::parse($resource->docker_compose_raw); - } catch (\Exception) { + } catch (Exception) { return; } $server = $resource->destination->server; @@ -3238,7 +3339,7 @@ function isAssociativeArray($array) } if (! is_array($array)) { - throw new \InvalidArgumentException('Input must be an array or a Collection.'); + throw new InvalidArgumentException('Input must be an array or a Collection.'); } if ($array === []) { @@ -3354,7 +3455,7 @@ function wireNavigate(): string // Return wire:navigate.hover for SPA navigation with prefetching, or empty string if disabled return ($settings->is_wire_navigate_enabled ?? true) ? 'wire:navigate.hover' : ''; - } catch (\Exception $e) { + } catch (Exception $e) { return 'wire:navigate.hover'; } } @@ -3363,13 +3464,13 @@ function wireNavigate(): string * Redirect to a named route with SPA navigation support. * Automatically uses wire:navigate when is_wire_navigate_enabled is true. */ -function redirectRoute(Livewire\Component $component, string $name, array $parameters = []): mixed +function redirectRoute(Component $component, string $name, array $parameters = []): mixed { $navigate = true; try { $navigate = instanceSettings()->is_wire_navigate_enabled ?? true; - } catch (\Exception $e) { + } catch (Exception $e) { $navigate = true; } @@ -3411,7 +3512,7 @@ function loadConfigFromGit(string $repository, string $branch, string $base_dire ]); try { return instant_remote_process($commands, $server); - } catch (\Exception) { + } catch (Exception) { // continue } } @@ -3542,8 +3643,8 @@ function convertGitUrl(string $gitRepository, string $deploymentType, GithubApp| // If this happens, the user may have provided an HTTP URL when they needed an SSH one // Let's try and fix that for known Git providers switch ($source->getMorphClass()) { - case \App\Models\GithubApp::class: - case \App\Models\GitlabApp::class: + case GithubApp::class: + case GitlabApp::class: $providerInfo['host'] = Url::fromString($source->html_url)->getHost(); $providerInfo['port'] = $source->custom_port; $providerInfo['user'] = $source->custom_user; @@ -3821,10 +3922,10 @@ function shouldSkipPasswordConfirmation(): bool * - User has no password (OAuth users) * * @param mixed $password The password to verify (may be array if skipped by frontend) - * @param \Livewire\Component|null $component Optional Livewire component to add errors to + * @param Component|null $component Optional Livewire component to add errors to * @return bool True if verification passed (or skipped), false if password is incorrect */ -function verifyPasswordConfirmation(mixed $password, ?Livewire\Component $component = null): bool +function verifyPasswordConfirmation(mixed $password, ?Component $component = null): bool { // Skip if password confirmation should be skipped if (shouldSkipPasswordConfirmation()) { @@ -3847,17 +3948,17 @@ function verifyPasswordConfirmation(mixed $password, ?Livewire\Component $compon * Extract hard-coded environment variables from docker-compose YAML. * * @param string $dockerComposeRaw Raw YAML content - * @return \Illuminate\Support\Collection Collection of arrays with: key, value, comment, service_name + * @return Collection Collection of arrays with: key, value, comment, service_name */ -function extractHardcodedEnvironmentVariables(string $dockerComposeRaw): \Illuminate\Support\Collection +function extractHardcodedEnvironmentVariables(string $dockerComposeRaw): Collection { if (blank($dockerComposeRaw)) { return collect([]); } try { - $yaml = \Symfony\Component\Yaml\Yaml::parse($dockerComposeRaw); - } catch (\Exception $e) { + $yaml = Yaml::parse($dockerComposeRaw); + } catch (Exception $e) { // Malformed YAML - return empty collection return collect([]); } @@ -4006,7 +4107,7 @@ function resolveSharedEnvironmentVariables(?string $value, $resource): ?string if (is_null($id)) { continue; } - $found = \App\Models\SharedEnvironmentVariable::where('type', $type) + $found = SharedEnvironmentVariable::where('type', $type) ->where('key', $variable) ->where('team_id', $resource->team()->id) ->where("{$type}_id", $id) diff --git a/composer.json b/composer.json index d4fb1eb8e..e2b16b31b 100644 --- a/composer.json +++ b/composer.json @@ -18,6 +18,7 @@ "laravel/fortify": "^1.34.0", "laravel/framework": "^12.49.0", "laravel/horizon": "^5.43.0", + "laravel/nightwatch": "^1.24", "laravel/pail": "^1.2.4", "laravel/prompts": "^0.3.11|^0.3.11|^0.3.11", "laravel/sanctum": "^4.3.0", diff --git a/composer.lock b/composer.lock index 993835a42..91900aa95 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "19bb661d294e5cf623e68830604e4f60", + "content-hash": "40bddea995c1744e4aec517263109a2f", "packages": [ { "name": "aws/aws-crt-php", @@ -62,16 +62,16 @@ }, { "name": "aws/aws-sdk-php", - "version": "3.371.3", + "version": "3.373.9", "source": { "type": "git", "url": "https://github.com/aws/aws-sdk-php.git", - "reference": "d300ec1c861e52dc8f17ca3d75dc754da949f065" + "reference": "a73e12fe5d010f3c6cda2f6f020b5a475444487d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/d300ec1c861e52dc8f17ca3d75dc754da949f065", - "reference": "d300ec1c861e52dc8f17ca3d75dc754da949f065", + "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/a73e12fe5d010f3c6cda2f6f020b5a475444487d", + "reference": "a73e12fe5d010f3c6cda2f6f020b5a475444487d", "shasum": "" }, "require": { @@ -92,12 +92,12 @@ "aws/aws-php-sns-message-validator": "~1.0", "behat/behat": "~3.0", "composer/composer": "^2.7.8", - "dms/phpunit-arraysubset-asserts": "^0.4.0", + "dms/phpunit-arraysubset-asserts": "^v0.5.0", "doctrine/cache": "~1.4", "ext-dom": "*", "ext-openssl": "*", "ext-sockets": "*", - "phpunit/phpunit": "^9.6", + "phpunit/phpunit": "^10.0", "psr/cache": "^2.0 || ^3.0", "psr/simple-cache": "^2.0 || ^3.0", "sebastian/comparator": "^1.2.3 || ^4.0 || ^5.0", @@ -153,22 +153,22 @@ "support": { "forum": "https://github.com/aws/aws-sdk-php/discussions", "issues": "https://github.com/aws/aws-sdk-php/issues", - "source": "https://github.com/aws/aws-sdk-php/tree/3.371.3" + "source": "https://github.com/aws/aws-sdk-php/tree/3.373.9" }, - "time": "2026-02-27T19:05:40+00:00" + "time": "2026-03-24T18:06:07+00:00" }, { "name": "bacon/bacon-qr-code", - "version": "v3.0.3", + "version": "v3.0.4", "source": { "type": "git", "url": "https://github.com/Bacon/BaconQrCode.git", - "reference": "36a1cb2b81493fa5b82e50bf8068bf84d1542563" + "reference": "3feed0e212b8412cc5d2612706744789b0615824" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/36a1cb2b81493fa5b82e50bf8068bf84d1542563", - "reference": "36a1cb2b81493fa5b82e50bf8068bf84d1542563", + "url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/3feed0e212b8412cc5d2612706744789b0615824", + "reference": "3feed0e212b8412cc5d2612706744789b0615824", "shasum": "" }, "require": { @@ -208,9 +208,9 @@ "homepage": "https://github.com/Bacon/BaconQrCode", "support": { "issues": "https://github.com/Bacon/BaconQrCode/issues", - "source": "https://github.com/Bacon/BaconQrCode/tree/v3.0.3" + "source": "https://github.com/Bacon/BaconQrCode/tree/v3.0.4" }, - "time": "2025-11-19T17:15:36+00:00" + "time": "2026-03-16T01:01:30+00:00" }, { "name": "brick/math", @@ -343,27 +343,27 @@ }, { "name": "danharrin/livewire-rate-limiting", - "version": "v2.1.0", + "version": "v2.2.0", "source": { "type": "git", "url": "https://github.com/danharrin/livewire-rate-limiting.git", - "reference": "14dde653a9ae8f38af07a0ba4921dc046235e1a0" + "reference": "c03e649220089f6e5a52d422e24e3f98c73e456d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/danharrin/livewire-rate-limiting/zipball/14dde653a9ae8f38af07a0ba4921dc046235e1a0", - "reference": "14dde653a9ae8f38af07a0ba4921dc046235e1a0", + "url": "https://api.github.com/repos/danharrin/livewire-rate-limiting/zipball/c03e649220089f6e5a52d422e24e3f98c73e456d", + "reference": "c03e649220089f6e5a52d422e24e3f98c73e456d", "shasum": "" }, "require": { - "illuminate/support": "^9.0|^10.0|^11.0|^12.0", + "illuminate/support": "^9.0|^10.0|^11.0|^12.0|^13.0", "php": "^8.0" }, "require-dev": { "livewire/livewire": "^3.0", "livewire/volt": "^1.3", - "orchestra/testbench": "^7.0|^8.0|^9.0|^10.0", - "phpunit/phpunit": "^9.0|^10.0|^11.5.3" + "orchestra/testbench": "^7.0|^8.0|^9.0|^10.0|^11.0", + "phpunit/phpunit": "^9.0|^10.0|^11.5.3|^12.5.12" }, "type": "library", "autoload": { @@ -393,7 +393,7 @@ "type": "github" } ], - "time": "2025-02-21T08:52:11+00:00" + "time": "2026-03-16T11:29:23+00:00" }, { "name": "dasprid/enum", @@ -522,16 +522,16 @@ }, { "name": "doctrine/dbal", - "version": "4.4.2", + "version": "4.4.3", "source": { "type": "git", "url": "https://github.com/doctrine/dbal.git", - "reference": "476f7f0fa6ea4aa5364926db7fabdf6049075722" + "reference": "61e730f1658814821a85f2402c945f3883407dec" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/dbal/zipball/476f7f0fa6ea4aa5364926db7fabdf6049075722", - "reference": "476f7f0fa6ea4aa5364926db7fabdf6049075722", + "url": "https://api.github.com/repos/doctrine/dbal/zipball/61e730f1658814821a85f2402c945f3883407dec", + "reference": "61e730f1658814821a85f2402c945f3883407dec", "shasum": "" }, "require": { @@ -608,7 +608,7 @@ ], "support": { "issues": "https://github.com/doctrine/dbal/issues", - "source": "https://github.com/doctrine/dbal/tree/4.4.2" + "source": "https://github.com/doctrine/dbal/tree/4.4.3" }, "funding": [ { @@ -624,7 +624,7 @@ "type": "tidelift" } ], - "time": "2026-02-26T12:12:19+00:00" + "time": "2026-03-20T08:52:12+00:00" }, { "name": "doctrine/deprecations", @@ -1440,16 +1440,16 @@ }, { "name": "guzzlehttp/psr7", - "version": "2.8.0", + "version": "2.9.0", "source": { "type": "git", "url": "https://github.com/guzzle/psr7.git", - "reference": "21dc724a0583619cd1652f673303492272778051" + "reference": "7d0ed42f28e42d61352a7a79de682e5e67fec884" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/21dc724a0583619cd1652f673303492272778051", - "reference": "21dc724a0583619cd1652f673303492272778051", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/7d0ed42f28e42d61352a7a79de682e5e67fec884", + "reference": "7d0ed42f28e42d61352a7a79de682e5e67fec884", "shasum": "" }, "require": { @@ -1465,6 +1465,7 @@ "require-dev": { "bamarni/composer-bin-plugin": "^1.8.2", "http-interop/http-factory-tests": "0.9.0", + "jshttp/mime-db": "1.54.0.1", "phpunit/phpunit": "^8.5.44 || ^9.6.25" }, "suggest": { @@ -1536,7 +1537,7 @@ ], "support": { "issues": "https://github.com/guzzle/psr7/issues", - "source": "https://github.com/guzzle/psr7/tree/2.8.0" + "source": "https://github.com/guzzle/psr7/tree/2.9.0" }, "funding": [ { @@ -1552,7 +1553,7 @@ "type": "tidelift" } ], - "time": "2025-08-23T21:21:41+00:00" + "time": "2026-03-10T16:41:02+00:00" }, { "name": "guzzlehttp/uri-template", @@ -1702,16 +1703,16 @@ }, { "name": "laravel/fortify", - "version": "v1.35.0", + "version": "v1.36.2", "source": { "type": "git", "url": "https://github.com/laravel/fortify.git", - "reference": "24c5bb81ea4787e0865c4a62f054ed7d1cb7a093" + "reference": "b36e0782e6f5f6cfbab34327895a63b7c4c031f9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/fortify/zipball/24c5bb81ea4787e0865c4a62f054ed7d1cb7a093", - "reference": "24c5bb81ea4787e0865c4a62f054ed7d1cb7a093", + "url": "https://api.github.com/repos/laravel/fortify/zipball/b36e0782e6f5f6cfbab34327895a63b7c4c031f9", + "reference": "b36e0782e6f5f6cfbab34327895a63b7c4c031f9", "shasum": "" }, "require": { @@ -1761,20 +1762,20 @@ "issues": "https://github.com/laravel/fortify/issues", "source": "https://github.com/laravel/fortify" }, - "time": "2026-02-24T14:00:44+00:00" + "time": "2026-03-20T20:13:51+00:00" }, { "name": "laravel/framework", - "version": "v12.53.0", + "version": "v12.55.1", "source": { "type": "git", "url": "https://github.com/laravel/framework.git", - "reference": "f57f035c0d34503d9ff30be76159bb35a003cd1f" + "reference": "6d9185a248d101b07eecaf8fd60b18129545fd33" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/framework/zipball/f57f035c0d34503d9ff30be76159bb35a003cd1f", - "reference": "f57f035c0d34503d9ff30be76159bb35a003cd1f", + "url": "https://api.github.com/repos/laravel/framework/zipball/6d9185a248d101b07eecaf8fd60b18129545fd33", + "reference": "6d9185a248d101b07eecaf8fd60b18129545fd33", "shasum": "" }, "require": { @@ -1795,7 +1796,7 @@ "guzzlehttp/uri-template": "^1.0", "laravel/prompts": "^0.3.0", "laravel/serializable-closure": "^1.3|^2.0", - "league/commonmark": "^2.7", + "league/commonmark": "^2.8.1", "league/flysystem": "^3.25.1", "league/flysystem-local": "^3.25.1", "league/uri": "^7.5.1", @@ -1890,7 +1891,7 @@ "orchestra/testbench-core": "^10.9.0", "pda/pheanstalk": "^5.0.6|^7.0.0", "php-http/discovery": "^1.15", - "phpstan/phpstan": "^2.0", + "phpstan/phpstan": "^2.1.41", "phpunit/phpunit": "^10.5.35|^11.5.3|^12.0.1", "predis/predis": "^2.3|^3.0", "resend/resend-php": "^0.10.0|^1.0", @@ -1983,20 +1984,20 @@ "issues": "https://github.com/laravel/framework/issues", "source": "https://github.com/laravel/framework" }, - "time": "2026-02-24T14:35:15+00:00" + "time": "2026-03-18T14:28:59+00:00" }, { "name": "laravel/horizon", - "version": "v5.45.0", + "version": "v5.45.4", "source": { "type": "git", "url": "https://github.com/laravel/horizon.git", - "reference": "7126ddf27fe9750c43ab0b567085dee3917d0510" + "reference": "b2b32e3f6013081e0176307e9081cd085f0ad4d6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/horizon/zipball/7126ddf27fe9750c43ab0b567085dee3917d0510", - "reference": "7126ddf27fe9750c43ab0b567085dee3917d0510", + "url": "https://api.github.com/repos/laravel/horizon/zipball/b2b32e3f6013081e0176307e9081cd085f0ad4d6", + "reference": "b2b32e3f6013081e0176307e9081cd085f0ad4d6", "shasum": "" }, "require": { @@ -2061,9 +2062,103 @@ ], "support": { "issues": "https://github.com/laravel/horizon/issues", - "source": "https://github.com/laravel/horizon/tree/v5.45.0" + "source": "https://github.com/laravel/horizon/tree/v5.45.4" }, - "time": "2026-02-21T14:20:09+00:00" + "time": "2026-03-18T14:14:59+00:00" + }, + { + "name": "laravel/nightwatch", + "version": "v1.24.4", + "source": { + "type": "git", + "url": "https://github.com/laravel/nightwatch.git", + "reference": "127e9bb9928f0fcf69b52b244053b393c90347c8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/nightwatch/zipball/127e9bb9928f0fcf69b52b244053b393c90347c8", + "reference": "127e9bb9928f0fcf69b52b244053b393c90347c8", + "shasum": "" + }, + "require": { + "ext-zlib": "*", + "guzzlehttp/promises": "^2.0", + "laravel/framework": "^10.0|^11.0|^12.0|^13.0", + "monolog/monolog": "^3.6", + "nesbot/carbon": "^2.0|^3.0", + "php": "^8.2", + "psr/http-message": "^1.0|^2.0", + "psr/log": "^1.0|^2.0|^3.0", + "ramsey/uuid": "^4.0", + "symfony/console": "^6.0|^7.0|^8.0", + "symfony/http-foundation": "^6.0|^7.0|^8.0", + "symfony/polyfill-php84": "^1.29" + }, + "require-dev": { + "aws/aws-sdk-php": "^3.349", + "ext-pcntl": "*", + "ext-pdo": "*", + "guzzlehttp/guzzle": "^7.0", + "guzzlehttp/psr7": "^2.0", + "laravel/horizon": "^5.4", + "laravel/pint": "1.21.0", + "laravel/vapor-core": "^2.38.2", + "livewire/livewire": "^2.0|^3.0", + "mockery/mockery": "^1.0", + "mongodb/laravel-mongodb": "^4.0|^5.0", + "orchestra/testbench": "^8.0|^9.0|^10.0", + "orchestra/testbench-core": "^8.0|^9.0|^10.0", + "orchestra/workbench": "^8.0|^9.0|^10.0", + "phpstan/phpstan": "^1.0", + "phpunit/phpunit": "^10.0|^11.0|^12.0", + "singlestoredb/singlestoredb-laravel": "^1.0|^2.0", + "spatie/laravel-ignition": "^2.0", + "symfony/mailer": "^6.0|^7.0|^8.0", + "symfony/mime": "^6.0|^7.0|^8.0", + "symfony/var-dumper": "^6.0|^7.0|^8.0" + }, + "type": "library", + "extra": { + "laravel": { + "aliases": { + "Nightwatch": "Laravel\\Nightwatch\\Facades\\Nightwatch" + }, + "providers": [ + "Laravel\\Nightwatch\\NightwatchServiceProvider" + ] + } + }, + "autoload": { + "files": [ + "agent/helpers.php" + ], + "psr-4": { + "Laravel\\Nightwatch\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The official Laravel Nightwatch package.", + "homepage": "https://nightwatch.laravel.com", + "keywords": [ + "Insights", + "laravel", + "monitoring" + ], + "support": { + "docs": "https://nightwatch.laravel.com/docs", + "issues": "https://github.com/laravel/nightwatch/issues", + "source": "https://github.com/laravel/nightwatch" + }, + "time": "2026-03-18T23:25:05+00:00" }, { "name": "laravel/pail", @@ -2147,16 +2242,16 @@ }, { "name": "laravel/prompts", - "version": "v0.3.13", + "version": "v0.3.16", "source": { "type": "git", "url": "https://github.com/laravel/prompts.git", - "reference": "ed8c466571b37e977532fb2fd3c272c784d7050d" + "reference": "11e7d5f93803a2190b00e145142cb00a33d17ad2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/prompts/zipball/ed8c466571b37e977532fb2fd3c272c784d7050d", - "reference": "ed8c466571b37e977532fb2fd3c272c784d7050d", + "url": "https://api.github.com/repos/laravel/prompts/zipball/11e7d5f93803a2190b00e145142cb00a33d17ad2", + "reference": "11e7d5f93803a2190b00e145142cb00a33d17ad2", "shasum": "" }, "require": { @@ -2200,9 +2295,9 @@ "description": "Add beautiful and user-friendly forms to your command-line applications.", "support": { "issues": "https://github.com/laravel/prompts/issues", - "source": "https://github.com/laravel/prompts/tree/v0.3.13" + "source": "https://github.com/laravel/prompts/tree/v0.3.16" }, - "time": "2026-02-06T12:17:10+00:00" + "time": "2026-03-23T14:35:33+00:00" }, { "name": "laravel/sanctum", @@ -2389,16 +2484,16 @@ }, { "name": "laravel/socialite", - "version": "v5.24.3", + "version": "v5.26.0", "source": { "type": "git", "url": "https://github.com/laravel/socialite.git", - "reference": "0feb62267e7b8abc68593ca37639ad302728c129" + "reference": "1d26f0c653a5f0e88859f4197830a29fe0cc59d0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/socialite/zipball/0feb62267e7b8abc68593ca37639ad302728c129", - "reference": "0feb62267e7b8abc68593ca37639ad302728c129", + "url": "https://api.github.com/repos/laravel/socialite/zipball/1d26f0c653a5f0e88859f4197830a29fe0cc59d0", + "reference": "1d26f0c653a5f0e88859f4197830a29fe0cc59d0", "shasum": "" }, "require": { @@ -2457,7 +2552,7 @@ "issues": "https://github.com/laravel/socialite/issues", "source": "https://github.com/laravel/socialite" }, - "time": "2026-02-21T13:32:50+00:00" + "time": "2026-03-24T18:37:47+00:00" }, { "name": "laravel/tinker", @@ -2527,29 +2622,29 @@ }, { "name": "laravel/ui", - "version": "v4.6.1", + "version": "v4.6.3", "source": { "type": "git", "url": "https://github.com/laravel/ui.git", - "reference": "7d6ffa38d79f19c9b3e70a751a9af845e8f41d88" + "reference": "ff27db15416c1ed8ad9848f5692e47595dd5de27" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/ui/zipball/7d6ffa38d79f19c9b3e70a751a9af845e8f41d88", - "reference": "7d6ffa38d79f19c9b3e70a751a9af845e8f41d88", + "url": "https://api.github.com/repos/laravel/ui/zipball/ff27db15416c1ed8ad9848f5692e47595dd5de27", + "reference": "ff27db15416c1ed8ad9848f5692e47595dd5de27", "shasum": "" }, "require": { - "illuminate/console": "^9.21|^10.0|^11.0|^12.0", - "illuminate/filesystem": "^9.21|^10.0|^11.0|^12.0", - "illuminate/support": "^9.21|^10.0|^11.0|^12.0", - "illuminate/validation": "^9.21|^10.0|^11.0|^12.0", + "illuminate/console": "^9.21|^10.0|^11.0|^12.0|^13.0", + "illuminate/filesystem": "^9.21|^10.0|^11.0|^12.0|^13.0", + "illuminate/support": "^9.21|^10.0|^11.0|^12.0|^13.0", + "illuminate/validation": "^9.21|^10.0|^11.0|^12.0|^13.0", "php": "^8.0", - "symfony/console": "^6.0|^7.0" + "symfony/console": "^6.0|^7.0|^8.0" }, "require-dev": { - "orchestra/testbench": "^7.35|^8.15|^9.0|^10.0", - "phpunit/phpunit": "^9.3|^10.4|^11.5" + "orchestra/testbench": "^7.35|^8.15|^9.0|^10.0|^11.0", + "phpunit/phpunit": "^9.3|^10.4|^11.5|^12.5|^13.0" }, "type": "library", "extra": { @@ -2584,9 +2679,9 @@ "ui" ], "support": { - "source": "https://github.com/laravel/ui/tree/v4.6.1" + "source": "https://github.com/laravel/ui/tree/v4.6.3" }, - "time": "2025-01-28T15:15:29+00:00" + "time": "2026-03-17T13:41:52+00:00" }, { "name": "lcobucci/jwt", @@ -2663,16 +2758,16 @@ }, { "name": "league/commonmark", - "version": "2.8.1", + "version": "2.8.2", "source": { "type": "git", "url": "https://github.com/thephpleague/commonmark.git", - "reference": "84b1ca48347efdbe775426f108622a42735a6579" + "reference": "59fb075d2101740c337c7216e3f32b36c204218b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/84b1ca48347efdbe775426f108622a42735a6579", - "reference": "84b1ca48347efdbe775426f108622a42735a6579", + "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/59fb075d2101740c337c7216e3f32b36c204218b", + "reference": "59fb075d2101740c337c7216e3f32b36c204218b", "shasum": "" }, "require": { @@ -2766,7 +2861,7 @@ "type": "tidelift" } ], - "time": "2026-03-05T21:37:03+00:00" + "time": "2026-03-19T13:16:38+00:00" }, { "name": "league/config", @@ -2852,16 +2947,16 @@ }, { "name": "league/flysystem", - "version": "3.32.0", + "version": "3.33.0", "source": { "type": "git", "url": "https://github.com/thephpleague/flysystem.git", - "reference": "254b1595b16b22dbddaaef9ed6ca9fdac4956725" + "reference": "570b8871e0ce693764434b29154c54b434905350" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/254b1595b16b22dbddaaef9ed6ca9fdac4956725", - "reference": "254b1595b16b22dbddaaef9ed6ca9fdac4956725", + "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/570b8871e0ce693764434b29154c54b434905350", + "reference": "570b8871e0ce693764434b29154c54b434905350", "shasum": "" }, "require": { @@ -2929,9 +3024,9 @@ ], "support": { "issues": "https://github.com/thephpleague/flysystem/issues", - "source": "https://github.com/thephpleague/flysystem/tree/3.32.0" + "source": "https://github.com/thephpleague/flysystem/tree/3.33.0" }, - "time": "2026-02-25T17:01:41+00:00" + "time": "2026-03-25T07:59:30+00:00" }, { "name": "league/flysystem-aws-s3-v3", @@ -3039,16 +3134,16 @@ }, { "name": "league/flysystem-sftp-v3", - "version": "3.31.0", + "version": "3.33.0", "source": { "type": "git", "url": "https://github.com/thephpleague/flysystem-sftp-v3.git", - "reference": "f01dd8d66e98b20608846963cc790c2b698e8b03" + "reference": "34ff5ef0f841add92e2b902c1005f72135b03646" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/flysystem-sftp-v3/zipball/f01dd8d66e98b20608846963cc790c2b698e8b03", - "reference": "f01dd8d66e98b20608846963cc790c2b698e8b03", + "url": "https://api.github.com/repos/thephpleague/flysystem-sftp-v3/zipball/34ff5ef0f841add92e2b902c1005f72135b03646", + "reference": "34ff5ef0f841add92e2b902c1005f72135b03646", "shasum": "" }, "require": { @@ -3082,9 +3177,9 @@ "sftp" ], "support": { - "source": "https://github.com/thephpleague/flysystem-sftp-v3/tree/3.31.0" + "source": "https://github.com/thephpleague/flysystem-sftp-v3/tree/3.33.0" }, - "time": "2026-01-23T15:30:45+00:00" + "time": "2026-03-20T13:22:31+00:00" }, { "name": "league/mime-type-detection", @@ -3220,20 +3315,20 @@ }, { "name": "league/uri", - "version": "7.8.0", + "version": "7.8.1", "source": { "type": "git", "url": "https://github.com/thephpleague/uri.git", - "reference": "4436c6ec8d458e4244448b069cc572d088230b76" + "reference": "08cf38e3924d4f56238125547b5720496fac8fd4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/uri/zipball/4436c6ec8d458e4244448b069cc572d088230b76", - "reference": "4436c6ec8d458e4244448b069cc572d088230b76", + "url": "https://api.github.com/repos/thephpleague/uri/zipball/08cf38e3924d4f56238125547b5720496fac8fd4", + "reference": "08cf38e3924d4f56238125547b5720496fac8fd4", "shasum": "" }, "require": { - "league/uri-interfaces": "^7.8", + "league/uri-interfaces": "^7.8.1", "php": "^8.1", "psr/http-factory": "^1" }, @@ -3306,7 +3401,7 @@ "docs": "https://uri.thephpleague.com", "forum": "https://thephpleague.slack.com", "issues": "https://github.com/thephpleague/uri-src/issues", - "source": "https://github.com/thephpleague/uri/tree/7.8.0" + "source": "https://github.com/thephpleague/uri/tree/7.8.1" }, "funding": [ { @@ -3314,20 +3409,20 @@ "type": "github" } ], - "time": "2026-01-14T17:24:56+00:00" + "time": "2026-03-15T20:22:25+00:00" }, { "name": "league/uri-interfaces", - "version": "7.8.0", + "version": "7.8.1", "source": { "type": "git", "url": "https://github.com/thephpleague/uri-interfaces.git", - "reference": "c5c5cd056110fc8afaba29fa6b72a43ced42acd4" + "reference": "85d5c77c5d6d3af6c54db4a78246364908f3c928" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/uri-interfaces/zipball/c5c5cd056110fc8afaba29fa6b72a43ced42acd4", - "reference": "c5c5cd056110fc8afaba29fa6b72a43ced42acd4", + "url": "https://api.github.com/repos/thephpleague/uri-interfaces/zipball/85d5c77c5d6d3af6c54db4a78246364908f3c928", + "reference": "85d5c77c5d6d3af6c54db4a78246364908f3c928", "shasum": "" }, "require": { @@ -3390,7 +3485,7 @@ "docs": "https://uri.thephpleague.com", "forum": "https://thephpleague.slack.com", "issues": "https://github.com/thephpleague/uri-src/issues", - "source": "https://github.com/thephpleague/uri-interfaces/tree/7.8.0" + "source": "https://github.com/thephpleague/uri-interfaces/tree/7.8.1" }, "funding": [ { @@ -3398,7 +3493,7 @@ "type": "github" } ], - "time": "2026-01-15T06:54:53+00:00" + "time": "2026-03-08T20:05:35+00:00" }, { "name": "livewire/livewire", @@ -3540,27 +3635,27 @@ }, { "name": "lorisleiva/laravel-actions", - "version": "v2.9.1", + "version": "v2.10.1", "source": { "type": "git", "url": "https://github.com/lorisleiva/laravel-actions.git", - "reference": "11c2531366ca8bd5efcd0afc9e8047e7999926ff" + "reference": "1cb9fd448c655ae90ac93c77be0c10cb57cf27d5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/lorisleiva/laravel-actions/zipball/11c2531366ca8bd5efcd0afc9e8047e7999926ff", - "reference": "11c2531366ca8bd5efcd0afc9e8047e7999926ff", + "url": "https://api.github.com/repos/lorisleiva/laravel-actions/zipball/1cb9fd448c655ae90ac93c77be0c10cb57cf27d5", + "reference": "1cb9fd448c655ae90ac93c77be0c10cb57cf27d5", "shasum": "" }, "require": { - "illuminate/contracts": "^10.0|^11.0|^12.0", - "lorisleiva/lody": "^0.6", - "php": "^8.1" + "illuminate/contracts": "^11.0|^12.0|^13.0", + "lorisleiva/lody": "^0.7", + "php": "^8.2" }, "require-dev": { - "orchestra/testbench": "^10.0", - "pestphp/pest": "^2.34|^3.0", - "phpunit/phpunit": "^10.5|^11.5" + "orchestra/testbench": "^9.0|^10.0|^11.0", + "pestphp/pest": "^3.0|^4.0", + "phpunit/phpunit": "^11.5|^12.0" }, "type": "library", "extra": { @@ -3604,7 +3699,7 @@ ], "support": { "issues": "https://github.com/lorisleiva/laravel-actions/issues", - "source": "https://github.com/lorisleiva/laravel-actions/tree/v2.9.1" + "source": "https://github.com/lorisleiva/laravel-actions/tree/v2.10.1" }, "funding": [ { @@ -3612,30 +3707,30 @@ "type": "github" } ], - "time": "2025-08-10T08:58:19+00:00" + "time": "2026-03-19T13:33:12+00:00" }, { "name": "lorisleiva/lody", - "version": "v0.6.0", + "version": "v0.7.0", "source": { "type": "git", "url": "https://github.com/lorisleiva/lody.git", - "reference": "6bada710ebc75f06fdf62db26327be1592c4f014" + "reference": "82ecb6faa55fb20109e6959f42f0f652cd77674b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/lorisleiva/lody/zipball/6bada710ebc75f06fdf62db26327be1592c4f014", - "reference": "6bada710ebc75f06fdf62db26327be1592c4f014", + "url": "https://api.github.com/repos/lorisleiva/lody/zipball/82ecb6faa55fb20109e6959f42f0f652cd77674b", + "reference": "82ecb6faa55fb20109e6959f42f0f652cd77674b", "shasum": "" }, "require": { - "illuminate/contracts": "^10.0|^11.0|^12.0", - "php": "^8.1" + "illuminate/contracts": "^11.0|^12.0|^13.0", + "php": "^8.2" }, "require-dev": { - "orchestra/testbench": "^10.0", - "pestphp/pest": "^2.34|^3.0", - "phpunit/phpunit": "^10.5|^11.5" + "orchestra/testbench": "^9.0|^10.0|^11.0", + "pestphp/pest": "^3.0|^4.0", + "phpunit/phpunit": "^11.5|^12.0" }, "type": "library", "extra": { @@ -3676,7 +3771,7 @@ ], "support": { "issues": "https://github.com/lorisleiva/lody/issues", - "source": "https://github.com/lorisleiva/lody/tree/v0.6.0" + "source": "https://github.com/lorisleiva/lody/tree/v0.7.0" }, "funding": [ { @@ -3684,7 +3779,7 @@ "type": "github" } ], - "time": "2025-03-01T19:21:17+00:00" + "time": "2026-03-18T12:49:31+00:00" }, { "name": "monolog/monolog", @@ -3857,16 +3952,16 @@ }, { "name": "nesbot/carbon", - "version": "3.11.1", + "version": "3.11.3", "source": { "type": "git", "url": "https://github.com/CarbonPHP/carbon.git", - "reference": "f438fcc98f92babee98381d399c65336f3a3827f" + "reference": "6a7e652845bb018c668220c2a545aded8594fbbf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/CarbonPHP/carbon/zipball/f438fcc98f92babee98381d399c65336f3a3827f", - "reference": "f438fcc98f92babee98381d399c65336f3a3827f", + "url": "https://api.github.com/repos/CarbonPHP/carbon/zipball/6a7e652845bb018c668220c2a545aded8594fbbf", + "reference": "6a7e652845bb018c668220c2a545aded8594fbbf", "shasum": "" }, "require": { @@ -3958,7 +4053,7 @@ "type": "tidelift" } ], - "time": "2026-01-29T09:26:29+00:00" + "time": "2026-03-11T17:23:39+00:00" }, { "name": "nette/schema", @@ -4864,16 +4959,16 @@ }, { "name": "phpdocumentor/reflection-docblock", - "version": "5.6.6", + "version": "5.6.7", "source": { "type": "git", "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", - "reference": "5cee1d3dfc2d2aa6599834520911d246f656bcb8" + "reference": "31a105931bc8ffa3a123383829772e832fd8d903" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/5cee1d3dfc2d2aa6599834520911d246f656bcb8", - "reference": "5cee1d3dfc2d2aa6599834520911d246f656bcb8", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/31a105931bc8ffa3a123383829772e832fd8d903", + "reference": "31a105931bc8ffa3a123383829772e832fd8d903", "shasum": "" }, "require": { @@ -4922,9 +5017,9 @@ "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", "support": { "issues": "https://github.com/phpDocumentor/ReflectionDocBlock/issues", - "source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/5.6.6" + "source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/5.6.7" }, - "time": "2025-12-22T21:13:58+00:00" + "time": "2026-03-18T20:47:46+00:00" }, { "name": "phpdocumentor/type-resolver", @@ -5061,16 +5156,16 @@ }, { "name": "phpseclib/phpseclib", - "version": "3.0.49", + "version": "3.0.50", "source": { "type": "git", "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "6233a1e12584754e6b5daa69fe1289b47775c1b9" + "reference": "aa6ad8321ed103dc3624fb600a25b66ebf78ec7b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/6233a1e12584754e6b5daa69fe1289b47775c1b9", - "reference": "6233a1e12584754e6b5daa69fe1289b47775c1b9", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/aa6ad8321ed103dc3624fb600a25b66ebf78ec7b", + "reference": "aa6ad8321ed103dc3624fb600a25b66ebf78ec7b", "shasum": "" }, "require": { @@ -5151,7 +5246,7 @@ ], "support": { "issues": "https://github.com/phpseclib/phpseclib/issues", - "source": "https://github.com/phpseclib/phpseclib/tree/3.0.49" + "source": "https://github.com/phpseclib/phpseclib/tree/3.0.50" }, "funding": [ { @@ -5167,7 +5262,7 @@ "type": "tidelift" } ], - "time": "2026-01-27T09:17:28+00:00" + "time": "2026-03-19T02:57:58+00:00" }, { "name": "phpstan/phpdoc-parser", @@ -5284,16 +5379,16 @@ }, { "name": "poliander/cron", - "version": "3.3.0", + "version": "3.3.1", "source": { "type": "git", "url": "https://github.com/poliander/cron.git", - "reference": "13892a8d7f90c7e93947f21e115037b6a0d979bd" + "reference": "8b6fc91b86de3d973f6ea16eda846f522ed1ce7a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/poliander/cron/zipball/13892a8d7f90c7e93947f21e115037b6a0d979bd", - "reference": "13892a8d7f90c7e93947f21e115037b6a0d979bd", + "url": "https://api.github.com/repos/poliander/cron/zipball/8b6fc91b86de3d973f6ea16eda846f522ed1ce7a", + "reference": "8b6fc91b86de3d973f6ea16eda846f522ed1ce7a", "shasum": "" }, "require": { @@ -5322,9 +5417,9 @@ "homepage": "https://github.com/poliander/cron", "support": { "issues": "https://github.com/poliander/cron/issues", - "source": "https://github.com/poliander/cron/tree/3.3.0" + "source": "https://github.com/poliander/cron/tree/3.3.1" }, - "time": "2025-11-23T17:30:50+00:00" + "time": "2026-03-05T19:37:26+00:00" }, { "name": "pragmarx/google2fa", @@ -5841,16 +5936,16 @@ }, { "name": "psy/psysh", - "version": "v0.12.20", + "version": "v0.12.22", "source": { "type": "git", "url": "https://github.com/bobthecow/psysh.git", - "reference": "19678eb6b952a03b8a1d96ecee9edba518bb0373" + "reference": "3be75d5b9244936dd4ac62ade2bfb004d13acf0f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/bobthecow/psysh/zipball/19678eb6b952a03b8a1d96ecee9edba518bb0373", - "reference": "19678eb6b952a03b8a1d96ecee9edba518bb0373", + "url": "https://api.github.com/repos/bobthecow/psysh/zipball/3be75d5b9244936dd4ac62ade2bfb004d13acf0f", + "reference": "3be75d5b9244936dd4ac62ade2bfb004d13acf0f", "shasum": "" }, "require": { @@ -5914,9 +6009,9 @@ ], "support": { "issues": "https://github.com/bobthecow/psysh/issues", - "source": "https://github.com/bobthecow/psysh/tree/v0.12.20" + "source": "https://github.com/bobthecow/psysh/tree/v0.12.22" }, - "time": "2026-02-11T15:05:28+00:00" + "time": "2026-03-22T23:03:24+00:00" }, { "name": "purplepixie/phpdns", @@ -6353,16 +6448,16 @@ }, { "name": "sentry/sentry", - "version": "4.21.0", + "version": "4.23.0", "source": { "type": "git", "url": "https://github.com/getsentry/sentry-php.git", - "reference": "2bf405fc4d38f00073a7d023cf321e59f614d54c" + "reference": "121a674d5fffcdb8e414b75c1b76edba8e592b66" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/getsentry/sentry-php/zipball/2bf405fc4d38f00073a7d023cf321e59f614d54c", - "reference": "2bf405fc4d38f00073a7d023cf321e59f614d54c", + "url": "https://api.github.com/repos/getsentry/sentry-php/zipball/121a674d5fffcdb8e414b75c1b76edba8e592b66", + "reference": "121a674d5fffcdb8e414b75c1b76edba8e592b66", "shasum": "" }, "require": { @@ -6384,12 +6479,14 @@ "guzzlehttp/psr7": "^1.8.4|^2.1.1", "monolog/monolog": "^1.6|^2.0|^3.0", "nyholm/psr7": "^1.8", + "open-telemetry/api": "^1.0", + "open-telemetry/exporter-otlp": "^1.0", + "open-telemetry/sdk": "^1.0", "phpbench/phpbench": "^1.0", "phpstan/phpstan": "^1.3", "phpunit/phpunit": "^8.5.52|^9.6.34", "spiral/roadrunner-http": "^3.6", - "spiral/roadrunner-worker": "^3.6", - "vimeo/psalm": "^4.17" + "spiral/roadrunner-worker": "^3.6" }, "suggest": { "monolog/monolog": "Allow sending log messages to Sentry by using the included Monolog handler." @@ -6428,7 +6525,7 @@ ], "support": { "issues": "https://github.com/getsentry/sentry-php/issues", - "source": "https://github.com/getsentry/sentry-php/tree/4.21.0" + "source": "https://github.com/getsentry/sentry-php/tree/4.23.0" }, "funding": [ { @@ -6440,38 +6537,39 @@ "type": "custom" } ], - "time": "2026-02-24T15:32:51+00:00" + "time": "2026-03-23T13:15:52+00:00" }, { "name": "sentry/sentry-laravel", - "version": "4.21.0", + "version": "4.24.0", "source": { "type": "git", "url": "https://github.com/getsentry/sentry-laravel.git", - "reference": "4b939116c2d3c5de328f23a5f1dfb97b40e0c17b" + "reference": "f823bd85e38e06cb4f1b7a82d48a2fc95320b31d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/getsentry/sentry-laravel/zipball/4b939116c2d3c5de328f23a5f1dfb97b40e0c17b", - "reference": "4b939116c2d3c5de328f23a5f1dfb97b40e0c17b", + "url": "https://api.github.com/repos/getsentry/sentry-laravel/zipball/f823bd85e38e06cb4f1b7a82d48a2fc95320b31d", + "reference": "f823bd85e38e06cb4f1b7a82d48a2fc95320b31d", "shasum": "" }, "require": { - "illuminate/support": "^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0", + "illuminate/support": "^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0 | ^13.0", "nyholm/psr7": "^1.0", "php": "^7.2 | ^8.0", - "sentry/sentry": "^4.21.0", + "sentry/sentry": "^4.23.0", "symfony/psr-http-message-bridge": "^1.0 | ^2.0 | ^6.0 | ^7.0 | ^8.0" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.11", "guzzlehttp/guzzle": "^7.2", "laravel/folio": "^1.1", - "laravel/framework": "^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0", + "laravel/framework": "^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0 | ^13.0", + "laravel/octane": "^2.15", "laravel/pennant": "^1.0", - "livewire/livewire": "^2.0 | ^3.0", + "livewire/livewire": "^2.0 | ^3.0 | ^4.0", "mockery/mockery": "^1.3", - "orchestra/testbench": "^4.7 | ^5.1 | ^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0", + "orchestra/testbench": "^4.7 | ^5.1 | ^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0 | ^11.0", "phpstan/phpstan": "^1.10", "phpunit/phpunit": "^8.5 | ^9.6 | ^10.4 | ^11.5" }, @@ -6518,7 +6616,7 @@ ], "support": { "issues": "https://github.com/getsentry/sentry-laravel/issues", - "source": "https://github.com/getsentry/sentry-laravel/tree/4.21.0" + "source": "https://github.com/getsentry/sentry-laravel/tree/4.24.0" }, "funding": [ { @@ -6530,7 +6628,7 @@ "type": "custom" } ], - "time": "2026-02-26T16:08:52+00:00" + "time": "2026-03-24T10:33:54+00:00" }, { "name": "socialiteproviders/authentik", @@ -6776,22 +6874,22 @@ }, { "name": "socialiteproviders/manager", - "version": "v4.8.1", + "version": "4.9.2", "source": { "type": "git", "url": "https://github.com/SocialiteProviders/Manager.git", - "reference": "8180ec14bef230ec2351cff993d5d2d7ca470ef4" + "reference": "35372dc62787e61e91cfec73f45fd5d5ae0f8891" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/SocialiteProviders/Manager/zipball/8180ec14bef230ec2351cff993d5d2d7ca470ef4", - "reference": "8180ec14bef230ec2351cff993d5d2d7ca470ef4", + "url": "https://api.github.com/repos/SocialiteProviders/Manager/zipball/35372dc62787e61e91cfec73f45fd5d5ae0f8891", + "reference": "35372dc62787e61e91cfec73f45fd5d5ae0f8891", "shasum": "" }, "require": { - "illuminate/support": "^8.0 || ^9.0 || ^10.0 || ^11.0 || ^12.0", + "illuminate/support": "^11.0 || ^12.0 || ^13.0", "laravel/socialite": "^5.5", - "php": "^8.1" + "php": "^8.2" }, "require-dev": { "mockery/mockery": "^1.2", @@ -6846,7 +6944,7 @@ "issues": "https://github.com/socialiteproviders/manager/issues", "source": "https://github.com/socialiteproviders/manager" }, - "time": "2025-02-24T19:33:30+00:00" + "time": "2026-03-18T22:13:24+00:00" }, { "name": "socialiteproviders/microsoft-azure", @@ -6951,16 +7049,16 @@ }, { "name": "spatie/backtrace", - "version": "1.8.1", + "version": "1.8.2", "source": { "type": "git", "url": "https://github.com/spatie/backtrace.git", - "reference": "8c0f16a59ae35ec8c62d85c3c17585158f430110" + "reference": "8ffe78be5ed355b5009e3dd989d183433e9a5adc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/backtrace/zipball/8c0f16a59ae35ec8c62d85c3c17585158f430110", - "reference": "8c0f16a59ae35ec8c62d85c3c17585158f430110", + "url": "https://api.github.com/repos/spatie/backtrace/zipball/8ffe78be5ed355b5009e3dd989d183433e9a5adc", + "reference": "8ffe78be5ed355b5009e3dd989d183433e9a5adc", "shasum": "" }, "require": { @@ -6971,7 +7069,7 @@ "laravel/serializable-closure": "^1.3 || ^2.0", "phpunit/phpunit": "^9.3 || ^11.4.3", "spatie/phpunit-snapshot-assertions": "^4.2 || ^5.1.6", - "symfony/var-dumper": "^5.1 || ^6.0 || ^7.0" + "symfony/var-dumper": "^5.1|^6.0|^7.0|^8.0" }, "type": "library", "autoload": { @@ -6999,7 +7097,7 @@ ], "support": { "issues": "https://github.com/spatie/backtrace/issues", - "source": "https://github.com/spatie/backtrace/tree/1.8.1" + "source": "https://github.com/spatie/backtrace/tree/1.8.2" }, "funding": [ { @@ -7011,7 +7109,7 @@ "type": "other" } ], - "time": "2025-08-26T08:22:30+00:00" + "time": "2026-03-11T13:48:28+00:00" }, { "name": "spatie/commonmark-shiki-highlighter", @@ -7075,16 +7173,16 @@ }, { "name": "spatie/laravel-activitylog", - "version": "4.12.1", + "version": "4.12.3", "source": { "type": "git", "url": "https://github.com/spatie/laravel-activitylog.git", - "reference": "bf66b5bbe9a946e977e876420d16b30b9aff1b2d" + "reference": "2a2024fcac05628b0d1bfdbb1b94dda8b0661dc0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/laravel-activitylog/zipball/bf66b5bbe9a946e977e876420d16b30b9aff1b2d", - "reference": "bf66b5bbe9a946e977e876420d16b30b9aff1b2d", + "url": "https://api.github.com/repos/spatie/laravel-activitylog/zipball/2a2024fcac05628b0d1bfdbb1b94dda8b0661dc0", + "reference": "2a2024fcac05628b0d1bfdbb1b94dda8b0661dc0", "shasum": "" }, "require": { @@ -7150,7 +7248,7 @@ ], "support": { "issues": "https://github.com/spatie/laravel-activitylog/issues", - "source": "https://github.com/spatie/laravel-activitylog/tree/4.12.1" + "source": "https://github.com/spatie/laravel-activitylog/tree/4.12.3" }, "funding": [ { @@ -7162,20 +7260,20 @@ "type": "github" } ], - "time": "2026-02-22T08:37:18+00:00" + "time": "2026-03-24T12:33:53+00:00" }, { "name": "spatie/laravel-data", - "version": "4.20.0", + "version": "4.20.1", "source": { "type": "git", "url": "https://github.com/spatie/laravel-data.git", - "reference": "05b792ab0e059d26eca15d47d199ba6f4c96054e" + "reference": "5490cb15de6fc8b35a8cd2f661fac072d987a1ad" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/laravel-data/zipball/05b792ab0e059d26eca15d47d199ba6f4c96054e", - "reference": "05b792ab0e059d26eca15d47d199ba6f4c96054e", + "url": "https://api.github.com/repos/spatie/laravel-data/zipball/5490cb15de6fc8b35a8cd2f661fac072d987a1ad", + "reference": "5490cb15de6fc8b35a8cd2f661fac072d987a1ad", "shasum": "" }, "require": { @@ -7236,7 +7334,7 @@ ], "support": { "issues": "https://github.com/spatie/laravel-data/issues", - "source": "https://github.com/spatie/laravel-data/tree/4.20.0" + "source": "https://github.com/spatie/laravel-data/tree/4.20.1" }, "funding": [ { @@ -7244,7 +7342,7 @@ "type": "github" } ], - "time": "2026-02-25T16:18:18+00:00" + "time": "2026-03-18T07:44:01+00:00" }, { "name": "spatie/laravel-markdown", @@ -7385,16 +7483,16 @@ }, { "name": "spatie/laravel-ray", - "version": "1.43.6", + "version": "1.43.7", "source": { "type": "git", "url": "https://github.com/spatie/laravel-ray.git", - "reference": "117a4addce2cb8adfc01b864435b5b278e2f0c40" + "reference": "d550d0b5bf87bb1b1668089f3c843e786ee522d3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/laravel-ray/zipball/117a4addce2cb8adfc01b864435b5b278e2f0c40", - "reference": "117a4addce2cb8adfc01b864435b5b278e2f0c40", + "url": "https://api.github.com/repos/spatie/laravel-ray/zipball/d550d0b5bf87bb1b1668089f3c843e786ee522d3", + "reference": "d550d0b5bf87bb1b1668089f3c843e786ee522d3", "shasum": "" }, "require": { @@ -7408,7 +7506,7 @@ "spatie/backtrace": "^1.7.1", "spatie/ray": "^1.45.0", "symfony/stopwatch": "4.2|^5.1|^6.0|^7.0|^8.0", - "zbateson/mail-mime-parser": "^1.3.1|^2.0|^3.0" + "zbateson/mail-mime-parser": "^1.3.1|^2.0|^3.0|^4.0" }, "require-dev": { "guzzlehttp/guzzle": "^7.3", @@ -7458,7 +7556,7 @@ ], "support": { "issues": "https://github.com/spatie/laravel-ray/issues", - "source": "https://github.com/spatie/laravel-ray/tree/1.43.6" + "source": "https://github.com/spatie/laravel-ray/tree/1.43.7" }, "funding": [ { @@ -7470,7 +7568,7 @@ "type": "other" } ], - "time": "2026-02-19T10:24:51+00:00" + "time": "2026-03-06T08:19:04+00:00" }, { "name": "spatie/laravel-schemaless-attributes", @@ -7892,27 +7990,27 @@ }, { "name": "stevebauman/purify", - "version": "v6.3.1", + "version": "v6.3.2", "source": { "type": "git", "url": "https://github.com/stevebauman/purify.git", - "reference": "3acb5e77904f420ce8aad8fa1c7f394e82daa500" + "reference": "deba4aa55a45a7593c369b52d481c87b545a5bf8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/stevebauman/purify/zipball/3acb5e77904f420ce8aad8fa1c7f394e82daa500", - "reference": "3acb5e77904f420ce8aad8fa1c7f394e82daa500", + "url": "https://api.github.com/repos/stevebauman/purify/zipball/deba4aa55a45a7593c369b52d481c87b545a5bf8", + "reference": "deba4aa55a45a7593c369b52d481c87b545a5bf8", "shasum": "" }, "require": { "ezyang/htmlpurifier": "^4.17", - "illuminate/contracts": "^7.0|^8.0|^9.0|^10.0|^11.0|^12.0", - "illuminate/support": "^7.0|^8.0|^9.0|^10.0|^11.0|^12.0", + "illuminate/contracts": "^7.0|^8.0|^9.0|^10.0|^11.0|^12.0|^13.0", + "illuminate/support": "^7.0|^8.0|^9.0|^10.0|^11.0|^12.0|^13.0", "php": ">=7.4" }, "require-dev": { - "orchestra/testbench": "^5.0|^6.0|^7.0|^8.0|^9.0|^10.0", - "phpunit/phpunit": "^8.0|^9.0|^10.0|^11.5.3" + "orchestra/testbench": "^5.0|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "phpunit/phpunit": "^8.0|^9.0|^10.0|^11.5.3|^12.5.12" }, "type": "library", "extra": { @@ -7952,9 +8050,9 @@ ], "support": { "issues": "https://github.com/stevebauman/purify/issues", - "source": "https://github.com/stevebauman/purify/tree/v6.3.1" + "source": "https://github.com/stevebauman/purify/tree/v6.3.2" }, - "time": "2025-05-21T16:53:09+00:00" + "time": "2026-03-18T16:42:42+00:00" }, { "name": "stripe/stripe-php", @@ -8094,16 +8192,16 @@ }, { "name": "symfony/console", - "version": "v7.4.6", + "version": "v7.4.7", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "6d643a93b47398599124022eb24d97c153c12f27" + "reference": "e1e6770440fb9c9b0cf725f81d1361ad1835329d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/6d643a93b47398599124022eb24d97c153c12f27", - "reference": "6d643a93b47398599124022eb24d97c153c12f27", + "url": "https://api.github.com/repos/symfony/console/zipball/e1e6770440fb9c9b0cf725f81d1361ad1835329d", + "reference": "e1e6770440fb9c9b0cf725f81d1361ad1835329d", "shasum": "" }, "require": { @@ -8168,7 +8266,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v7.4.6" + "source": "https://github.com/symfony/console/tree/v7.4.7" }, "funding": [ { @@ -8188,7 +8286,7 @@ "type": "tidelift" } ], - "time": "2026-02-25T17:02:47+00:00" + "time": "2026-03-06T14:06:20+00:00" }, { "name": "symfony/css-selector", @@ -8709,16 +8807,16 @@ }, { "name": "symfony/http-foundation", - "version": "v7.4.6", + "version": "v7.4.7", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "fd97d5e926e988a363cef56fbbf88c5c528e9065" + "reference": "f94b3e7b7dafd40e666f0c9ff2084133bae41e81" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/fd97d5e926e988a363cef56fbbf88c5c528e9065", - "reference": "fd97d5e926e988a363cef56fbbf88c5c528e9065", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/f94b3e7b7dafd40e666f0c9ff2084133bae41e81", + "reference": "f94b3e7b7dafd40e666f0c9ff2084133bae41e81", "shasum": "" }, "require": { @@ -8767,7 +8865,7 @@ "description": "Defines an object-oriented layer for the HTTP specification", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-foundation/tree/v7.4.6" + "source": "https://github.com/symfony/http-foundation/tree/v7.4.7" }, "funding": [ { @@ -8787,20 +8885,20 @@ "type": "tidelift" } ], - "time": "2026-02-21T16:25:55+00:00" + "time": "2026-03-06T13:15:18+00:00" }, { "name": "symfony/http-kernel", - "version": "v7.4.6", + "version": "v7.4.7", "source": { "type": "git", "url": "https://github.com/symfony/http-kernel.git", - "reference": "002ac0cf4cd972a7fd0912dcd513a95e8a81ce83" + "reference": "3b3fcf386c809be990c922e10e4c620d6367cab1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-kernel/zipball/002ac0cf4cd972a7fd0912dcd513a95e8a81ce83", - "reference": "002ac0cf4cd972a7fd0912dcd513a95e8a81ce83", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/3b3fcf386c809be990c922e10e4c620d6367cab1", + "reference": "3b3fcf386c809be990c922e10e4c620d6367cab1", "shasum": "" }, "require": { @@ -8886,7 +8984,7 @@ "description": "Provides a structured process for converting a Request into a Response", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-kernel/tree/v7.4.6" + "source": "https://github.com/symfony/http-kernel/tree/v7.4.7" }, "funding": [ { @@ -8906,7 +9004,7 @@ "type": "tidelift" } ], - "time": "2026-02-26T08:30:57+00:00" + "time": "2026-03-06T16:33:18+00:00" }, { "name": "symfony/mailer", @@ -8994,16 +9092,16 @@ }, { "name": "symfony/mime", - "version": "v7.4.6", + "version": "v7.4.7", "source": { "type": "git", "url": "https://github.com/symfony/mime.git", - "reference": "9fc881d95feae4c6c48678cb6372bd8a7ba04f5f" + "reference": "da5ab4fde3f6c88ab06e96185b9922f48b677cd1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/mime/zipball/9fc881d95feae4c6c48678cb6372bd8a7ba04f5f", - "reference": "9fc881d95feae4c6c48678cb6372bd8a7ba04f5f", + "url": "https://api.github.com/repos/symfony/mime/zipball/da5ab4fde3f6c88ab06e96185b9922f48b677cd1", + "reference": "da5ab4fde3f6c88ab06e96185b9922f48b677cd1", "shasum": "" }, "require": { @@ -9059,7 +9157,7 @@ "mime-type" ], "support": { - "source": "https://github.com/symfony/mime/tree/v7.4.6" + "source": "https://github.com/symfony/mime/tree/v7.4.7" }, "funding": [ { @@ -9079,7 +9177,7 @@ "type": "tidelift" } ], - "time": "2026-02-05T15:57:06+00:00" + "time": "2026-03-05T15:24:09+00:00" }, { "name": "symfony/options-resolver", @@ -11414,31 +11512,31 @@ }, { "name": "zbateson/mail-mime-parser", - "version": "3.0.5", + "version": "4.0.1", "source": { "type": "git", "url": "https://github.com/zbateson/mail-mime-parser.git", - "reference": "ff054c8e05310c445c2028c6128a4319cc9f6aa8" + "reference": "3db681988a48fdffdba551dcc6b2f4c2da574540" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zbateson/mail-mime-parser/zipball/ff054c8e05310c445c2028c6128a4319cc9f6aa8", - "reference": "ff054c8e05310c445c2028c6128a4319cc9f6aa8", + "url": "https://api.github.com/repos/zbateson/mail-mime-parser/zipball/3db681988a48fdffdba551dcc6b2f4c2da574540", + "reference": "3db681988a48fdffdba551dcc6b2f4c2da574540", "shasum": "" }, "require": { "guzzlehttp/psr7": "^2.5", - "php": ">=8.0", + "php": ">=8.1", "php-di/php-di": "^6.0|^7.0", "psr/log": "^1|^2|^3", - "zbateson/mb-wrapper": "^2.0", - "zbateson/stream-decorators": "^2.1" + "zbateson/mb-wrapper": "^2.0 || ^3.0", + "zbateson/stream-decorators": "^2.1 || ^3.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "*", + "friendsofphp/php-cs-fixer": "^3.0", "monolog/monolog": "^2|^3", - "phpstan/phpstan": "*", - "phpunit/phpunit": "^9.6" + "phpstan/phpstan": "^2.0", + "phpunit/phpunit": "^10.5" }, "suggest": { "ext-iconv": "For best support/performance", @@ -11486,31 +11584,31 @@ "type": "github" } ], - "time": "2025-12-02T00:29:16+00:00" + "time": "2026-03-11T18:03:41+00:00" }, { "name": "zbateson/mb-wrapper", - "version": "2.0.1", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/zbateson/mb-wrapper.git", - "reference": "50a14c0c9537f978a61cde9fdc192a0267cc9cff" + "reference": "f0ee6af2712e92e52ee2552588cd69d21ab3363f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zbateson/mb-wrapper/zipball/50a14c0c9537f978a61cde9fdc192a0267cc9cff", - "reference": "50a14c0c9537f978a61cde9fdc192a0267cc9cff", + "url": "https://api.github.com/repos/zbateson/mb-wrapper/zipball/f0ee6af2712e92e52ee2552588cd69d21ab3363f", + "reference": "f0ee6af2712e92e52ee2552588cd69d21ab3363f", "shasum": "" }, "require": { - "php": ">=8.0", + "php": ">=8.1", "symfony/polyfill-iconv": "^1.9", "symfony/polyfill-mbstring": "^1.9" }, "require-dev": { "friendsofphp/php-cs-fixer": "*", "phpstan/phpstan": "*", - "phpunit/phpunit": "^9.6|^10.0" + "phpunit/phpunit": "^10.0|^11.0" }, "suggest": { "ext-iconv": "For best support/performance", @@ -11547,7 +11645,7 @@ ], "support": { "issues": "https://github.com/zbateson/mb-wrapper/issues", - "source": "https://github.com/zbateson/mb-wrapper/tree/2.0.1" + "source": "https://github.com/zbateson/mb-wrapper/tree/3.0.0" }, "funding": [ { @@ -11555,31 +11653,31 @@ "type": "github" } ], - "time": "2024-12-20T22:05:33+00:00" + "time": "2026-02-13T19:33:26+00:00" }, { "name": "zbateson/stream-decorators", - "version": "2.1.1", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/zbateson/stream-decorators.git", - "reference": "32a2a62fb0f26313395c996ebd658d33c3f9c4e5" + "reference": "0c0e79a8c960055c0e2710357098eedc07e6697a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zbateson/stream-decorators/zipball/32a2a62fb0f26313395c996ebd658d33c3f9c4e5", - "reference": "32a2a62fb0f26313395c996ebd658d33c3f9c4e5", + "url": "https://api.github.com/repos/zbateson/stream-decorators/zipball/0c0e79a8c960055c0e2710357098eedc07e6697a", + "reference": "0c0e79a8c960055c0e2710357098eedc07e6697a", "shasum": "" }, "require": { "guzzlehttp/psr7": "^2.5", - "php": ">=8.0", - "zbateson/mb-wrapper": "^2.0" + "php": ">=8.1", + "zbateson/mb-wrapper": "^2.0 || ^3.0" }, "require-dev": { "friendsofphp/php-cs-fixer": "*", "phpstan/phpstan": "*", - "phpunit/phpunit": "^9.6|^10.0" + "phpunit/phpunit": "^10.0 || ^11.0" }, "type": "library", "autoload": { @@ -11610,7 +11708,7 @@ ], "support": { "issues": "https://github.com/zbateson/stream-decorators/issues", - "source": "https://github.com/zbateson/stream-decorators/tree/2.1.1" + "source": "https://github.com/zbateson/stream-decorators/tree/3.0.0" }, "funding": [ { @@ -11618,7 +11716,7 @@ "type": "github" } ], - "time": "2024-04-29T21:42:39+00:00" + "time": "2026-02-13T19:45:34+00:00" }, { "name": "zircote/swagger-php", @@ -13025,16 +13123,16 @@ }, { "name": "brianium/paratest", - "version": "v7.19.0", + "version": "v7.19.2", "source": { "type": "git", "url": "https://github.com/paratestphp/paratest.git", - "reference": "7c6c29af7c4b406b49ce0c6b0a3a81d3684474e6" + "reference": "66e4f7910cecf67736bccf2b8bd53a2e3eb98bd9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/paratestphp/paratest/zipball/7c6c29af7c4b406b49ce0c6b0a3a81d3684474e6", - "reference": "7c6c29af7c4b406b49ce0c6b0a3a81d3684474e6", + "url": "https://api.github.com/repos/paratestphp/paratest/zipball/66e4f7910cecf67736bccf2b8bd53a2e3eb98bd9", + "reference": "66e4f7910cecf67736bccf2b8bd53a2e3eb98bd9", "shasum": "" }, "require": { @@ -13048,9 +13146,9 @@ "phpunit/php-code-coverage": "^12.5.3 || ^13.0.1", "phpunit/php-file-iterator": "^6.0.1 || ^7", "phpunit/php-timer": "^8 || ^9", - "phpunit/phpunit": "^12.5.9 || ^13", + "phpunit/phpunit": "^12.5.14 || ^13.0.5", "sebastian/environment": "^8.0.3 || ^9", - "symfony/console": "^7.4.4 || ^8.0.4", + "symfony/console": "^7.4.7 || ^8.0.7", "symfony/process": "^7.4.5 || ^8.0.5" }, "require-dev": { @@ -13058,11 +13156,11 @@ "ext-pcntl": "*", "ext-pcov": "*", "ext-posix": "*", - "phpstan/phpstan": "^2.1.38", - "phpstan/phpstan-deprecation-rules": "^2.0.3", - "phpstan/phpstan-phpunit": "^2.0.12", - "phpstan/phpstan-strict-rules": "^2.0.8", - "symfony/filesystem": "^7.4.0 || ^8.0.1" + "phpstan/phpstan": "^2.1.40", + "phpstan/phpstan-deprecation-rules": "^2.0.4", + "phpstan/phpstan-phpunit": "^2.0.16", + "phpstan/phpstan-strict-rules": "^2.0.10", + "symfony/filesystem": "^7.4.6 || ^8.0.6" }, "bin": [ "bin/paratest", @@ -13102,7 +13200,7 @@ ], "support": { "issues": "https://github.com/paratestphp/paratest/issues", - "source": "https://github.com/paratestphp/paratest/tree/v7.19.0" + "source": "https://github.com/paratestphp/paratest/tree/v7.19.2" }, "funding": [ { @@ -13114,7 +13212,7 @@ "type": "paypal" } ], - "time": "2026-02-06T10:53:26+00:00" + "time": "2026-03-09T14:33:17+00:00" }, { "name": "daverandom/libdns", @@ -13162,22 +13260,22 @@ }, { "name": "driftingly/rector-laravel", - "version": "2.1.9", + "version": "2.2.0", "source": { "type": "git", "url": "https://github.com/driftingly/rector-laravel.git", - "reference": "aee9d4a1d489e7ec484fc79f33137f8ee051b3f7" + "reference": "807840ceb09de6764cbfcce0719108d044a459a9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/driftingly/rector-laravel/zipball/aee9d4a1d489e7ec484fc79f33137f8ee051b3f7", - "reference": "aee9d4a1d489e7ec484fc79f33137f8ee051b3f7", + "url": "https://api.github.com/repos/driftingly/rector-laravel/zipball/807840ceb09de6764cbfcce0719108d044a459a9", + "reference": "807840ceb09de6764cbfcce0719108d044a459a9", "shasum": "" }, "require": { "php": "^7.4 || ^8.0", "rector/rector": "^2.2.7", - "webmozart/assert": "^1.11" + "webmozart/assert": "^1.11 || ^2.0" }, "type": "rector-extension", "autoload": { @@ -13192,9 +13290,9 @@ "description": "Rector upgrades rules for Laravel Framework", "support": { "issues": "https://github.com/driftingly/rector-laravel/issues", - "source": "https://github.com/driftingly/rector-laravel/tree/2.1.9" + "source": "https://github.com/driftingly/rector-laravel/tree/2.2.0" }, - "time": "2025-12-25T23:31:36+00:00" + "time": "2026-03-19T17:24:38+00:00" }, { "name": "fakerphp/faker", @@ -13502,25 +13600,25 @@ }, { "name": "laravel/boost", - "version": "v2.2.1", + "version": "v2.4.1", "source": { "type": "git", "url": "https://github.com/laravel/boost.git", - "reference": "e27f1616177377fef95296620530c44a7dda4df9" + "reference": "f6241df9fd81a86d79a051851177d4ffe3e28506" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/boost/zipball/e27f1616177377fef95296620530c44a7dda4df9", - "reference": "e27f1616177377fef95296620530c44a7dda4df9", + "url": "https://api.github.com/repos/laravel/boost/zipball/f6241df9fd81a86d79a051851177d4ffe3e28506", + "reference": "f6241df9fd81a86d79a051851177d4ffe3e28506", "shasum": "" }, "require": { "guzzlehttp/guzzle": "^7.9", - "illuminate/console": "^11.45.3|^12.41.1", - "illuminate/contracts": "^11.45.3|^12.41.1", - "illuminate/routing": "^11.45.3|^12.41.1", - "illuminate/support": "^11.45.3|^12.41.1", - "laravel/mcp": "^0.5.1", + "illuminate/console": "^11.45.3|^12.41.1|^13.0", + "illuminate/contracts": "^11.45.3|^12.41.1|^13.0", + "illuminate/routing": "^11.45.3|^12.41.1|^13.0", + "illuminate/support": "^11.45.3|^12.41.1|^13.0", + "laravel/mcp": "^0.5.1|^0.6.0", "laravel/prompts": "^0.3.10", "laravel/roster": "^0.5.0", "php": "^8.2" @@ -13528,7 +13626,7 @@ "require-dev": { "laravel/pint": "^1.27.0", "mockery/mockery": "^1.6.12", - "orchestra/testbench": "^9.15.0|^10.6", + "orchestra/testbench": "^9.15.0|^10.6|^11.0", "pestphp/pest": "^2.36.0|^3.8.4|^4.1.5", "phpstan/phpstan": "^2.1.27", "rector/rector": "^2.1" @@ -13564,20 +13662,20 @@ "issues": "https://github.com/laravel/boost/issues", "source": "https://github.com/laravel/boost" }, - "time": "2026-02-25T16:07:36+00:00" + "time": "2026-03-25T16:37:40+00:00" }, { "name": "laravel/dusk", - "version": "v8.3.6", + "version": "v8.5.0", "source": { "type": "git", "url": "https://github.com/laravel/dusk.git", - "reference": "5c3beee54f91f575f50cadcd7e5d44c80cc9a9aa" + "reference": "f9f75666bed46d1ebca13792447be6e753f4e790" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/dusk/zipball/5c3beee54f91f575f50cadcd7e5d44c80cc9a9aa", - "reference": "5c3beee54f91f575f50cadcd7e5d44c80cc9a9aa", + "url": "https://api.github.com/repos/laravel/dusk/zipball/f9f75666bed46d1ebca13792447be6e753f4e790", + "reference": "f9f75666bed46d1ebca13792447be6e753f4e790", "shasum": "" }, "require": { @@ -13636,22 +13734,22 @@ ], "support": { "issues": "https://github.com/laravel/dusk/issues", - "source": "https://github.com/laravel/dusk/tree/v8.3.6" + "source": "https://github.com/laravel/dusk/tree/v8.5.0" }, - "time": "2026-02-10T18:14:59+00:00" + "time": "2026-03-21T11:50:49+00:00" }, { "name": "laravel/mcp", - "version": "v0.5.9", + "version": "v0.6.4", "source": { "type": "git", "url": "https://github.com/laravel/mcp.git", - "reference": "39e8da60eb7bce4737c5d868d35a3fe78938c129" + "reference": "f822c5eb5beed19adb2e5bfe2f46f8c977ecea42" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/mcp/zipball/39e8da60eb7bce4737c5d868d35a3fe78938c129", - "reference": "39e8da60eb7bce4737c5d868d35a3fe78938c129", + "url": "https://api.github.com/repos/laravel/mcp/zipball/f822c5eb5beed19adb2e5bfe2f46f8c977ecea42", + "reference": "f822c5eb5beed19adb2e5bfe2f46f8c977ecea42", "shasum": "" }, "require": { @@ -13711,20 +13809,20 @@ "issues": "https://github.com/laravel/mcp/issues", "source": "https://github.com/laravel/mcp" }, - "time": "2026-02-17T19:05:53+00:00" + "time": "2026-03-19T12:37:13+00:00" }, { "name": "laravel/pint", - "version": "v1.27.1", + "version": "v1.29.0", "source": { "type": "git", "url": "https://github.com/laravel/pint.git", - "reference": "54cca2de13790570c7b6f0f94f37896bee4abcb5" + "reference": "bdec963f53172c5e36330f3a400604c69bf02d39" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/pint/zipball/54cca2de13790570c7b6f0f94f37896bee4abcb5", - "reference": "54cca2de13790570c7b6f0f94f37896bee4abcb5", + "url": "https://api.github.com/repos/laravel/pint/zipball/bdec963f53172c5e36330f3a400604c69bf02d39", + "reference": "bdec963f53172c5e36330f3a400604c69bf02d39", "shasum": "" }, "require": { @@ -13735,13 +13833,14 @@ "php": "^8.2.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^3.93.1", - "illuminate/view": "^12.51.0", - "larastan/larastan": "^3.9.2", + "friendsofphp/php-cs-fixer": "^3.94.2", + "illuminate/view": "^12.54.1", + "larastan/larastan": "^3.9.3", "laravel-zero/framework": "^12.0.5", "mockery/mockery": "^1.6.12", - "nunomaduro/termwind": "^2.3.3", - "pestphp/pest": "^3.8.5" + "nunomaduro/termwind": "^2.4.0", + "pestphp/pest": "^3.8.6", + "shipfastlabs/agent-detector": "^1.1.0" }, "bin": [ "builds/pint" @@ -13778,20 +13877,20 @@ "issues": "https://github.com/laravel/pint/issues", "source": "https://github.com/laravel/pint" }, - "time": "2026-02-10T20:00:20+00:00" + "time": "2026-03-12T15:51:39+00:00" }, { "name": "laravel/roster", - "version": "v0.5.0", + "version": "v0.5.1", "source": { "type": "git", "url": "https://github.com/laravel/roster.git", - "reference": "56904a78f4d7360c1c490ced7deeebf9aecb8c0e" + "reference": "5089de7615f72f78e831590ff9d0435fed0102bb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/roster/zipball/56904a78f4d7360c1c490ced7deeebf9aecb8c0e", - "reference": "56904a78f4d7360c1c490ced7deeebf9aecb8c0e", + "url": "https://api.github.com/repos/laravel/roster/zipball/5089de7615f72f78e831590ff9d0435fed0102bb", + "reference": "5089de7615f72f78e831590ff9d0435fed0102bb", "shasum": "" }, "require": { @@ -13839,20 +13938,20 @@ "issues": "https://github.com/laravel/roster/issues", "source": "https://github.com/laravel/roster" }, - "time": "2026-02-17T17:33:35+00:00" + "time": "2026-03-05T07:58:43+00:00" }, { "name": "laravel/telescope", - "version": "5.18.0", + "version": "v5.19.0", "source": { "type": "git", "url": "https://github.com/laravel/telescope.git", - "reference": "8bbc1d839317cef7106cabf028e407416e5a1dad" + "reference": "5e95df170d14e03dd74c4b744969cf01f67a050b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/telescope/zipball/8bbc1d839317cef7106cabf028e407416e5a1dad", - "reference": "8bbc1d839317cef7106cabf028e407416e5a1dad", + "url": "https://api.github.com/repos/laravel/telescope/zipball/5e95df170d14e03dd74c4b744969cf01f67a050b", + "reference": "5e95df170d14e03dd74c4b744969cf01f67a050b", "shasum": "" }, "require": { @@ -13860,8 +13959,8 @@ "laravel/framework": "^8.37|^9.0|^10.0|^11.0|^12.0|^13.0", "laravel/sentinel": "^1.0", "php": "^8.0", - "symfony/console": "^5.3|^6.0|^7.0", - "symfony/var-dumper": "^5.0|^6.0|^7.0" + "symfony/console": "^5.3|^6.0|^7.0|^8.0", + "symfony/var-dumper": "^5.0|^6.0|^7.0|^8.0" }, "require-dev": { "ext-gd": "*", @@ -13906,26 +14005,26 @@ ], "support": { "issues": "https://github.com/laravel/telescope/issues", - "source": "https://github.com/laravel/telescope/tree/5.18.0" + "source": "https://github.com/laravel/telescope/tree/v5.19.0" }, - "time": "2026-02-20T19:55:06+00:00" + "time": "2026-03-24T18:37:14+00:00" }, { "name": "league/uri-components", - "version": "7.8.0", + "version": "7.8.1", "source": { "type": "git", "url": "https://github.com/thephpleague/uri-components.git", - "reference": "8b5ffcebcc0842b76eb80964795bd56a8333b2ba" + "reference": "848ff9db2f0be06229d6034b7c2e33d41b4fd675" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/uri-components/zipball/8b5ffcebcc0842b76eb80964795bd56a8333b2ba", - "reference": "8b5ffcebcc0842b76eb80964795bd56a8333b2ba", + "url": "https://api.github.com/repos/thephpleague/uri-components/zipball/848ff9db2f0be06229d6034b7c2e33d41b4fd675", + "reference": "848ff9db2f0be06229d6034b7c2e33d41b4fd675", "shasum": "" }, "require": { - "league/uri": "^7.8", + "league/uri": "^7.8.1", "php": "^8.1" }, "suggest": { @@ -13984,7 +14083,7 @@ "docs": "https://uri.thephpleague.com", "forum": "https://thephpleague.slack.com", "issues": "https://github.com/thephpleague/uri-src/issues", - "source": "https://github.com/thephpleague/uri-components/tree/7.8.0" + "source": "https://github.com/thephpleague/uri-components/tree/7.8.1" }, "funding": [ { @@ -13992,7 +14091,7 @@ "type": "github" } ], - "time": "2026-01-14T17:24:56+00:00" + "time": "2026-03-15T20:22:25+00:00" }, { "name": "mockery/mockery", @@ -14235,33 +14334,33 @@ }, { "name": "pestphp/pest", - "version": "v4.4.1", + "version": "v4.4.3", "source": { "type": "git", "url": "https://github.com/pestphp/pest.git", - "reference": "f96a1b27864b585b0b29b0ee7331176726f7e54a" + "reference": "e6ab897594312728ef2e32d586cb4f6780b1b495" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pestphp/pest/zipball/f96a1b27864b585b0b29b0ee7331176726f7e54a", - "reference": "f96a1b27864b585b0b29b0ee7331176726f7e54a", + "url": "https://api.github.com/repos/pestphp/pest/zipball/e6ab897594312728ef2e32d586cb4f6780b1b495", + "reference": "e6ab897594312728ef2e32d586cb4f6780b1b495", "shasum": "" }, "require": { - "brianium/paratest": "^7.19.0", - "nunomaduro/collision": "^8.9.0", + "brianium/paratest": "^7.19.2", + "nunomaduro/collision": "^8.9.1", "nunomaduro/termwind": "^2.4.0", "pestphp/pest-plugin": "^4.0.0", "pestphp/pest-plugin-arch": "^4.0.0", "pestphp/pest-plugin-mutate": "^4.0.1", "pestphp/pest-plugin-profanity": "^4.2.1", "php": "^8.3.0", - "phpunit/phpunit": "^12.5.12", + "phpunit/phpunit": "^12.5.14", "symfony/process": "^7.4.5|^8.0.5" }, "conflict": { "filp/whoops": "<2.18.3", - "phpunit/phpunit": ">12.5.12", + "phpunit/phpunit": ">12.5.14", "sebastian/exporter": "<7.0.0", "webmozart/assert": "<1.11.0" }, @@ -14269,7 +14368,7 @@ "pestphp/pest-dev-tools": "^4.1.0", "pestphp/pest-plugin-browser": "^4.3.0", "pestphp/pest-plugin-type-coverage": "^4.0.3", - "psy/psysh": "^0.12.20" + "psy/psysh": "^0.12.21" }, "bin": [ "bin/pest" @@ -14335,7 +14434,7 @@ ], "support": { "issues": "https://github.com/pestphp/pest/issues", - "source": "https://github.com/pestphp/pest/tree/v4.4.1" + "source": "https://github.com/pestphp/pest/tree/v4.4.3" }, "funding": [ { @@ -14347,7 +14446,7 @@ "type": "github" } ], - "time": "2026-02-17T15:27:18+00:00" + "time": "2026-03-21T13:14:39+00:00" }, { "name": "pestphp/pest-plugin", @@ -14964,11 +15063,11 @@ }, { "name": "phpstan/phpstan", - "version": "2.1.40", + "version": "2.1.44", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/9b2c7aeb83a75d8680ea5e7c9b7fca88052b766b", - "reference": "9b2c7aeb83a75d8680ea5e7c9b7fca88052b766b", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/4a88c083c668b2c364a425c9b3171b2d9ea5d218", + "reference": "4a88c083c668b2c364a425c9b3171b2d9ea5d218", "shasum": "" }, "require": { @@ -15013,7 +15112,7 @@ "type": "github" } ], - "time": "2026-02-23T15:04:35+00:00" + "time": "2026-03-25T17:34:21+00:00" }, { "name": "phpunit/php-code-coverage", @@ -15363,16 +15462,16 @@ }, { "name": "phpunit/phpunit", - "version": "12.5.12", + "version": "12.5.14", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "418e06b3b46b0d54bad749ff4907fc7dfb530199" + "reference": "47283cfd98d553edcb1353591f4e255dc1bb61f0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/418e06b3b46b0d54bad749ff4907fc7dfb530199", - "reference": "418e06b3b46b0d54bad749ff4907fc7dfb530199", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/47283cfd98d553edcb1353591f4e255dc1bb61f0", + "reference": "47283cfd98d553edcb1353591f4e255dc1bb61f0", "shasum": "" }, "require": { @@ -15441,7 +15540,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.12" + "source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.14" }, "funding": [ { @@ -15465,25 +15564,25 @@ "type": "tidelift" } ], - "time": "2026-02-16T08:34:36+00:00" + "time": "2026-02-18T12:38:40+00:00" }, { "name": "rector/rector", - "version": "2.3.8", + "version": "2.3.9", "source": { "type": "git", "url": "https://github.com/rectorphp/rector.git", - "reference": "bbd37aedd8df749916cffa2a947cfc4714d1ba2c" + "reference": "917842143fd9f5331a2adefc214b8d7143bd32c4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/rectorphp/rector/zipball/bbd37aedd8df749916cffa2a947cfc4714d1ba2c", - "reference": "bbd37aedd8df749916cffa2a947cfc4714d1ba2c", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/917842143fd9f5331a2adefc214b8d7143bd32c4", + "reference": "917842143fd9f5331a2adefc214b8d7143bd32c4", "shasum": "" }, "require": { "php": "^7.4|^8.0", - "phpstan/phpstan": "^2.1.38" + "phpstan/phpstan": "^2.1.40" }, "conflict": { "rector/rector-doctrine": "*", @@ -15517,7 +15616,7 @@ ], "support": { "issues": "https://github.com/rectorphp/rector/issues", - "source": "https://github.com/rectorphp/rector/tree/2.3.8" + "source": "https://github.com/rectorphp/rector/tree/2.3.9" }, "funding": [ { @@ -15525,7 +15624,7 @@ "type": "github" } ], - "time": "2026-02-22T09:45:50+00:00" + "time": "2026-03-16T09:43:55+00:00" }, { "name": "revolt/event-loop", @@ -15887,16 +15986,16 @@ }, { "name": "sebastian/environment", - "version": "8.0.3", + "version": "8.0.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/environment.git", - "reference": "24a711b5c916efc6d6e62aa65aa2ec98fef77f68" + "reference": "7b8842c2d8e85d0c3a5831236bf5869af6ab2a11" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/24a711b5c916efc6d6e62aa65aa2ec98fef77f68", - "reference": "24a711b5c916efc6d6e62aa65aa2ec98fef77f68", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/7b8842c2d8e85d0c3a5831236bf5869af6ab2a11", + "reference": "7b8842c2d8e85d0c3a5831236bf5869af6ab2a11", "shasum": "" }, "require": { @@ -15939,7 +16038,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/environment/issues", "security": "https://github.com/sebastianbergmann/environment/security/policy", - "source": "https://github.com/sebastianbergmann/environment/tree/8.0.3" + "source": "https://github.com/sebastianbergmann/environment/tree/8.0.4" }, "funding": [ { @@ -15959,7 +16058,7 @@ "type": "tidelift" } ], - "time": "2025-08-12T14:11:56+00:00" + "time": "2026-03-15T07:05:40+00:00" }, { "name": "sebastian/exporter", @@ -16617,26 +16716,26 @@ }, { "name": "spatie/flare-client-php", - "version": "1.10.1", + "version": "1.11.0", "source": { "type": "git", "url": "https://github.com/spatie/flare-client-php.git", - "reference": "bf1716eb98bd689451b071548ae9e70738dce62f" + "reference": "fb3ffb946675dba811fbde9122224db2f84daca9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/flare-client-php/zipball/bf1716eb98bd689451b071548ae9e70738dce62f", - "reference": "bf1716eb98bd689451b071548ae9e70738dce62f", + "url": "https://api.github.com/repos/spatie/flare-client-php/zipball/fb3ffb946675dba811fbde9122224db2f84daca9", + "reference": "fb3ffb946675dba811fbde9122224db2f84daca9", "shasum": "" }, "require": { - "illuminate/pipeline": "^8.0|^9.0|^10.0|^11.0|^12.0", + "illuminate/pipeline": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0", "php": "^8.0", "spatie/backtrace": "^1.6.1", - "symfony/http-foundation": "^5.2|^6.0|^7.0", - "symfony/mime": "^5.2|^6.0|^7.0", - "symfony/process": "^5.2|^6.0|^7.0", - "symfony/var-dumper": "^5.2|^6.0|^7.0" + "symfony/http-foundation": "^5.2|^6.0|^7.0|^8.0", + "symfony/mime": "^5.2|^6.0|^7.0|^8.0", + "symfony/process": "^5.2|^6.0|^7.0|^8.0", + "symfony/var-dumper": "^5.2|^6.0|^7.0|^8.0" }, "require-dev": { "dms/phpunit-arraysubset-asserts": "^0.5.0", @@ -16674,7 +16773,7 @@ ], "support": { "issues": "https://github.com/spatie/flare-client-php/issues", - "source": "https://github.com/spatie/flare-client-php/tree/1.10.1" + "source": "https://github.com/spatie/flare-client-php/tree/1.11.0" }, "funding": [ { @@ -16682,41 +16781,44 @@ "type": "github" } ], - "time": "2025-02-14T13:42:06+00:00" + "time": "2026-03-17T08:06:16+00:00" }, { "name": "spatie/ignition", - "version": "1.15.1", + "version": "1.16.0", "source": { "type": "git", "url": "https://github.com/spatie/ignition.git", - "reference": "31f314153020aee5af3537e507fef892ffbf8c85" + "reference": "b59385bb7aa24dae81bcc15850ebecfda7b40838" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/ignition/zipball/31f314153020aee5af3537e507fef892ffbf8c85", - "reference": "31f314153020aee5af3537e507fef892ffbf8c85", + "url": "https://api.github.com/repos/spatie/ignition/zipball/b59385bb7aa24dae81bcc15850ebecfda7b40838", + "reference": "b59385bb7aa24dae81bcc15850ebecfda7b40838", "shasum": "" }, "require": { "ext-json": "*", "ext-mbstring": "*", "php": "^8.0", - "spatie/error-solutions": "^1.0", - "spatie/flare-client-php": "^1.7", - "symfony/console": "^5.4|^6.0|^7.0", - "symfony/var-dumper": "^5.4|^6.0|^7.0" + "spatie/backtrace": "^1.7.1", + "spatie/error-solutions": "^1.1.2", + "spatie/flare-client-php": "^1.9", + "symfony/console": "^5.4.42|^6.0|^7.0|^8.0", + "symfony/http-foundation": "^5.4.42|^6.0|^7.0|^8.0", + "symfony/mime": "^5.4.42|^6.0|^7.0|^8.0", + "symfony/var-dumper": "^5.4.42|^6.0|^7.0|^8.0" }, "require-dev": { - "illuminate/cache": "^9.52|^10.0|^11.0|^12.0", + "illuminate/cache": "^9.52|^10.0|^11.0|^12.0|^13.0", "mockery/mockery": "^1.4", - "pestphp/pest": "^1.20|^2.0", + "pestphp/pest": "^1.20|^2.0|^3.0", "phpstan/extension-installer": "^1.1", "phpstan/phpstan-deprecation-rules": "^1.0", "phpstan/phpstan-phpunit": "^1.0", "psr/simple-cache-implementation": "*", - "symfony/cache": "^5.4|^6.0|^7.0", - "symfony/process": "^5.4|^6.0|^7.0", + "symfony/cache": "^5.4.38|^6.0|^7.0|^8.0", + "symfony/process": "^5.4.35|^6.0|^7.0|^8.0", "vlucas/phpdotenv": "^5.5" }, "suggest": { @@ -16765,20 +16867,20 @@ "type": "github" } ], - "time": "2025-02-21T14:31:39+00:00" + "time": "2026-03-17T10:51:08+00:00" }, { "name": "spatie/laravel-ignition", - "version": "2.11.0", + "version": "2.12.0", "source": { "type": "git", "url": "https://github.com/spatie/laravel-ignition.git", - "reference": "11f38d1ff7abc583a61c96bf3c1b03610a69cccd" + "reference": "45b3b6e1e73fc161cba2149972698644b99594ee" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/laravel-ignition/zipball/11f38d1ff7abc583a61c96bf3c1b03610a69cccd", - "reference": "11f38d1ff7abc583a61c96bf3c1b03610a69cccd", + "url": "https://api.github.com/repos/spatie/laravel-ignition/zipball/45b3b6e1e73fc161cba2149972698644b99594ee", + "reference": "45b3b6e1e73fc161cba2149972698644b99594ee", "shasum": "" }, "require": { @@ -16788,7 +16890,7 @@ "illuminate/support": "^11.0|^12.0|^13.0", "nesbot/carbon": "^2.72|^3.0", "php": "^8.2", - "spatie/ignition": "^1.15.1", + "spatie/ignition": "^1.16", "symfony/console": "^7.4|^8.0", "symfony/var-dumper": "^7.4|^8.0" }, @@ -16857,7 +16959,7 @@ "type": "github" } ], - "time": "2026-02-22T19:14:05+00:00" + "time": "2026-03-17T12:20:04+00:00" }, { "name": "staabm/side-effects-detector", @@ -16913,16 +17015,16 @@ }, { "name": "symfony/http-client", - "version": "v7.4.6", + "version": "v7.4.7", "source": { "type": "git", "url": "https://github.com/symfony/http-client.git", - "reference": "2bde8afd5ab2fe0b05a9c2d4c3c0e28ceb98a154" + "reference": "1010624285470eb60e88ed10035102c75b4ea6af" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-client/zipball/2bde8afd5ab2fe0b05a9c2d4c3c0e28ceb98a154", - "reference": "2bde8afd5ab2fe0b05a9c2d4c3c0e28ceb98a154", + "url": "https://api.github.com/repos/symfony/http-client/zipball/1010624285470eb60e88ed10035102c75b4ea6af", + "reference": "1010624285470eb60e88ed10035102c75b4ea6af", "shasum": "" }, "require": { @@ -16990,7 +17092,7 @@ "http" ], "support": { - "source": "https://github.com/symfony/http-client/tree/v7.4.6" + "source": "https://github.com/symfony/http-client/tree/v7.4.7" }, "funding": [ { @@ -17010,7 +17112,7 @@ "type": "tidelift" } ], - "time": "2026-02-18T09:46:18+00:00" + "time": "2026-03-05T11:16:58+00:00" }, { "name": "symfony/http-client-contracts", @@ -17209,5 +17311,5 @@ "php": "^8.4" }, "platform-dev": {}, - "plugin-api-version": "2.9.0" + "plugin-api-version": "2.6.0" } diff --git a/config/constants.php b/config/constants.php index 9c6454cae..828493208 100644 --- a/config/constants.php +++ b/config/constants.php @@ -2,7 +2,7 @@ return [ 'coolify' => [ - 'version' => '4.0.0-beta.469', + 'version' => '4.0.0-beta.471', 'helper_version' => '1.0.12', 'realtime_version' => '1.0.11', 'self_hosted' => env('SELF_HOSTED', true), @@ -55,6 +55,10 @@ 'is_scheduler_enabled' => env('SCHEDULER_ENABLED', true), ], + 'nightwatch' => [ + 'is_nightwatch_enabled' => env('NIGHTWATCH_ENABLED', false), + ], + 'docker' => [ 'minimum_required_version' => '24.0', ], diff --git a/config/logging.php b/config/logging.php index 1a75978f3..1dbb1135f 100644 --- a/config/logging.php +++ b/config/logging.php @@ -123,7 +123,7 @@ 'driver' => 'daily', 'path' => storage_path('logs/scheduled.log'), 'level' => 'debug', - 'days' => 1, + 'days' => 7, ], 'scheduled-errors' => [ diff --git a/config/purify.php b/config/purify.php index 66dbbb568..a5dcabb92 100644 --- a/config/purify.php +++ b/config/purify.php @@ -49,6 +49,17 @@ 'AutoFormat.RemoveEmpty' => false, ], + 'validation_logs' => [ + 'Core.Encoding' => 'utf-8', + 'HTML.Doctype' => 'HTML 4.01 Transitional', + 'HTML.Allowed' => 'a[href|title|target|class],br,div[class],pre[class],span[class],p[class]', + 'HTML.ForbiddenElements' => '', + 'CSS.AllowedProperties' => '', + 'AutoFormat.AutoParagraph' => false, + 'AutoFormat.RemoveEmpty' => false, + 'Attr.AllowedFrameTargets' => ['_blank'], + ], + ], /* diff --git a/database/migrations/2026_03_23_101720_add_uuid_to_local_persistent_volumes_table.php b/database/migrations/2026_03_23_101720_add_uuid_to_local_persistent_volumes_table.php new file mode 100644 index 000000000..6b4fb690d --- /dev/null +++ b/database/migrations/2026_03_23_101720_add_uuid_to_local_persistent_volumes_table.php @@ -0,0 +1,39 @@ +string('uuid')->nullable()->after('id'); + }); + + DB::table('local_persistent_volumes') + ->whereNull('uuid') + ->orderBy('id') + ->chunk(1000, function ($volumes) { + foreach ($volumes as $volume) { + DB::table('local_persistent_volumes') + ->where('id', $volume->id) + ->update(['uuid' => (string) new Cuid2]); + } + }); + + Schema::table('local_persistent_volumes', function (Blueprint $table) { + $table->string('uuid')->nullable(false)->unique()->change(); + }); + } + + public function down(): void + { + Schema::table('local_persistent_volumes', function (Blueprint $table) { + $table->dropColumn('uuid'); + }); + } +}; diff --git a/docker/development/etc/s6-overlay/s6-rc.d/horizon/run b/docker/development/etc/s6-overlay/s6-rc.d/horizon/run index ada19b3a3..dbc472d06 100644 --- a/docker/development/etc/s6-overlay/s6-rc.d/horizon/run +++ b/docker/development/etc/s6-overlay/s6-rc.d/horizon/run @@ -1,12 +1,11 @@ -#!/command/execlineb -P +#!/bin/sh -# Use with-contenv to ensure environment variables are available -with-contenv cd /var/www/html -foreground { - php - artisan - start:horizon -} +if grep -qE '^HORIZON_ENABLED=false' .env 2>/dev/null; then + echo " INFO Horizon is disabled, sleeping." + exec sleep infinity +fi +echo " INFO Horizon is enabled, starting..." +exec php artisan horizon diff --git a/docker/development/etc/s6-overlay/s6-rc.d/nightwatch-agent/dependencies.d/init-setup b/docker/development/etc/s6-overlay/s6-rc.d/nightwatch-agent/dependencies.d/init-setup new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/docker/development/etc/s6-overlay/s6-rc.d/nightwatch-agent/dependencies.d/init-setup @@ -0,0 +1 @@ + diff --git a/docker/development/etc/s6-overlay/s6-rc.d/nightwatch-agent/run b/docker/development/etc/s6-overlay/s6-rc.d/nightwatch-agent/run new file mode 100644 index 000000000..ee46dba7e --- /dev/null +++ b/docker/development/etc/s6-overlay/s6-rc.d/nightwatch-agent/run @@ -0,0 +1,11 @@ +#!/bin/sh + +cd /var/www/html + +if grep -qE '^NIGHTWATCH_ENABLED=true' .env 2>/dev/null; then + echo " INFO Nightwatch is enabled, starting..." + exec php artisan nightwatch:agent +fi + +echo " INFO Nightwatch is disabled, sleeping." +exec sleep infinity diff --git a/docker/development/etc/s6-overlay/s6-rc.d/nightwatch-agent/type b/docker/development/etc/s6-overlay/s6-rc.d/nightwatch-agent/type new file mode 100644 index 000000000..5883cff0c --- /dev/null +++ b/docker/development/etc/s6-overlay/s6-rc.d/nightwatch-agent/type @@ -0,0 +1 @@ +longrun diff --git a/docker/development/etc/s6-overlay/s6-rc.d/scheduler-worker/run b/docker/development/etc/s6-overlay/s6-rc.d/scheduler-worker/run index b81a44833..bfa44c7e3 100644 --- a/docker/development/etc/s6-overlay/s6-rc.d/scheduler-worker/run +++ b/docker/development/etc/s6-overlay/s6-rc.d/scheduler-worker/run @@ -1,13 +1,11 @@ -#!/command/execlineb -P +#!/bin/sh -# Use with-contenv to ensure environment variables are available -with-contenv cd /var/www/html -foreground { - php - artisan - start:scheduler -} - +if grep -qE '^SCHEDULER_ENABLED=false' .env 2>/dev/null; then + echo " INFO Scheduler is disabled, sleeping." + exec sleep infinity +fi +echo " INFO Scheduler is enabled, starting..." +exec php artisan schedule:work diff --git a/docker/development/etc/s6-overlay/s6-rc.d/user/contents.d/nightwatch-agent b/docker/development/etc/s6-overlay/s6-rc.d/user/contents.d/nightwatch-agent new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/docker/development/etc/s6-overlay/s6-rc.d/user/contents.d/nightwatch-agent @@ -0,0 +1 @@ + diff --git a/docker/production/etc/s6-overlay/s6-rc.d/horizon/run b/docker/production/etc/s6-overlay/s6-rc.d/horizon/run index be6647607..dbc472d06 100644 --- a/docker/production/etc/s6-overlay/s6-rc.d/horizon/run +++ b/docker/production/etc/s6-overlay/s6-rc.d/horizon/run @@ -1,11 +1,11 @@ -#!/command/execlineb -P +#!/bin/sh -# Use with-contenv to ensure environment variables are available -with-contenv cd /var/www/html -foreground { - php - artisan - start:horizon -} +if grep -qE '^HORIZON_ENABLED=false' .env 2>/dev/null; then + echo " INFO Horizon is disabled, sleeping." + exec sleep infinity +fi + +echo " INFO Horizon is enabled, starting..." +exec php artisan horizon diff --git a/docker/production/etc/s6-overlay/s6-rc.d/nightwatch-agent/dependencies.d/init-script b/docker/production/etc/s6-overlay/s6-rc.d/nightwatch-agent/dependencies.d/init-script new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/docker/production/etc/s6-overlay/s6-rc.d/nightwatch-agent/dependencies.d/init-script @@ -0,0 +1 @@ + diff --git a/docker/production/etc/s6-overlay/s6-rc.d/nightwatch-agent/run b/docker/production/etc/s6-overlay/s6-rc.d/nightwatch-agent/run new file mode 100644 index 000000000..ee46dba7e --- /dev/null +++ b/docker/production/etc/s6-overlay/s6-rc.d/nightwatch-agent/run @@ -0,0 +1,11 @@ +#!/bin/sh + +cd /var/www/html + +if grep -qE '^NIGHTWATCH_ENABLED=true' .env 2>/dev/null; then + echo " INFO Nightwatch is enabled, starting..." + exec php artisan nightwatch:agent +fi + +echo " INFO Nightwatch is disabled, sleeping." +exec sleep infinity diff --git a/docker/production/etc/s6-overlay/s6-rc.d/nightwatch-agent/type b/docker/production/etc/s6-overlay/s6-rc.d/nightwatch-agent/type new file mode 100644 index 000000000..5883cff0c --- /dev/null +++ b/docker/production/etc/s6-overlay/s6-rc.d/nightwatch-agent/type @@ -0,0 +1 @@ +longrun diff --git a/docker/production/etc/s6-overlay/s6-rc.d/scheduler-worker/run b/docker/production/etc/s6-overlay/s6-rc.d/scheduler-worker/run index a2ecb0a73..bfa44c7e3 100644 --- a/docker/production/etc/s6-overlay/s6-rc.d/scheduler-worker/run +++ b/docker/production/etc/s6-overlay/s6-rc.d/scheduler-worker/run @@ -1,10 +1,11 @@ -#!/command/execlineb -P +#!/bin/sh -# Use with-contenv to ensure environment variables are available -with-contenv cd /var/www/html -foreground { - php - artisan - start:scheduler -} + +if grep -qE '^SCHEDULER_ENABLED=false' .env 2>/dev/null; then + echo " INFO Scheduler is disabled, sleeping." + exec sleep infinity +fi + +echo " INFO Scheduler is enabled, starting..." +exec php artisan schedule:work diff --git a/docker/production/etc/s6-overlay/s6-rc.d/user/contents.d/nightwatch-agent b/docker/production/etc/s6-overlay/s6-rc.d/user/contents.d/nightwatch-agent new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/docker/production/etc/s6-overlay/s6-rc.d/user/contents.d/nightwatch-agent @@ -0,0 +1 @@ + diff --git a/openapi.json b/openapi.json index d119176a1..aec5a2843 100644 --- a/openapi.json +++ b/openapi.json @@ -3502,6 +3502,105 @@ } ] }, + "post": { + "tags": [ + "Applications" + ], + "summary": "Create Storage", + "description": "Create a persistent storage or file storage for an application.", + "operationId": "create-storage-by-application-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the application.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application\/json": { + "schema": { + "required": [ + "type", + "mount_path" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "persistent", + "file" + ], + "description": "The type of storage." + }, + "name": { + "type": "string", + "description": "Volume name (persistent only, required for persistent)." + }, + "mount_path": { + "type": "string", + "description": "The container mount path." + }, + "host_path": { + "type": "string", + "nullable": true, + "description": "The host path (persistent only, optional)." + }, + "content": { + "type": "string", + "nullable": true, + "description": "File content (file only, optional)." + }, + "is_directory": { + "type": "boolean", + "description": "Whether this is a directory mount (file only, default false)." + }, + "fs_path": { + "type": "string", + "description": "Host directory path (required when is_directory is true)." + } + }, + "type": "object", + "additionalProperties": false + } + } + } + }, + "responses": { + "201": { + "description": "Storage created.", + "content": { + "application\/json": { + "schema": { + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + }, + "422": { + "$ref": "#\/components\/responses\/422" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, "patch": { "tags": [ "Applications" @@ -3527,13 +3626,16 @@ "application\/json": { "schema": { "required": [ - "id", "type" ], "properties": { + "uuid": { + "type": "string", + "description": "The UUID of the storage (preferred)." + }, "id": { "type": "integer", - "description": "The ID of the storage." + "description": "The ID of the storage (deprecated, use uuid instead)." }, "type": { "type": "string", @@ -3603,6 +3705,70 @@ ] } }, + "\/applications\/{uuid}\/storages\/{storage_uuid}": { + "delete": { + "tags": [ + "Applications" + ], + "summary": "Delete Storage", + "description": "Delete a persistent storage or file storage by application UUID.", + "operationId": "delete-storage-by-application-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the application.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "storage_uuid", + "in": "path", + "description": "UUID of the storage.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Storage deleted.", + "content": { + "application\/json": { + "schema": { + "properties": { + "message": { + "type": "string" + } + }, + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + }, + "422": { + "$ref": "#\/components\/responses\/422" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "\/cloud-tokens": { "get": { "tags": [ @@ -6513,6 +6679,333 @@ ] } }, + "\/databases\/{uuid}\/storages": { + "get": { + "tags": [ + "Databases" + ], + "summary": "List Storages", + "description": "List all persistent storages and file storages by database UUID.", + "operationId": "list-storages-by-database-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the database.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "All storages by database UUID.", + "content": { + "application\/json": { + "schema": { + "properties": { + "persistent_storages": { + "type": "array", + "items": { + "type": "object" + } + }, + "file_storages": { + "type": "array", + "items": { + "type": "object" + } + } + }, + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, + "post": { + "tags": [ + "Databases" + ], + "summary": "Create Storage", + "description": "Create a persistent storage or file storage for a database.", + "operationId": "create-storage-by-database-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the database.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application\/json": { + "schema": { + "required": [ + "type", + "mount_path" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "persistent", + "file" + ], + "description": "The type of storage." + }, + "name": { + "type": "string", + "description": "Volume name (persistent only, required for persistent)." + }, + "mount_path": { + "type": "string", + "description": "The container mount path." + }, + "host_path": { + "type": "string", + "nullable": true, + "description": "The host path (persistent only, optional)." + }, + "content": { + "type": "string", + "nullable": true, + "description": "File content (file only, optional)." + }, + "is_directory": { + "type": "boolean", + "description": "Whether this is a directory mount (file only, default false)." + }, + "fs_path": { + "type": "string", + "description": "Host directory path (required when is_directory is true)." + } + }, + "type": "object", + "additionalProperties": false + } + } + } + }, + "responses": { + "201": { + "description": "Storage created.", + "content": { + "application\/json": { + "schema": { + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + }, + "422": { + "$ref": "#\/components\/responses\/422" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, + "patch": { + "tags": [ + "Databases" + ], + "summary": "Update Storage", + "description": "Update a persistent storage or file storage by database UUID.", + "operationId": "update-storage-by-database-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the database.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "Storage updated. For read-only storages (from docker-compose or services), only is_preview_suffix_enabled can be updated.", + "required": true, + "content": { + "application\/json": { + "schema": { + "required": [ + "type" + ], + "properties": { + "uuid": { + "type": "string", + "description": "The UUID of the storage (preferred)." + }, + "id": { + "type": "integer", + "description": "The ID of the storage (deprecated, use uuid instead)." + }, + "type": { + "type": "string", + "enum": [ + "persistent", + "file" + ], + "description": "The type of storage: persistent or file." + }, + "is_preview_suffix_enabled": { + "type": "boolean", + "description": "Whether to add -pr-N suffix for preview deployments." + }, + "name": { + "type": "string", + "description": "The volume name (persistent only, not allowed for read-only storages)." + }, + "mount_path": { + "type": "string", + "description": "The container mount path (not allowed for read-only storages)." + }, + "host_path": { + "type": "string", + "nullable": true, + "description": "The host path (persistent only, not allowed for read-only storages)." + }, + "content": { + "type": "string", + "nullable": true, + "description": "The file content (file only, not allowed for read-only storages)." + } + }, + "type": "object", + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Storage updated.", + "content": { + "application\/json": { + "schema": { + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + }, + "422": { + "$ref": "#\/components\/responses\/422" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "\/databases\/{uuid}\/storages\/{storage_uuid}": { + "delete": { + "tags": [ + "Databases" + ], + "summary": "Delete Storage", + "description": "Delete a persistent storage or file storage by database UUID.", + "operationId": "delete-storage-by-database-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the database.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "storage_uuid", + "in": "path", + "description": "UUID of the storage.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Storage deleted.", + "content": { + "application\/json": { + "schema": { + "properties": { + "message": { + "type": "string" + } + }, + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + }, + "422": { + "$ref": "#\/components\/responses\/422" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "\/deployments": { "get": { "tags": [ @@ -11238,6 +11731,338 @@ ] } }, + "\/services\/{uuid}\/storages": { + "get": { + "tags": [ + "Services" + ], + "summary": "List Storages", + "description": "List all persistent storages and file storages by service UUID.", + "operationId": "list-storages-by-service-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the service.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "All storages by service UUID.", + "content": { + "application\/json": { + "schema": { + "properties": { + "persistent_storages": { + "type": "array", + "items": { + "type": "object" + } + }, + "file_storages": { + "type": "array", + "items": { + "type": "object" + } + } + }, + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, + "post": { + "tags": [ + "Services" + ], + "summary": "Create Storage", + "description": "Create a persistent storage or file storage for a service sub-resource.", + "operationId": "create-storage-by-service-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the service.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application\/json": { + "schema": { + "required": [ + "type", + "mount_path", + "resource_uuid" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "persistent", + "file" + ], + "description": "The type of storage." + }, + "resource_uuid": { + "type": "string", + "description": "UUID of the service application or database sub-resource." + }, + "name": { + "type": "string", + "description": "Volume name (persistent only, required for persistent)." + }, + "mount_path": { + "type": "string", + "description": "The container mount path." + }, + "host_path": { + "type": "string", + "nullable": true, + "description": "The host path (persistent only, optional)." + }, + "content": { + "type": "string", + "nullable": true, + "description": "File content (file only, optional)." + }, + "is_directory": { + "type": "boolean", + "description": "Whether this is a directory mount (file only, default false)." + }, + "fs_path": { + "type": "string", + "description": "Host directory path (required when is_directory is true)." + } + }, + "type": "object", + "additionalProperties": false + } + } + } + }, + "responses": { + "201": { + "description": "Storage created.", + "content": { + "application\/json": { + "schema": { + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + }, + "422": { + "$ref": "#\/components\/responses\/422" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, + "patch": { + "tags": [ + "Services" + ], + "summary": "Update Storage", + "description": "Update a persistent storage or file storage by service UUID.", + "operationId": "update-storage-by-service-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the service.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "Storage updated. For read-only storages (from docker-compose or services), only is_preview_suffix_enabled can be updated.", + "required": true, + "content": { + "application\/json": { + "schema": { + "required": [ + "type" + ], + "properties": { + "uuid": { + "type": "string", + "description": "The UUID of the storage (preferred)." + }, + "id": { + "type": "integer", + "description": "The ID of the storage (deprecated, use uuid instead)." + }, + "type": { + "type": "string", + "enum": [ + "persistent", + "file" + ], + "description": "The type of storage: persistent or file." + }, + "is_preview_suffix_enabled": { + "type": "boolean", + "description": "Whether to add -pr-N suffix for preview deployments." + }, + "name": { + "type": "string", + "description": "The volume name (persistent only, not allowed for read-only storages)." + }, + "mount_path": { + "type": "string", + "description": "The container mount path (not allowed for read-only storages)." + }, + "host_path": { + "type": "string", + "nullable": true, + "description": "The host path (persistent only, not allowed for read-only storages)." + }, + "content": { + "type": "string", + "nullable": true, + "description": "The file content (file only, not allowed for read-only storages)." + } + }, + "type": "object", + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Storage updated.", + "content": { + "application\/json": { + "schema": { + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + }, + "422": { + "$ref": "#\/components\/responses\/422" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "\/services\/{uuid}\/storages\/{storage_uuid}": { + "delete": { + "tags": [ + "Services" + ], + "summary": "Delete Storage", + "description": "Delete a persistent storage or file storage by service UUID.", + "operationId": "delete-storage-by-service-uuid", + "parameters": [ + { + "name": "uuid", + "in": "path", + "description": "UUID of the service.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "storage_uuid", + "in": "path", + "description": "UUID of the storage.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Storage deleted.", + "content": { + "application\/json": { + "schema": { + "properties": { + "message": { + "type": "string" + } + }, + "type": "object" + } + } + } + }, + "401": { + "$ref": "#\/components\/responses\/401" + }, + "400": { + "$ref": "#\/components\/responses\/400" + }, + "404": { + "$ref": "#\/components\/responses\/404" + }, + "422": { + "$ref": "#\/components\/responses\/422" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "\/teams": { "get": { "tags": [ diff --git a/openapi.yaml b/openapi.yaml index 7064be28a..93038ce80 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -2204,6 +2204,73 @@ paths: security: - bearerAuth: [] + post: + tags: + - Applications + summary: 'Create Storage' + description: 'Create a persistent storage or file storage for an application.' + operationId: create-storage-by-application-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the application.' + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + required: + - type + - mount_path + properties: + type: + type: string + enum: [persistent, file] + description: 'The type of storage.' + name: + type: string + description: 'Volume name (persistent only, required for persistent).' + mount_path: + type: string + description: 'The container mount path.' + host_path: + type: string + nullable: true + description: 'The host path (persistent only, optional).' + content: + type: string + nullable: true + description: 'File content (file only, optional).' + is_directory: + type: boolean + description: 'Whether this is a directory mount (file only, default false).' + fs_path: + type: string + description: 'Host directory path (required when is_directory is true).' + type: object + additionalProperties: false + responses: + '201': + description: 'Storage created.' + content: + application/json: + schema: + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + '422': + $ref: '#/components/responses/422' + security: + - + bearerAuth: [] patch: tags: - Applications @@ -2225,12 +2292,14 @@ paths: application/json: schema: required: - - id - type properties: + uuid: + type: string + description: 'The UUID of the storage (preferred).' id: type: integer - description: 'The ID of the storage.' + description: 'The ID of the storage (deprecated, use uuid instead).' type: type: string enum: [persistent, file] @@ -2272,6 +2341,48 @@ paths: security: - bearerAuth: [] + '/applications/{uuid}/storages/{storage_uuid}': + delete: + tags: + - Applications + summary: 'Delete Storage' + description: 'Delete a persistent storage or file storage by application UUID.' + operationId: delete-storage-by-application-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the application.' + required: true + schema: + type: string + - + name: storage_uuid + in: path + description: 'UUID of the storage.' + required: true + schema: + type: string + responses: + '200': + description: 'Storage deleted.' + content: + application/json: + schema: + properties: + message: { type: string } + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + '422': + $ref: '#/components/responses/422' + security: + - + bearerAuth: [] /cloud-tokens: get: tags: @@ -4209,6 +4320,219 @@ paths: security: - bearerAuth: [] + '/databases/{uuid}/storages': + get: + tags: + - Databases + summary: 'List Storages' + description: 'List all persistent storages and file storages by database UUID.' + operationId: list-storages-by-database-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the database.' + required: true + schema: + type: string + responses: + '200': + description: 'All storages by database UUID.' + content: + application/json: + schema: + properties: + persistent_storages: { type: array, items: { type: object } } + file_storages: { type: array, items: { type: object } } + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + security: + - + bearerAuth: [] + post: + tags: + - Databases + summary: 'Create Storage' + description: 'Create a persistent storage or file storage for a database.' + operationId: create-storage-by-database-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the database.' + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + required: + - type + - mount_path + properties: + type: + type: string + enum: [persistent, file] + description: 'The type of storage.' + name: + type: string + description: 'Volume name (persistent only, required for persistent).' + mount_path: + type: string + description: 'The container mount path.' + host_path: + type: string + nullable: true + description: 'The host path (persistent only, optional).' + content: + type: string + nullable: true + description: 'File content (file only, optional).' + is_directory: + type: boolean + description: 'Whether this is a directory mount (file only, default false).' + fs_path: + type: string + description: 'Host directory path (required when is_directory is true).' + type: object + additionalProperties: false + responses: + '201': + description: 'Storage created.' + content: + application/json: + schema: + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + '422': + $ref: '#/components/responses/422' + security: + - + bearerAuth: [] + patch: + tags: + - Databases + summary: 'Update Storage' + description: 'Update a persistent storage or file storage by database UUID.' + operationId: update-storage-by-database-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the database.' + required: true + schema: + type: string + requestBody: + description: 'Storage updated. For read-only storages (from docker-compose or services), only is_preview_suffix_enabled can be updated.' + required: true + content: + application/json: + schema: + required: + - type + properties: + uuid: + type: string + description: 'The UUID of the storage (preferred).' + id: + type: integer + description: 'The ID of the storage (deprecated, use uuid instead).' + type: + type: string + enum: [persistent, file] + description: 'The type of storage: persistent or file.' + is_preview_suffix_enabled: + type: boolean + description: 'Whether to add -pr-N suffix for preview deployments.' + name: + type: string + description: 'The volume name (persistent only, not allowed for read-only storages).' + mount_path: + type: string + description: 'The container mount path (not allowed for read-only storages).' + host_path: + type: string + nullable: true + description: 'The host path (persistent only, not allowed for read-only storages).' + content: + type: string + nullable: true + description: 'The file content (file only, not allowed for read-only storages).' + type: object + additionalProperties: false + responses: + '200': + description: 'Storage updated.' + content: + application/json: + schema: + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + '422': + $ref: '#/components/responses/422' + security: + - + bearerAuth: [] + '/databases/{uuid}/storages/{storage_uuid}': + delete: + tags: + - Databases + summary: 'Delete Storage' + description: 'Delete a persistent storage or file storage by database UUID.' + operationId: delete-storage-by-database-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the database.' + required: true + schema: + type: string + - + name: storage_uuid + in: path + description: 'UUID of the storage.' + required: true + schema: + type: string + responses: + '200': + description: 'Storage deleted.' + content: + application/json: + schema: + properties: + message: { type: string } + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + '422': + $ref: '#/components/responses/422' + security: + - + bearerAuth: [] /deployments: get: tags: @@ -7070,6 +7394,223 @@ paths: security: - bearerAuth: [] + '/services/{uuid}/storages': + get: + tags: + - Services + summary: 'List Storages' + description: 'List all persistent storages and file storages by service UUID.' + operationId: list-storages-by-service-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the service.' + required: true + schema: + type: string + responses: + '200': + description: 'All storages by service UUID.' + content: + application/json: + schema: + properties: + persistent_storages: { type: array, items: { type: object } } + file_storages: { type: array, items: { type: object } } + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + security: + - + bearerAuth: [] + post: + tags: + - Services + summary: 'Create Storage' + description: 'Create a persistent storage or file storage for a service sub-resource.' + operationId: create-storage-by-service-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the service.' + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + required: + - type + - mount_path + - resource_uuid + properties: + type: + type: string + enum: [persistent, file] + description: 'The type of storage.' + resource_uuid: + type: string + description: 'UUID of the service application or database sub-resource.' + name: + type: string + description: 'Volume name (persistent only, required for persistent).' + mount_path: + type: string + description: 'The container mount path.' + host_path: + type: string + nullable: true + description: 'The host path (persistent only, optional).' + content: + type: string + nullable: true + description: 'File content (file only, optional).' + is_directory: + type: boolean + description: 'Whether this is a directory mount (file only, default false).' + fs_path: + type: string + description: 'Host directory path (required when is_directory is true).' + type: object + additionalProperties: false + responses: + '201': + description: 'Storage created.' + content: + application/json: + schema: + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + '422': + $ref: '#/components/responses/422' + security: + - + bearerAuth: [] + patch: + tags: + - Services + summary: 'Update Storage' + description: 'Update a persistent storage or file storage by service UUID.' + operationId: update-storage-by-service-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the service.' + required: true + schema: + type: string + requestBody: + description: 'Storage updated. For read-only storages (from docker-compose or services), only is_preview_suffix_enabled can be updated.' + required: true + content: + application/json: + schema: + required: + - type + properties: + uuid: + type: string + description: 'The UUID of the storage (preferred).' + id: + type: integer + description: 'The ID of the storage (deprecated, use uuid instead).' + type: + type: string + enum: [persistent, file] + description: 'The type of storage: persistent or file.' + is_preview_suffix_enabled: + type: boolean + description: 'Whether to add -pr-N suffix for preview deployments.' + name: + type: string + description: 'The volume name (persistent only, not allowed for read-only storages).' + mount_path: + type: string + description: 'The container mount path (not allowed for read-only storages).' + host_path: + type: string + nullable: true + description: 'The host path (persistent only, not allowed for read-only storages).' + content: + type: string + nullable: true + description: 'The file content (file only, not allowed for read-only storages).' + type: object + additionalProperties: false + responses: + '200': + description: 'Storage updated.' + content: + application/json: + schema: + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + '422': + $ref: '#/components/responses/422' + security: + - + bearerAuth: [] + '/services/{uuid}/storages/{storage_uuid}': + delete: + tags: + - Services + summary: 'Delete Storage' + description: 'Delete a persistent storage or file storage by service UUID.' + operationId: delete-storage-by-service-uuid + parameters: + - + name: uuid + in: path + description: 'UUID of the service.' + required: true + schema: + type: string + - + name: storage_uuid + in: path + description: 'UUID of the storage.' + required: true + schema: + type: string + responses: + '200': + description: 'Storage deleted.' + content: + application/json: + schema: + properties: + message: { type: string } + type: object + '401': + $ref: '#/components/responses/401' + '400': + $ref: '#/components/responses/400' + '404': + $ref: '#/components/responses/404' + '422': + $ref: '#/components/responses/422' + security: + - + bearerAuth: [] /teams: get: tags: diff --git a/other/nightly/docker-compose.prod.yml b/other/nightly/docker-compose.prod.yml index d42047245..0bd4ae2dd 100644 --- a/other/nightly/docker-compose.prod.yml +++ b/other/nightly/docker-compose.prod.yml @@ -60,7 +60,7 @@ services: retries: 10 timeout: 2s soketi: - image: '${REGISTRY_URL:-ghcr.io}/coollabsio/coolify-realtime:1.0.10' + image: '${REGISTRY_URL:-ghcr.io}/coollabsio/coolify-realtime:1.0.11' ports: - "${SOKETI_PORT:-6001}:6001" - "6002:6002" diff --git a/other/nightly/docker-compose.windows.yml b/other/nightly/docker-compose.windows.yml index bf1f94af0..ca233356a 100644 --- a/other/nightly/docker-compose.windows.yml +++ b/other/nightly/docker-compose.windows.yml @@ -79,7 +79,7 @@ services: retries: 10 timeout: 2s redis: - image: redis:alpine + image: redis:7-alpine pull_policy: always container_name: coolify-redis restart: always diff --git a/other/nightly/docker-compose.yml b/other/nightly/docker-compose.yml index 68d0f0744..0fd3dda07 100644 --- a/other/nightly/docker-compose.yml +++ b/other/nightly/docker-compose.yml @@ -4,7 +4,7 @@ services: restart: always working_dir: /var/www/html extra_hosts: - - 'host.docker.internal:host-gateway' + - host.docker.internal:host-gateway networks: - coolify depends_on: @@ -18,7 +18,7 @@ services: networks: - coolify redis: - image: redis:alpine + image: redis:7-alpine container_name: coolify-redis restart: always networks: @@ -26,7 +26,7 @@ services: soketi: container_name: coolify-realtime extra_hosts: - - 'host.docker.internal:host-gateway' + - host.docker.internal:host-gateway restart: always networks: - coolify diff --git a/other/nightly/install.sh b/other/nightly/install.sh index 921ba6a92..09406118c 100755 --- a/other/nightly/install.sh +++ b/other/nightly/install.sh @@ -20,7 +20,7 @@ DATE=$(date +"%Y%m%d-%H%M%S") OS_TYPE=$(grep -w "ID" /etc/os-release | cut -d "=" -f 2 | tr -d '"') ENV_FILE="/data/coolify/source/.env" -DOCKER_VERSION="27.0" +DOCKER_VERSION="latest" # TODO: Ask for a user CURRENT_USER=$USER @@ -499,13 +499,10 @@ fi install_docker() { set +e - curl -s https://releases.rancher.com/install-docker/${DOCKER_VERSION}.sh | sh 2>&1 || true + curl -fsSL https://get.docker.com | sh 2>&1 || true if ! [ -x "$(command -v docker)" ]; then - curl -s https://get.docker.com | sh -s -- --version ${DOCKER_VERSION} 2>&1 - if ! [ -x "$(command -v docker)" ]; then - echo "Automated Docker installation failed. Trying manual installation." - install_docker_manually - fi + echo "Automated Docker installation failed. Trying manual installation." + install_docker_manually fi set -e } @@ -548,16 +545,6 @@ if ! [ -x "$(command -v docker)" ]; then echo " - Docker is not installed. Installing Docker. It may take a while." getAJoke case "$OS_TYPE" in - "almalinux") - dnf config-manager --add-repo=https://download.docker.com/linux/centos/docker-ce.repo >/dev/null 2>&1 - dnf install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin >/dev/null 2>&1 - if ! [ -x "$(command -v docker)" ]; then - echo " - Docker could not be installed automatically. Please visit https://docs.docker.com/engine/install/ and install Docker manually to continue." - exit 1 - fi - systemctl start docker >/dev/null 2>&1 - systemctl enable docker >/dev/null 2>&1 - ;; "alpine" | "postmarketos") apk add docker docker-cli-compose >/dev/null 2>&1 rc-update add docker default >/dev/null 2>&1 @@ -569,8 +556,9 @@ if ! [ -x "$(command -v docker)" ]; then fi ;; "arch") - pacman -Sy docker docker-compose --noconfirm >/dev/null 2>&1 + pacman -Syu --noconfirm --needed docker docker-compose >/dev/null 2>&1 systemctl enable docker.service >/dev/null 2>&1 + systemctl start docker.service >/dev/null 2>&1 if ! [ -x "$(command -v docker)" ]; then echo " - Failed to install Docker with pacman. Try to install it manually." echo " Please visit https://wiki.archlinux.org/title/docker for more information." @@ -581,7 +569,7 @@ if ! [ -x "$(command -v docker)" ]; then dnf install docker -y >/dev/null 2>&1 DOCKER_CONFIG=${DOCKER_CONFIG:-/usr/local/lib/docker} mkdir -p $DOCKER_CONFIG/cli-plugins >/dev/null 2>&1 - curl -sL "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o $DOCKER_CONFIG/cli-plugins/docker-compose >/dev/null 2>&1 + curl -fsSL "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o $DOCKER_CONFIG/cli-plugins/docker-compose >/dev/null 2>&1 chmod +x $DOCKER_CONFIG/cli-plugins/docker-compose >/dev/null 2>&1 systemctl start docker >/dev/null 2>&1 systemctl enable docker >/dev/null 2>&1 @@ -591,34 +579,28 @@ if ! [ -x "$(command -v docker)" ]; then exit 1 fi ;; - "centos" | "fedora" | "rhel" | "tencentos") - if [ -x "$(command -v dnf5)" ]; then - # dnf5 is available - dnf config-manager addrepo --from-repofile=https://download.docker.com/linux/$OS_TYPE/docker-ce.repo --overwrite >/dev/null 2>&1 - else - # dnf5 is not available, use dnf - dnf config-manager --add-repo=https://download.docker.com/linux/$OS_TYPE/docker-ce.repo >/dev/null 2>&1 - fi + "almalinux" | "tencentos") + dnf config-manager --add-repo=https://download.docker.com/linux/centos/docker-ce.repo >/dev/null 2>&1 dnf install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin >/dev/null 2>&1 + systemctl start docker >/dev/null 2>&1 + systemctl enable docker >/dev/null 2>&1 if ! [ -x "$(command -v docker)" ]; then echo " - Docker could not be installed automatically. Please visit https://docs.docker.com/engine/install/ and install Docker manually to continue." exit 1 fi - systemctl start docker >/dev/null 2>&1 - systemctl enable docker >/dev/null 2>&1 ;; - "ubuntu" | "debian" | "raspbian") + "ubuntu" | "debian" | "raspbian" | "centos" | "fedora" | "rhel" | "sles") install_docker if ! [ -x "$(command -v docker)" ]; then - echo " - Automated Docker installation failed. Trying manual installation." - install_docker_manually + echo " - Docker could not be installed automatically. Please visit https://docs.docker.com/engine/install/ and install Docker manually to continue." + exit 1 fi ;; *) install_docker if ! [ -x "$(command -v docker)" ]; then - echo " - Automated Docker installation failed. Trying manual installation." - install_docker_manually + echo " - Docker could not be installed automatically. Please visit https://docs.docker.com/engine/install/ and install Docker manually to continue." + exit 1 fi ;; esac @@ -627,6 +609,19 @@ else echo " - Docker is installed." fi +# Verify minimum Docker version +MIN_DOCKER_VERSION=24 +INSTALLED_DOCKER_VERSION=$(docker version --format '{{.Server.Version}}' 2>/dev/null | cut -d. -f1) +if [ -z "$INSTALLED_DOCKER_VERSION" ]; then + echo " - WARNING: Could not determine Docker version. Please ensure Docker $MIN_DOCKER_VERSION+ is installed." +elif [ "$INSTALLED_DOCKER_VERSION" -lt "$MIN_DOCKER_VERSION" ]; then + echo " - ERROR: Docker version $INSTALLED_DOCKER_VERSION is too old. Coolify requires Docker $MIN_DOCKER_VERSION or newer." + echo " Please upgrade Docker: https://docs.docker.com/engine/install/" + exit 1 +else + echo " - Docker version $(docker version --format '{{.Server.Version}}' 2>/dev/null) meets minimum requirement ($MIN_DOCKER_VERSION+)." +fi + log_section "Step 4/9: Checking Docker configuration" echo "4/9 Checking Docker configuration..." diff --git a/other/nightly/versions.json b/other/nightly/versions.json index 7564f625e..af11ef4d3 100644 --- a/other/nightly/versions.json +++ b/other/nightly/versions.json @@ -1,7 +1,7 @@ { "coolify": { "v4": { - "version": "4.0.0-beta.469" + "version": "4.0.0-beta.471" }, "nightly": { "version": "4.0.0" @@ -13,17 +13,17 @@ "version": "1.0.11" }, "sentinel": { - "version": "0.0.19" + "version": "0.0.21" } }, "traefik": { - "v3.6": "3.6.5", + "v3.6": "3.6.11", "v3.5": "3.5.6", "v3.4": "3.4.5", "v3.3": "3.3.7", "v3.2": "3.2.5", "v3.1": "3.1.7", "v3.0": "3.0.4", - "v2.11": "2.11.32" + "v2.11": "2.11.40" } } diff --git a/phpunit.xml b/phpunit.xml index 6716b6b84..5d55acf75 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -22,6 +22,7 @@ + diff --git a/public/svgs/espocrm.svg b/public/svgs/espocrm.svg new file mode 100644 index 000000000..79d96f8c3 --- /dev/null +++ b/public/svgs/espocrm.svg @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/views/components/applications/links.blade.php b/resources/views/components/applications/links.blade.php index 26b1cedf5..85e8f7431 100644 --- a/resources/views/components/applications/links.blade.php +++ b/resources/views/components/applications/links.blade.php @@ -4,7 +4,7 @@ @if ( (data_get($application, 'fqdn') || - collect(json_decode($this->application->docker_compose_domains))->count() > 0 || + collect(json_decode($this->application->docker_compose_domains))->contains(fn($fqdn) => !empty(data_get($fqdn, 'domain'))) || data_get($application, 'previews', collect([]))->count() > 0 || data_get($application, 'ports_mappings_array')) && data_get($application, 'settings.is_raw_compose_deployment_enabled') !== true) diff --git a/resources/views/components/forms/monaco-editor.blade.php b/resources/views/components/forms/monaco-editor.blade.php index e774f5863..1a35be218 100644 --- a/resources/views/components/forms/monaco-editor.blade.php +++ b/resources/views/components/forms/monaco-editor.blade.php @@ -1,4 +1,4 @@ -
+
@endif