Merge remote-tracking branch 'origin/next' into harden-database-import-files

This commit is contained in:
Andras Bacsai 2026-06-29 10:30:07 +02:00
commit 7d65a4b496
550 changed files with 18078 additions and 5008 deletions

View file

@ -0,0 +1,404 @@
---
name: configure-nightwatch
description: Configures Laravel Nightwatch data collection, sampling rates, filtering rules, and redaction policies. Use when setting up Nightwatch, managing data volume, protecting sensitive data (PII), or optimizing event collection for production workloads.
license: MIT
metadata:
author: laravel
---
# Nightwatch Configuration Guide
This skill helps configure Laravel Nightwatch data collection to balance observability, performance, and privacy. Covers sampling strategies, filtering rules, and redaction methods across all event types.
## Documentation Reference
The [Nightwatch Documentation](https://nightwatch.laravel.com/docs) is the definitive and up-to-date source of information for all Nightwatch configuration options. This skill provides practical guidance and common patterns, but always consult the official documentation as the primary source of truth for specific details, environment variables, and API behavior. The documentation includes comprehensive coverage of:
- [Filtering and Configuration](https://nightwatch.laravel.com/docs/filtering) - Core concepts for sampling, filtering, and redaction
- Individual event type pages with specific configuration options:
- [Requests](https://nightwatch.laravel.com/docs/requests) - Request sampling, header handling, payload capture
- [Commands](https://nightwatch.laravel.com/docs/commands) - Command sampling and redaction
- [Queries](https://nightwatch.laravel.com/docs/queries) - Query filtering and redaction
- [Cache](https://nightwatch.laravel.com/docs/cache) - Cache event filtering by key or pattern
- [Jobs](https://nightwatch.laravel.com/docs/jobs) - Job filtering and sampling decoupling
- [Mail](https://nightwatch.laravel.com/docs/mail) - Mail event filtering
- [Notifications](https://nightwatch.laravel.com/docs/notifications) - Notification filtering by channel
- [Exceptions](https://nightwatch.laravel.com/docs/exceptions) - Exception sampling and throttling
- [Outgoing Requests](https://nightwatch.laravel.com/docs/outgoing-requests) - HTTP request filtering
- [reference.md](reference.md) - Quick lookup table by event type, production presets, and verification checklist
## Data Collection Flow
Nightwatch processes events through three stages:
1. **Sampling** - Controls which entry points are captured (requests, commands, scheduled tasks)
2. **Filtering** - Excludes specific events after sampling (queries, cache, mail, etc.)
3. **Redaction** - Modifies captured data to remove/obfuscate sensitive information
```
Request/Command/Scheduled Task
|
v
[Sampling?] ----NO----> Drop entire trace
| YES
v
Events generated
|
v
[Filtering?] ----YES---> Drop specific event
| NO
v
[Redaction] ----------> Store modified data
```
---
## Sampling Configuration
Sampling determines which entry points (requests, commands, scheduled tasks) trigger full trace collection. When an entry point is sampled, all related events are captured.
### Global Sample Rates
Configure via environment variables:
```bash
# Default: 100% sampling (all requests/commands captured)
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
```
**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.
### Route-Based Sampling
Apply different rates to specific routes using the `Sample` middleware:
```php routes/web.php
use Illuminate\Support\Facades\Route;
use Laravel\Nightwatch\Http\Middleware\Sample;
// Sample admin routes at 100%
Route::middleware(Sample::rate(1.0))->prefix('admin')->group(function () {
// All admin routes sampled fully
});
// Sample API routes at 5%
Route::middleware(Sample::rate(0.05))->prefix('api')->group(function () {
// API routes sampled sparingly
});
// Always sample critical endpoints
Route::post('/checkout', [CheckoutController::class, 'process'])
->middleware(Sample::always());
// Never sample health checks
Route::get('/health', [HealthController::class, 'check'])
->middleware(Sample::never());
```
### Unmatched Route Sampling
Handle 404/bot traffic with reduced sampling:
```php routes/web.php
Route::fallback(fn () => abort(404))
->middleware(Sample::rate(0.01)); // 1% sampling for unmatched routes
```
### Dynamic Sampling
Sample based on runtime conditions (user role, request attributes):
```php app/Http/Middleware/SampleAdminRequests.php
use Closure;
use Illuminate\Http\Request;
use Laravel\Nightwatch\Facades\Nightwatch;
class SampleAdminRequests
{
public function handle(Request $request, Closure $next)
{
if ($request->user()?->isAdmin()) {
Nightwatch::sample(); // Always sample admin requests
}
return $next($request);
}
}
```
### Command Sampling
Exclude specific commands from sampling:
```php AppServiceProvider.php
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Support\Facades\Event;
use Laravel\Nightwatch\Facades\Nightwatch;
public function boot(): void
{
Event::listen(function (CommandStarting $event) {
if (in_array($event->command, ['schedule:finish', 'horizon:snapshot'])) {
Nightwatch::dontSample();
}
});
}
```
### Vendor Commands
Nightwatch automatically ignores framework/internal commands. Opt-in to capture them:
```php
Nightwatch::captureDefaultVendorCommands();
```
---
## Filtering Configuration
Filtering excludes specific events from collection after sampling. Use filtering to reduce noise and quota usage.
### Database Queries
**Filter all queries** (disable query collection):
```bash
NIGHTWATCH_IGNORE_QUERIES=true
```
**Filter specific queries** by SQL pattern:
```php AppServiceProvider.php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Query;
public function boot(): void
{
// Filter job table queries (PostgreSQL)
Nightwatch::rejectQueries(function (Query $query) {
return str_contains($query->sql, 'into "jobs"');
});
// Filter cache table queries (MySQL)
Nightwatch::rejectQueries(function (Query $query) {
return str_contains($query->sql, 'from `cache`')
|| str_contains($query->sql, 'into `cache`');
});
}
```
### Cache Events
**Filter all cache events**:
```bash
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
```
**Filter by cache key patterns**:
```php
Nightwatch::rejectCacheKeys([
'my-app:users', // Exact match
'/^my-app:posts:/', // Regex: starts with my-app:posts:
'/^[a-zA-Z0-9]{40}$/', // Regex: session IDs
]);
```
**Filter with callback**:
```php
use Laravel\Nightwatch\Records\CacheEvent;
Nightwatch::rejectCacheEvents(function (CacheEvent $cacheEvent) {
return str_starts_with($cacheEvent->key, 'temp:');
});
```
### Mail Events
**Filter all mail**:
```bash
NIGHTWATCH_IGNORE_MAIL=true
```
**Filter specific mail**:
```php
use Laravel\Nightwatch\Records\Mail;
Nightwatch::rejectMail(function (Mail $mail) {
return str_contains($mail->subject, 'Newsletter');
});
```
### Notification Events
**Filter all notifications**:
```bash
NIGHTWATCH_IGNORE_NOTIFICATIONS=true
```
**Filter by channel**:
```php
use Laravel\Nightwatch\Records\Notification;
Nightwatch::rejectNotifications(function (Notification $notification) {
return $notification->channel === 'database';
});
```
### Outgoing HTTP Requests
**Filter all outgoing requests**:
```bash
NIGHTWATCH_IGNORE_OUTGOING_REQUESTS=true
```
**Filter by URL**:
```php
use Laravel\Nightwatch\Records\OutgoingRequest;
Nightwatch::rejectOutgoingRequests(function (OutgoingRequest $request) {
return str_contains($request->url, 'analytics.example.com');
});
```
### Queued Jobs
**Filter specific jobs**:
```php
use Laravel\Nightwatch\Records\QueuedJob;
Nightwatch::rejectQueuedJobs(function (QueuedJob $job) {
return $job->name === 'App\Jobs\LowPriorityJob';
});
```
### Decoupling Job Sampling
Sample jobs independently from parent contexts:
```php
use Illuminate\Support\Facades\Queue;
public function boot(): void
{
Queue::before(fn () => Nightwatch::sample(rate: 0.5));
}
```
---
## Redaction Configuration
Redaction modifies captured data to remove or obfuscate sensitive information. Unlike filtering, redaction keeps the event but sanitizes its content.
### Request Redaction
**Redact sensitive headers** (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):
```bash
# Customize redacted headers
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key
```
**Redact request payloads** (disabled by default):
```bash
# Enable payload capture
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true
# Customize redacted fields
NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card
```
**Programmatic redaction**:
```php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Request;
Nightwatch::redactRequests(function (Request $request) {
$request->url = str_replace('secret', '***', $request->url);
$request->ip = preg_replace('/\d+$/', '***', $request->ip);
});
```
### Query Redaction
```php
use Laravel\Nightwatch\Records\Query;
Nightwatch::redactQueries(function (Query $query) {
$query->sql = str_replace('secret_token', '***', $query->sql);
});
```
### Cache Redaction
```php
use Laravel\Nightwatch\Records\CacheEvent;
Nightwatch::redactCacheEvents(function (CacheEvent $cacheEvent) {
$cacheEvent->key = str_replace('user:', 'user:***:', $cacheEvent->key);
});
```
### Command Redaction
```php
use Laravel\Nightwatch\Records\Command;
Nightwatch::redactCommands(function (Command $command) {
$command->command = preg_replace('/--password=\S+/', '--password=***', $command->command);
});
```
### Exception Redaction
```php
use Laravel\Nightwatch\Records\Exception;
Nightwatch::redactExceptions(function (Exception $exception) {
$exception->message = str_replace('secret', '***', $exception->message);
});
```
### Mail Redaction
```php
use Laravel\Nightwatch\Records\Mail;
Nightwatch::redactMail(function (Mail $mail) {
$mail->subject = str_replace('Invoice #', 'Invoice ***', $mail->subject);
});
```
### Outgoing Request Redaction
```php
use Laravel\Nightwatch\Records\OutgoingRequest;
Nightwatch::redactOutgoingRequests(function (OutgoingRequest $outgoingRequest) {
$outgoingRequest->url = preg_replace('/api_key=\w+/', 'api_key=***', $outgoingRequest->url);
});
```

View file

@ -0,0 +1,108 @@
# Nightwatch Configuration Reference
## Configuration Summary by Event Type
| Event Type | Sampling | Filtering | Redaction |
| --------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------- |
| **Requests** | `NIGHTWATCH_REQUEST_SAMPLE_RATE`, Route middleware | Not applicable | Headers, payload, URL, IP |
| **Commands** | `NIGHTWATCH_COMMAND_SAMPLE_RATE`, Event listener | Not applicable | Command arguments |
| **Queries** | Parent context | `rejectQueries()`, `NIGHTWATCH_IGNORE_QUERIES` | SQL statement |
| **Cache** | Parent context | `rejectCacheKeys()`, `rejectCacheEvents()`, `NIGHTWATCH_IGNORE_CACHE_EVENTS` | Cache key |
| **Jobs** | Parent context, Queue::before | `rejectQueuedJobs()` | Not applicable |
| **Mail** | Parent context | `rejectMail()`, `NIGHTWATCH_IGNORE_MAIL` | Subject |
| **Notifications** | Parent context | `rejectNotifications()`, `NIGHTWATCH_IGNORE_NOTIFICATIONS` | Not applicable |
| **Outgoing Requests** | Parent context | `rejectOutgoingRequests()`, `NIGHTWATCH_IGNORE_OUTGOING_REQUESTS` | URL |
| **Exceptions** | `NIGHTWATCH_EXCEPTION_SAMPLE_RATE` | Not applicable | Exception message |
---
## Production Recommendations
### High-Traffic Applications
```bash
# Conservative sampling
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.01 # 1% of requests
NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1 # 10% of commands
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
# Filter noisy events
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
NIGHTWATCH_IGNORE_QUERIES=true # Or filter specific queries programmatically
```
### Privacy-Conscious Applications
```bash
# Disable sensitive data collection
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=false
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN
# Or use redaction in AppServiceProvider
```
### Balanced Configuration (Recommended Start)
```bash
# Sample rates
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0
# Filter obvious noise programmatically
# Redact PII as needed
```
---
## Verification Checklist
After configuration:
- [ ] Sampling rates appropriate for traffic volume
- [ ] Noisy events filtered (cache, certain queries)
- [ ] Sensitive data redacted (PII, tokens, credentials)
- [ ] Exceptions always captured for debugging
- [ ] Test in development with `NIGHTWATCH_REQUEST_SAMPLE_RATE=1.0`
- [ ] Monitor event quota usage in Nightwatch dashboard
---
## Common Patterns
### Filter Health Checks + Reduce Sampling
```php
Route::get('/health', fn() => ['status' => 'ok'])
->middleware(Sample::never());
```
### Exclude Internal/Vendor Queries
```php
Nightwatch::rejectQueries(fn($q) =>
str_contains($q->sql, 'telescope') ||
str_contains($q->sql, 'pulse')
);
```
### Protect User Data in Cache Keys
```php
Nightwatch::redactCacheEvents(fn($e) =>
$e->key = preg_replace('/user:\d+/', 'user:***', $e->key)
);
```

View file

@ -1,6 +1,6 @@
--- ---
name: fortify-development 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.' 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), passkeys, 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, passkeys, WebAuthn, 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 license: MIT
metadata: metadata:
author: laravel author: laravel
@ -32,6 +32,7 @@ ## Available Features
- `Features::updateProfileInformation()` - Profile updates - `Features::updateProfileInformation()` - Profile updates
- `Features::updatePasswords()` - Password changes - `Features::updatePasswords()` - Password changes
- `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes - `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes
- `Features::passkeys()` - Passwordless authentication with WebAuthn passkeys
> Use `search-docs` for feature configuration options and customization patterns. > Use `search-docs` for feature configuration options and customization patterns.
@ -50,6 +51,18 @@ ### Two-Factor Authentication Setup
> Use `search-docs` for TOTP implementation and recovery code handling patterns. > Use `search-docs` for TOTP implementation and recovery code handling patterns.
### Passkeys Setup
```
- [ ] Add PasskeyAuthenticatable trait to User model and implement PasskeyUser
- [ ] Enable passkeys feature in config/fortify.php
- [ ] If the passkeys table migration is missing, publish via `php artisan vendor:publish --tag=fortify-migrations` and migrate
- [ ] Configure passkeys relying_party_id, allowed_origins, user_handle_secret, and timeout if defaults are not suitable
- [ ] Build UI with @laravel/passkeys for registration, login, confirmation, and deletion
```
> Use `search-docs` for passkey configuration options. For `@laravel/passkeys` frontend usage, refer to the package's README on npm.
### Email Verification Setup ### Email Verification Setup
``` ```
@ -129,3 +142,10 @@ ## Key Endpoints
| 2FA Challenge | POST | `/two-factor-challenge` | | 2FA Challenge | POST | `/two-factor-challenge` |
| Get QR Code | GET | `/user/two-factor-qr-code` | | Get QR Code | GET | `/user/two-factor-qr-code` |
| Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` | | Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` |
| Passkey Login Options | GET | `/passkeys/login/options` |
| Passkey Login | POST | `/passkeys/login` |
| Passkey Confirm Options| GET | `/passkeys/confirm/options` |
| Passkey Confirm | POST | `/passkeys/confirm` |
| Passkey Options | GET | `/user/passkeys/options` |
| Register Passkey | POST | `/user/passkeys` |
| Delete Passkey | DELETE | `/user/passkeys/{passkey}` |

View file

@ -94,7 +94,7 @@ ### 8. Testing Patterns → `rules/testing.md`
### 9. Queue & Job Patterns → `rules/queue-jobs.md` ### 9. Queue & Job Patterns → `rules/queue-jobs.md`
- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]` - `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`
- `ShouldBeUnique` to prevent duplicates; `WithoutOverlapping::untilProcessing()` for concurrency - `ShouldBeUnique` to prevent duplicates; `ShouldBeUniqueUntilProcessing` for early lock release
- Always implement `failed()`; with `retryUntil()`, set `$tries = 0` - Always implement `failed()`; with `retryUntil()`, set `$tries = 0`
- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs - `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs
- Horizon for complex multi-queue scenarios - Horizon for complex multi-queue scenarios

View file

@ -82,7 +82,7 @@ ## Code to Interfaces
## Default Sort by Descending ## 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. When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.
Incorrect: Incorrect:
```php ```php

View file

@ -2,7 +2,7 @@ # Caching Best Practices
## Use `Cache::remember()` Instead of Manual Get/Put ## Use `Cache::remember()` Instead of Manual Get/Put
Atomic pattern prevents race conditions and removes boilerplate. Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.
Incorrect: Incorrect:
```php ```php

View file

@ -2,7 +2,7 @@ # Configuration Best Practices
## `env()` Only in Config Files ## `env()` Only in Config Files
Direct `env()` calls return `null` when config is cached. Direct `env()` calls may return `null` when config is cached.
Incorrect: Incorrect:
```php ```php

View file

@ -29,7 +29,11 @@ ## Always Queue Notifications
## Use `afterCommit()` on Notifications in Transactions ## Use `afterCommit()` on Notifications in Transactions
Same race condition as events — the queued notification job may run before the transaction commits. Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.
```php
$user->notify((new InvoicePaid($invoice))->afterCommit());
```
## Route Notification Channels to Dedicated Queues ## Route Notification Channels to Dedicated Queues

View file

@ -52,7 +52,7 @@ ## Use Retry with Backoff for External APIs
Only retry on specific errors: Only retry on specific errors:
```php ```php
$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) { $response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
return $exception instanceof ConnectionException return $exception instanceof ConnectionException
|| ($exception instanceof RequestException && $exception->response->serverError()); || ($exception instanceof RequestException && $exception->response->serverError());
})->post('https://api.example.com/data'); })->post('https://api.example.com/data');

View file

@ -10,7 +10,7 @@ ## Use `afterCommit()` on Mailables Inside Transactions
## Use `assertQueued()` Not `assertSent()` for Queued Mailables ## Use `assertQueued()` Not `assertSent()` for Queued Mailables
`Mail::assertSent()` only catches synchronous mail. Queued mailables silently pass `assertSent`, giving false confidence. `Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.
Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`. Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.

View file

@ -106,25 +106,23 @@ ## `retryUntil()` Needs `$tries = 0`
```php ```php
public $tries = 0; public $tries = 0;
public function retryUntil(): DateTime public function retryUntil(): \DateTimeInterface
{ {
return now()->addHours(4); return now()->addHours(4);
} }
``` ```
## Use `WithoutOverlapping::untilProcessing()` ## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release
Prevents concurrent execution while allowing new instances to queue. `ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue.
```php ```php
public function middleware(): array class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
{ {
return [new WithoutOverlapping($this->product->id)->untilProcessing()]; // Lock releases when processing begins, not when it finishes
} }
``` ```
Without `untilProcessing()`, the lock extends through queue wait time. With it, the lock releases when processing starts.
## Use Horizon for Complex Queue Scenarios ## Use Horizon for Complex Queue Scenarios
Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities. Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.

View file

@ -36,7 +36,8 @@ ## Use Resource Controllers
```php ```php
Route::resource('posts', PostController::class); Route::resource('posts', PostController::class);
Route::apiResource('api/posts', Api\PostController::class); // In routes/api.php — the /api prefix is applied automatically
Route::apiResource('posts', Api\PostController::class);
``` ```
## Keep Controllers Thin ## Keep Controllers Thin

View file

@ -32,7 +32,7 @@ ## Authorize Every Action
Incorrect: Incorrect:
```php ```php
public function update(Request $request, Post $post) public function update(UpdatePostRequest $request, Post $post)
{ {
$post->update($request->validated()); $post->update($request->validated());
} }
@ -90,7 +90,7 @@ ## Escape Output to Prevent XSS
## CSRF Protection ## CSRF Protection
Include `@csrf` in all POST/PUT/DELETE Blade forms. Not needed in Inertia. Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.
Incorrect: Incorrect:
```blade ```blade
@ -121,7 +121,7 @@ ## Rate Limit Auth and API Routes
## Validate File Uploads ## Validate File Uploads
Validate MIME type, extension, and size. Never trust client-provided filenames. Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.
```php ```php
public function rules(): array public function rules(): array

View file

@ -2,7 +2,7 @@ # Testing Best Practices
## Use `LazilyRefreshDatabase` Over `RefreshDatabase` ## 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. `RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date.
## Use Model Assertions Over Raw Database Assertions ## Use Model Assertions Over Raw Database Assertions

View file

@ -0,0 +1,96 @@
---
name: mcp-development
description: "Use this skill for Laravel MCP development only. Trigger when creating or editing MCP tools, resources, prompts, or servers in Laravel projects. Covers: artisan make:mcp-* generators, mcp:inspector, routes/ai.php, Tool/Resource/Prompt classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, and MCP debugging. Do not use for non-Laravel MCP projects or generic AI features without MCP."
license: MIT
metadata:
author: laravel
---
# MCP Development
## Documentation
Use `search-docs` for detailed Laravel MCP patterns and documentation.
## Basic Usage
Register MCP servers in `routes/ai.php`:
<!-- Register MCP Server -->
```php
use Laravel\Mcp\Facades\Mcp;
Mcp::web();
```
### Creating MCP Primitives
Create MCP tools, resources, prompts, and servers using artisan commands:
```bash
php artisan make:mcp-tool ToolName # Create a tool
php artisan make:mcp-resource ResourceName # Create a resource
php artisan make:mcp-prompt PromptName # Create a prompt
php artisan make:mcp-server ServerName # Create a server
```
After creating primitives, register them in your server's `$tools`, `$resources`, or `$prompts` properties.
### Tools
<!-- MCP Tool Example -->
```php
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Request;
use Laravel\Mcp\Server\Response;
class MyTool extends Tool
{
public function handle(Request $request): Response
{
return new Response(['result' => 'success']);
}
}
```
### Registering Primitives in a Server
Each MCP server must explicitly declare the tools, resources, and prompts it exposes.
<!-- Register Primitives in MCP Server -->
```php
use Laravel\Mcp\Server;
class AppServer extends Server
{
protected array $tools = [
\App\Mcp\Tools\MyTool::class,
];
protected array $resources = [
\App\Mcp\Resources\MyResource::class,
];
protected array $prompts = [
\App\Mcp\Prompts\MyPrompt::class,
];
}
```
## Verification
1. Check `routes/ai.php` for proper registration
2. Test tool via MCP client
## Common Pitfalls
- Running `mcp:start` command (it hangs waiting for input)
- Using HTTPS locally with Node-based MCP clients
- Not using `search-docs` for the latest MCP documentation
- Not registering MCP server routes in `routes/ai.php`
- Do not register `ai.php` in `bootstrap.php`; it is registered automatically.
- OAuth registration supports custom URI schemes (e.g., `cursor://`, `vscode://`) for native desktop clients via `mcp.custom_schemes` config

View file

@ -1,6 +1,6 @@
--- ---
name: pest-testing name: pest-testing
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." 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: test()/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 license: MIT
metadata: metadata:
author: laravel author: laravel
@ -18,6 +18,12 @@ ### Creating Tests
All tests must be written using Pest. Use `php artisan make:test --pest {name}`. All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
The `{name}` argument should include only the path and test name, but should not include the test suite.
- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`
- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`
- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`
- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`
### Test Organization ### Test Organization
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories. - Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
@ -26,6 +32,8 @@ ### Test Organization
### Basic Test Structure ### Basic Test Structure
Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.
<!-- Basic Pest Test Example --> <!-- Basic Pest Test Example -->
```php ```php
it('is true', function () { it('is true', function () {
@ -155,3 +163,4 @@ ## Common Pitfalls
- Forgetting datasets for repetitive validation tests - Forgetting datasets for repetitive validation tests
- Deleting tests without approval - Deleting tests without approval
- Forgetting `assertNoJavaScriptErrors()` in browser tests - Forgetting `assertNoJavaScriptErrors()` in browser tests
- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`

View file

@ -0,0 +1,404 @@
---
name: configure-nightwatch
description: Configures Laravel Nightwatch data collection, sampling rates, filtering rules, and redaction policies. Use when setting up Nightwatch, managing data volume, protecting sensitive data (PII), or optimizing event collection for production workloads.
license: MIT
metadata:
author: laravel
---
# Nightwatch Configuration Guide
This skill helps configure Laravel Nightwatch data collection to balance observability, performance, and privacy. Covers sampling strategies, filtering rules, and redaction methods across all event types.
## Documentation Reference
The [Nightwatch Documentation](https://nightwatch.laravel.com/docs) is the definitive and up-to-date source of information for all Nightwatch configuration options. This skill provides practical guidance and common patterns, but always consult the official documentation as the primary source of truth for specific details, environment variables, and API behavior. The documentation includes comprehensive coverage of:
- [Filtering and Configuration](https://nightwatch.laravel.com/docs/filtering) - Core concepts for sampling, filtering, and redaction
- Individual event type pages with specific configuration options:
- [Requests](https://nightwatch.laravel.com/docs/requests) - Request sampling, header handling, payload capture
- [Commands](https://nightwatch.laravel.com/docs/commands) - Command sampling and redaction
- [Queries](https://nightwatch.laravel.com/docs/queries) - Query filtering and redaction
- [Cache](https://nightwatch.laravel.com/docs/cache) - Cache event filtering by key or pattern
- [Jobs](https://nightwatch.laravel.com/docs/jobs) - Job filtering and sampling decoupling
- [Mail](https://nightwatch.laravel.com/docs/mail) - Mail event filtering
- [Notifications](https://nightwatch.laravel.com/docs/notifications) - Notification filtering by channel
- [Exceptions](https://nightwatch.laravel.com/docs/exceptions) - Exception sampling and throttling
- [Outgoing Requests](https://nightwatch.laravel.com/docs/outgoing-requests) - HTTP request filtering
- [reference.md](reference.md) - Quick lookup table by event type, production presets, and verification checklist
## Data Collection Flow
Nightwatch processes events through three stages:
1. **Sampling** - Controls which entry points are captured (requests, commands, scheduled tasks)
2. **Filtering** - Excludes specific events after sampling (queries, cache, mail, etc.)
3. **Redaction** - Modifies captured data to remove/obfuscate sensitive information
```
Request/Command/Scheduled Task
|
v
[Sampling?] ----NO----> Drop entire trace
| YES
v
Events generated
|
v
[Filtering?] ----YES---> Drop specific event
| NO
v
[Redaction] ----------> Store modified data
```
---
## Sampling Configuration
Sampling determines which entry points (requests, commands, scheduled tasks) trigger full trace collection. When an entry point is sampled, all related events are captured.
### Global Sample Rates
Configure via environment variables:
```bash
# Default: 100% sampling (all requests/commands captured)
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
```
**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.
### Route-Based Sampling
Apply different rates to specific routes using the `Sample` middleware:
```php routes/web.php
use Illuminate\Support\Facades\Route;
use Laravel\Nightwatch\Http\Middleware\Sample;
// Sample admin routes at 100%
Route::middleware(Sample::rate(1.0))->prefix('admin')->group(function () {
// All admin routes sampled fully
});
// Sample API routes at 5%
Route::middleware(Sample::rate(0.05))->prefix('api')->group(function () {
// API routes sampled sparingly
});
// Always sample critical endpoints
Route::post('/checkout', [CheckoutController::class, 'process'])
->middleware(Sample::always());
// Never sample health checks
Route::get('/health', [HealthController::class, 'check'])
->middleware(Sample::never());
```
### Unmatched Route Sampling
Handle 404/bot traffic with reduced sampling:
```php routes/web.php
Route::fallback(fn () => abort(404))
->middleware(Sample::rate(0.01)); // 1% sampling for unmatched routes
```
### Dynamic Sampling
Sample based on runtime conditions (user role, request attributes):
```php app/Http/Middleware/SampleAdminRequests.php
use Closure;
use Illuminate\Http\Request;
use Laravel\Nightwatch\Facades\Nightwatch;
class SampleAdminRequests
{
public function handle(Request $request, Closure $next)
{
if ($request->user()?->isAdmin()) {
Nightwatch::sample(); // Always sample admin requests
}
return $next($request);
}
}
```
### Command Sampling
Exclude specific commands from sampling:
```php AppServiceProvider.php
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Support\Facades\Event;
use Laravel\Nightwatch\Facades\Nightwatch;
public function boot(): void
{
Event::listen(function (CommandStarting $event) {
if (in_array($event->command, ['schedule:finish', 'horizon:snapshot'])) {
Nightwatch::dontSample();
}
});
}
```
### Vendor Commands
Nightwatch automatically ignores framework/internal commands. Opt-in to capture them:
```php
Nightwatch::captureDefaultVendorCommands();
```
---
## Filtering Configuration
Filtering excludes specific events from collection after sampling. Use filtering to reduce noise and quota usage.
### Database Queries
**Filter all queries** (disable query collection):
```bash
NIGHTWATCH_IGNORE_QUERIES=true
```
**Filter specific queries** by SQL pattern:
```php AppServiceProvider.php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Query;
public function boot(): void
{
// Filter job table queries (PostgreSQL)
Nightwatch::rejectQueries(function (Query $query) {
return str_contains($query->sql, 'into "jobs"');
});
// Filter cache table queries (MySQL)
Nightwatch::rejectQueries(function (Query $query) {
return str_contains($query->sql, 'from `cache`')
|| str_contains($query->sql, 'into `cache`');
});
}
```
### Cache Events
**Filter all cache events**:
```bash
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
```
**Filter by cache key patterns**:
```php
Nightwatch::rejectCacheKeys([
'my-app:users', // Exact match
'/^my-app:posts:/', // Regex: starts with my-app:posts:
'/^[a-zA-Z0-9]{40}$/', // Regex: session IDs
]);
```
**Filter with callback**:
```php
use Laravel\Nightwatch\Records\CacheEvent;
Nightwatch::rejectCacheEvents(function (CacheEvent $cacheEvent) {
return str_starts_with($cacheEvent->key, 'temp:');
});
```
### Mail Events
**Filter all mail**:
```bash
NIGHTWATCH_IGNORE_MAIL=true
```
**Filter specific mail**:
```php
use Laravel\Nightwatch\Records\Mail;
Nightwatch::rejectMail(function (Mail $mail) {
return str_contains($mail->subject, 'Newsletter');
});
```
### Notification Events
**Filter all notifications**:
```bash
NIGHTWATCH_IGNORE_NOTIFICATIONS=true
```
**Filter by channel**:
```php
use Laravel\Nightwatch\Records\Notification;
Nightwatch::rejectNotifications(function (Notification $notification) {
return $notification->channel === 'database';
});
```
### Outgoing HTTP Requests
**Filter all outgoing requests**:
```bash
NIGHTWATCH_IGNORE_OUTGOING_REQUESTS=true
```
**Filter by URL**:
```php
use Laravel\Nightwatch\Records\OutgoingRequest;
Nightwatch::rejectOutgoingRequests(function (OutgoingRequest $request) {
return str_contains($request->url, 'analytics.example.com');
});
```
### Queued Jobs
**Filter specific jobs**:
```php
use Laravel\Nightwatch\Records\QueuedJob;
Nightwatch::rejectQueuedJobs(function (QueuedJob $job) {
return $job->name === 'App\Jobs\LowPriorityJob';
});
```
### Decoupling Job Sampling
Sample jobs independently from parent contexts:
```php
use Illuminate\Support\Facades\Queue;
public function boot(): void
{
Queue::before(fn () => Nightwatch::sample(rate: 0.5));
}
```
---
## Redaction Configuration
Redaction modifies captured data to remove or obfuscate sensitive information. Unlike filtering, redaction keeps the event but sanitizes its content.
### Request Redaction
**Redact sensitive headers** (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):
```bash
# Customize redacted headers
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key
```
**Redact request payloads** (disabled by default):
```bash
# Enable payload capture
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true
# Customize redacted fields
NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card
```
**Programmatic redaction**:
```php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Request;
Nightwatch::redactRequests(function (Request $request) {
$request->url = str_replace('secret', '***', $request->url);
$request->ip = preg_replace('/\d+$/', '***', $request->ip);
});
```
### Query Redaction
```php
use Laravel\Nightwatch\Records\Query;
Nightwatch::redactQueries(function (Query $query) {
$query->sql = str_replace('secret_token', '***', $query->sql);
});
```
### Cache Redaction
```php
use Laravel\Nightwatch\Records\CacheEvent;
Nightwatch::redactCacheEvents(function (CacheEvent $cacheEvent) {
$cacheEvent->key = str_replace('user:', 'user:***:', $cacheEvent->key);
});
```
### Command Redaction
```php
use Laravel\Nightwatch\Records\Command;
Nightwatch::redactCommands(function (Command $command) {
$command->command = preg_replace('/--password=\S+/', '--password=***', $command->command);
});
```
### Exception Redaction
```php
use Laravel\Nightwatch\Records\Exception;
Nightwatch::redactExceptions(function (Exception $exception) {
$exception->message = str_replace('secret', '***', $exception->message);
});
```
### Mail Redaction
```php
use Laravel\Nightwatch\Records\Mail;
Nightwatch::redactMail(function (Mail $mail) {
$mail->subject = str_replace('Invoice #', 'Invoice ***', $mail->subject);
});
```
### Outgoing Request Redaction
```php
use Laravel\Nightwatch\Records\OutgoingRequest;
Nightwatch::redactOutgoingRequests(function (OutgoingRequest $outgoingRequest) {
$outgoingRequest->url = preg_replace('/api_key=\w+/', 'api_key=***', $outgoingRequest->url);
});
```

View file

@ -0,0 +1,108 @@
# Nightwatch Configuration Reference
## Configuration Summary by Event Type
| Event Type | Sampling | Filtering | Redaction |
| --------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------- |
| **Requests** | `NIGHTWATCH_REQUEST_SAMPLE_RATE`, Route middleware | Not applicable | Headers, payload, URL, IP |
| **Commands** | `NIGHTWATCH_COMMAND_SAMPLE_RATE`, Event listener | Not applicable | Command arguments |
| **Queries** | Parent context | `rejectQueries()`, `NIGHTWATCH_IGNORE_QUERIES` | SQL statement |
| **Cache** | Parent context | `rejectCacheKeys()`, `rejectCacheEvents()`, `NIGHTWATCH_IGNORE_CACHE_EVENTS` | Cache key |
| **Jobs** | Parent context, Queue::before | `rejectQueuedJobs()` | Not applicable |
| **Mail** | Parent context | `rejectMail()`, `NIGHTWATCH_IGNORE_MAIL` | Subject |
| **Notifications** | Parent context | `rejectNotifications()`, `NIGHTWATCH_IGNORE_NOTIFICATIONS` | Not applicable |
| **Outgoing Requests** | Parent context | `rejectOutgoingRequests()`, `NIGHTWATCH_IGNORE_OUTGOING_REQUESTS` | URL |
| **Exceptions** | `NIGHTWATCH_EXCEPTION_SAMPLE_RATE` | Not applicable | Exception message |
---
## Production Recommendations
### High-Traffic Applications
```bash
# Conservative sampling
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.01 # 1% of requests
NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1 # 10% of commands
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
# Filter noisy events
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
NIGHTWATCH_IGNORE_QUERIES=true # Or filter specific queries programmatically
```
### Privacy-Conscious Applications
```bash
# Disable sensitive data collection
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=false
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN
# Or use redaction in AppServiceProvider
```
### Balanced Configuration (Recommended Start)
```bash
# Sample rates
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0
# Filter obvious noise programmatically
# Redact PII as needed
```
---
## Verification Checklist
After configuration:
- [ ] Sampling rates appropriate for traffic volume
- [ ] Noisy events filtered (cache, certain queries)
- [ ] Sensitive data redacted (PII, tokens, credentials)
- [ ] Exceptions always captured for debugging
- [ ] Test in development with `NIGHTWATCH_REQUEST_SAMPLE_RATE=1.0`
- [ ] Monitor event quota usage in Nightwatch dashboard
---
## Common Patterns
### Filter Health Checks + Reduce Sampling
```php
Route::get('/health', fn() => ['status' => 'ok'])
->middleware(Sample::never());
```
### Exclude Internal/Vendor Queries
```php
Nightwatch::rejectQueries(fn($q) =>
str_contains($q->sql, 'telescope') ||
str_contains($q->sql, 'pulse')
);
```
### Protect User Data in Cache Keys
```php
Nightwatch::redactCacheEvents(fn($e) =>
$e->key = preg_replace('/user:\d+/', 'user:***', $e->key)
);
```

View file

@ -1,6 +1,6 @@
--- ---
name: fortify-development 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.' 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), passkeys, 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, passkeys, WebAuthn, 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 license: MIT
metadata: metadata:
author: laravel author: laravel
@ -32,6 +32,7 @@ ## Available Features
- `Features::updateProfileInformation()` - Profile updates - `Features::updateProfileInformation()` - Profile updates
- `Features::updatePasswords()` - Password changes - `Features::updatePasswords()` - Password changes
- `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes - `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes
- `Features::passkeys()` - Passwordless authentication with WebAuthn passkeys
> Use `search-docs` for feature configuration options and customization patterns. > Use `search-docs` for feature configuration options and customization patterns.
@ -50,6 +51,18 @@ ### Two-Factor Authentication Setup
> Use `search-docs` for TOTP implementation and recovery code handling patterns. > Use `search-docs` for TOTP implementation and recovery code handling patterns.
### Passkeys Setup
```
- [ ] Add PasskeyAuthenticatable trait to User model and implement PasskeyUser
- [ ] Enable passkeys feature in config/fortify.php
- [ ] If the passkeys table migration is missing, publish via `php artisan vendor:publish --tag=fortify-migrations` and migrate
- [ ] Configure passkeys relying_party_id, allowed_origins, user_handle_secret, and timeout if defaults are not suitable
- [ ] Build UI with @laravel/passkeys for registration, login, confirmation, and deletion
```
> Use `search-docs` for passkey configuration options. For `@laravel/passkeys` frontend usage, refer to the package's README on npm.
### Email Verification Setup ### Email Verification Setup
``` ```
@ -129,3 +142,10 @@ ## Key Endpoints
| 2FA Challenge | POST | `/two-factor-challenge` | | 2FA Challenge | POST | `/two-factor-challenge` |
| Get QR Code | GET | `/user/two-factor-qr-code` | | Get QR Code | GET | `/user/two-factor-qr-code` |
| Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` | | Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` |
| Passkey Login Options | GET | `/passkeys/login/options` |
| Passkey Login | POST | `/passkeys/login` |
| Passkey Confirm Options| GET | `/passkeys/confirm/options` |
| Passkey Confirm | POST | `/passkeys/confirm` |
| Passkey Options | GET | `/user/passkeys/options` |
| Register Passkey | POST | `/user/passkeys` |
| Delete Passkey | DELETE | `/user/passkeys/{passkey}` |

View file

@ -94,7 +94,7 @@ ### 8. Testing Patterns → `rules/testing.md`
### 9. Queue & Job Patterns → `rules/queue-jobs.md` ### 9. Queue & Job Patterns → `rules/queue-jobs.md`
- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]` - `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`
- `ShouldBeUnique` to prevent duplicates; `WithoutOverlapping::untilProcessing()` for concurrency - `ShouldBeUnique` to prevent duplicates; `ShouldBeUniqueUntilProcessing` for early lock release
- Always implement `failed()`; with `retryUntil()`, set `$tries = 0` - Always implement `failed()`; with `retryUntil()`, set `$tries = 0`
- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs - `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs
- Horizon for complex multi-queue scenarios - Horizon for complex multi-queue scenarios

View file

@ -82,7 +82,7 @@ ## Code to Interfaces
## Default Sort by Descending ## 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. When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.
Incorrect: Incorrect:
```php ```php

View file

@ -2,7 +2,7 @@ # Caching Best Practices
## Use `Cache::remember()` Instead of Manual Get/Put ## Use `Cache::remember()` Instead of Manual Get/Put
Atomic pattern prevents race conditions and removes boilerplate. Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.
Incorrect: Incorrect:
```php ```php

View file

@ -2,7 +2,7 @@ # Configuration Best Practices
## `env()` Only in Config Files ## `env()` Only in Config Files
Direct `env()` calls return `null` when config is cached. Direct `env()` calls may return `null` when config is cached.
Incorrect: Incorrect:
```php ```php

View file

@ -29,7 +29,11 @@ ## Always Queue Notifications
## Use `afterCommit()` on Notifications in Transactions ## Use `afterCommit()` on Notifications in Transactions
Same race condition as events — the queued notification job may run before the transaction commits. Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.
```php
$user->notify((new InvoicePaid($invoice))->afterCommit());
```
## Route Notification Channels to Dedicated Queues ## Route Notification Channels to Dedicated Queues

View file

@ -52,7 +52,7 @@ ## Use Retry with Backoff for External APIs
Only retry on specific errors: Only retry on specific errors:
```php ```php
$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) { $response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
return $exception instanceof ConnectionException return $exception instanceof ConnectionException
|| ($exception instanceof RequestException && $exception->response->serverError()); || ($exception instanceof RequestException && $exception->response->serverError());
})->post('https://api.example.com/data'); })->post('https://api.example.com/data');

View file

@ -10,7 +10,7 @@ ## Use `afterCommit()` on Mailables Inside Transactions
## Use `assertQueued()` Not `assertSent()` for Queued Mailables ## Use `assertQueued()` Not `assertSent()` for Queued Mailables
`Mail::assertSent()` only catches synchronous mail. Queued mailables silently pass `assertSent`, giving false confidence. `Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.
Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`. Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.

View file

@ -106,25 +106,23 @@ ## `retryUntil()` Needs `$tries = 0`
```php ```php
public $tries = 0; public $tries = 0;
public function retryUntil(): DateTime public function retryUntil(): \DateTimeInterface
{ {
return now()->addHours(4); return now()->addHours(4);
} }
``` ```
## Use `WithoutOverlapping::untilProcessing()` ## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release
Prevents concurrent execution while allowing new instances to queue. `ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue.
```php ```php
public function middleware(): array class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
{ {
return [new WithoutOverlapping($this->product->id)->untilProcessing()]; // Lock releases when processing begins, not when it finishes
} }
``` ```
Without `untilProcessing()`, the lock extends through queue wait time. With it, the lock releases when processing starts.
## Use Horizon for Complex Queue Scenarios ## Use Horizon for Complex Queue Scenarios
Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities. Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.

View file

@ -36,7 +36,8 @@ ## Use Resource Controllers
```php ```php
Route::resource('posts', PostController::class); Route::resource('posts', PostController::class);
Route::apiResource('api/posts', Api\PostController::class); // In routes/api.php — the /api prefix is applied automatically
Route::apiResource('posts', Api\PostController::class);
``` ```
## Keep Controllers Thin ## Keep Controllers Thin

View file

@ -32,7 +32,7 @@ ## Authorize Every Action
Incorrect: Incorrect:
```php ```php
public function update(Request $request, Post $post) public function update(UpdatePostRequest $request, Post $post)
{ {
$post->update($request->validated()); $post->update($request->validated());
} }
@ -90,7 +90,7 @@ ## Escape Output to Prevent XSS
## CSRF Protection ## CSRF Protection
Include `@csrf` in all POST/PUT/DELETE Blade forms. Not needed in Inertia. Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.
Incorrect: Incorrect:
```blade ```blade
@ -121,7 +121,7 @@ ## Rate Limit Auth and API Routes
## Validate File Uploads ## Validate File Uploads
Validate MIME type, extension, and size. Never trust client-provided filenames. Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.
```php ```php
public function rules(): array public function rules(): array

View file

@ -2,7 +2,7 @@ # Testing Best Practices
## Use `LazilyRefreshDatabase` Over `RefreshDatabase` ## 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. `RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date.
## Use Model Assertions Over Raw Database Assertions ## Use Model Assertions Over Raw Database Assertions

View file

@ -0,0 +1,96 @@
---
name: mcp-development
description: "Use this skill for Laravel MCP development only. Trigger when creating or editing MCP tools, resources, prompts, or servers in Laravel projects. Covers: artisan make:mcp-* generators, mcp:inspector, routes/ai.php, Tool/Resource/Prompt classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, and MCP debugging. Do not use for non-Laravel MCP projects or generic AI features without MCP."
license: MIT
metadata:
author: laravel
---
# MCP Development
## Documentation
Use `search-docs` for detailed Laravel MCP patterns and documentation.
## Basic Usage
Register MCP servers in `routes/ai.php`:
<!-- Register MCP Server -->
```php
use Laravel\Mcp\Facades\Mcp;
Mcp::web();
```
### Creating MCP Primitives
Create MCP tools, resources, prompts, and servers using artisan commands:
```bash
php artisan make:mcp-tool ToolName # Create a tool
php artisan make:mcp-resource ResourceName # Create a resource
php artisan make:mcp-prompt PromptName # Create a prompt
php artisan make:mcp-server ServerName # Create a server
```
After creating primitives, register them in your server's `$tools`, `$resources`, or `$prompts` properties.
### Tools
<!-- MCP Tool Example -->
```php
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Request;
use Laravel\Mcp\Server\Response;
class MyTool extends Tool
{
public function handle(Request $request): Response
{
return new Response(['result' => 'success']);
}
}
```
### Registering Primitives in a Server
Each MCP server must explicitly declare the tools, resources, and prompts it exposes.
<!-- Register Primitives in MCP Server -->
```php
use Laravel\Mcp\Server;
class AppServer extends Server
{
protected array $tools = [
\App\Mcp\Tools\MyTool::class,
];
protected array $resources = [
\App\Mcp\Resources\MyResource::class,
];
protected array $prompts = [
\App\Mcp\Prompts\MyPrompt::class,
];
}
```
## Verification
1. Check `routes/ai.php` for proper registration
2. Test tool via MCP client
## Common Pitfalls
- Running `mcp:start` command (it hangs waiting for input)
- Using HTTPS locally with Node-based MCP clients
- Not using `search-docs` for the latest MCP documentation
- Not registering MCP server routes in `routes/ai.php`
- Do not register `ai.php` in `bootstrap.php`; it is registered automatically.
- OAuth registration supports custom URI schemes (e.g., `cursor://`, `vscode://`) for native desktop clients via `mcp.custom_schemes` config

View file

@ -1,6 +1,6 @@
--- ---
name: pest-testing name: pest-testing
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." 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: test()/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 license: MIT
metadata: metadata:
author: laravel author: laravel
@ -18,6 +18,12 @@ ### Creating Tests
All tests must be written using Pest. Use `php artisan make:test --pest {name}`. All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
The `{name}` argument should include only the path and test name, but should not include the test suite.
- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`
- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`
- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`
- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`
### Test Organization ### Test Organization
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories. - Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
@ -26,6 +32,8 @@ ### Test Organization
### Basic Test Structure ### Basic Test Structure
Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.
<!-- Basic Pest Test Example --> <!-- Basic Pest Test Example -->
```php ```php
it('is true', function () { it('is true', function () {
@ -155,3 +163,4 @@ ## Common Pitfalls
- Forgetting datasets for repetitive validation tests - Forgetting datasets for repetitive validation tests
- Deleting tests without approval - Deleting tests without approval
- Forgetting `assertNoJavaScriptErrors()` in browser tests - Forgetting `assertNoJavaScriptErrors()` in browser tests
- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`

View file

@ -0,0 +1,404 @@
---
name: configure-nightwatch
description: Configures Laravel Nightwatch data collection, sampling rates, filtering rules, and redaction policies. Use when setting up Nightwatch, managing data volume, protecting sensitive data (PII), or optimizing event collection for production workloads.
license: MIT
metadata:
author: laravel
---
# Nightwatch Configuration Guide
This skill helps configure Laravel Nightwatch data collection to balance observability, performance, and privacy. Covers sampling strategies, filtering rules, and redaction methods across all event types.
## Documentation Reference
The [Nightwatch Documentation](https://nightwatch.laravel.com/docs) is the definitive and up-to-date source of information for all Nightwatch configuration options. This skill provides practical guidance and common patterns, but always consult the official documentation as the primary source of truth for specific details, environment variables, and API behavior. The documentation includes comprehensive coverage of:
- [Filtering and Configuration](https://nightwatch.laravel.com/docs/filtering) - Core concepts for sampling, filtering, and redaction
- Individual event type pages with specific configuration options:
- [Requests](https://nightwatch.laravel.com/docs/requests) - Request sampling, header handling, payload capture
- [Commands](https://nightwatch.laravel.com/docs/commands) - Command sampling and redaction
- [Queries](https://nightwatch.laravel.com/docs/queries) - Query filtering and redaction
- [Cache](https://nightwatch.laravel.com/docs/cache) - Cache event filtering by key or pattern
- [Jobs](https://nightwatch.laravel.com/docs/jobs) - Job filtering and sampling decoupling
- [Mail](https://nightwatch.laravel.com/docs/mail) - Mail event filtering
- [Notifications](https://nightwatch.laravel.com/docs/notifications) - Notification filtering by channel
- [Exceptions](https://nightwatch.laravel.com/docs/exceptions) - Exception sampling and throttling
- [Outgoing Requests](https://nightwatch.laravel.com/docs/outgoing-requests) - HTTP request filtering
- [reference.md](reference.md) - Quick lookup table by event type, production presets, and verification checklist
## Data Collection Flow
Nightwatch processes events through three stages:
1. **Sampling** - Controls which entry points are captured (requests, commands, scheduled tasks)
2. **Filtering** - Excludes specific events after sampling (queries, cache, mail, etc.)
3. **Redaction** - Modifies captured data to remove/obfuscate sensitive information
```
Request/Command/Scheduled Task
|
v
[Sampling?] ----NO----> Drop entire trace
| YES
v
Events generated
|
v
[Filtering?] ----YES---> Drop specific event
| NO
v
[Redaction] ----------> Store modified data
```
---
## Sampling Configuration
Sampling determines which entry points (requests, commands, scheduled tasks) trigger full trace collection. When an entry point is sampled, all related events are captured.
### Global Sample Rates
Configure via environment variables:
```bash
# Default: 100% sampling (all requests/commands captured)
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
```
**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.
### Route-Based Sampling
Apply different rates to specific routes using the `Sample` middleware:
```php routes/web.php
use Illuminate\Support\Facades\Route;
use Laravel\Nightwatch\Http\Middleware\Sample;
// Sample admin routes at 100%
Route::middleware(Sample::rate(1.0))->prefix('admin')->group(function () {
// All admin routes sampled fully
});
// Sample API routes at 5%
Route::middleware(Sample::rate(0.05))->prefix('api')->group(function () {
// API routes sampled sparingly
});
// Always sample critical endpoints
Route::post('/checkout', [CheckoutController::class, 'process'])
->middleware(Sample::always());
// Never sample health checks
Route::get('/health', [HealthController::class, 'check'])
->middleware(Sample::never());
```
### Unmatched Route Sampling
Handle 404/bot traffic with reduced sampling:
```php routes/web.php
Route::fallback(fn () => abort(404))
->middleware(Sample::rate(0.01)); // 1% sampling for unmatched routes
```
### Dynamic Sampling
Sample based on runtime conditions (user role, request attributes):
```php app/Http/Middleware/SampleAdminRequests.php
use Closure;
use Illuminate\Http\Request;
use Laravel\Nightwatch\Facades\Nightwatch;
class SampleAdminRequests
{
public function handle(Request $request, Closure $next)
{
if ($request->user()?->isAdmin()) {
Nightwatch::sample(); // Always sample admin requests
}
return $next($request);
}
}
```
### Command Sampling
Exclude specific commands from sampling:
```php AppServiceProvider.php
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Support\Facades\Event;
use Laravel\Nightwatch\Facades\Nightwatch;
public function boot(): void
{
Event::listen(function (CommandStarting $event) {
if (in_array($event->command, ['schedule:finish', 'horizon:snapshot'])) {
Nightwatch::dontSample();
}
});
}
```
### Vendor Commands
Nightwatch automatically ignores framework/internal commands. Opt-in to capture them:
```php
Nightwatch::captureDefaultVendorCommands();
```
---
## Filtering Configuration
Filtering excludes specific events from collection after sampling. Use filtering to reduce noise and quota usage.
### Database Queries
**Filter all queries** (disable query collection):
```bash
NIGHTWATCH_IGNORE_QUERIES=true
```
**Filter specific queries** by SQL pattern:
```php AppServiceProvider.php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Query;
public function boot(): void
{
// Filter job table queries (PostgreSQL)
Nightwatch::rejectQueries(function (Query $query) {
return str_contains($query->sql, 'into "jobs"');
});
// Filter cache table queries (MySQL)
Nightwatch::rejectQueries(function (Query $query) {
return str_contains($query->sql, 'from `cache`')
|| str_contains($query->sql, 'into `cache`');
});
}
```
### Cache Events
**Filter all cache events**:
```bash
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
```
**Filter by cache key patterns**:
```php
Nightwatch::rejectCacheKeys([
'my-app:users', // Exact match
'/^my-app:posts:/', // Regex: starts with my-app:posts:
'/^[a-zA-Z0-9]{40}$/', // Regex: session IDs
]);
```
**Filter with callback**:
```php
use Laravel\Nightwatch\Records\CacheEvent;
Nightwatch::rejectCacheEvents(function (CacheEvent $cacheEvent) {
return str_starts_with($cacheEvent->key, 'temp:');
});
```
### Mail Events
**Filter all mail**:
```bash
NIGHTWATCH_IGNORE_MAIL=true
```
**Filter specific mail**:
```php
use Laravel\Nightwatch\Records\Mail;
Nightwatch::rejectMail(function (Mail $mail) {
return str_contains($mail->subject, 'Newsletter');
});
```
### Notification Events
**Filter all notifications**:
```bash
NIGHTWATCH_IGNORE_NOTIFICATIONS=true
```
**Filter by channel**:
```php
use Laravel\Nightwatch\Records\Notification;
Nightwatch::rejectNotifications(function (Notification $notification) {
return $notification->channel === 'database';
});
```
### Outgoing HTTP Requests
**Filter all outgoing requests**:
```bash
NIGHTWATCH_IGNORE_OUTGOING_REQUESTS=true
```
**Filter by URL**:
```php
use Laravel\Nightwatch\Records\OutgoingRequest;
Nightwatch::rejectOutgoingRequests(function (OutgoingRequest $request) {
return str_contains($request->url, 'analytics.example.com');
});
```
### Queued Jobs
**Filter specific jobs**:
```php
use Laravel\Nightwatch\Records\QueuedJob;
Nightwatch::rejectQueuedJobs(function (QueuedJob $job) {
return $job->name === 'App\Jobs\LowPriorityJob';
});
```
### Decoupling Job Sampling
Sample jobs independently from parent contexts:
```php
use Illuminate\Support\Facades\Queue;
public function boot(): void
{
Queue::before(fn () => Nightwatch::sample(rate: 0.5));
}
```
---
## Redaction Configuration
Redaction modifies captured data to remove or obfuscate sensitive information. Unlike filtering, redaction keeps the event but sanitizes its content.
### Request Redaction
**Redact sensitive headers** (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):
```bash
# Customize redacted headers
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key
```
**Redact request payloads** (disabled by default):
```bash
# Enable payload capture
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true
# Customize redacted fields
NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card
```
**Programmatic redaction**:
```php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Request;
Nightwatch::redactRequests(function (Request $request) {
$request->url = str_replace('secret', '***', $request->url);
$request->ip = preg_replace('/\d+$/', '***', $request->ip);
});
```
### Query Redaction
```php
use Laravel\Nightwatch\Records\Query;
Nightwatch::redactQueries(function (Query $query) {
$query->sql = str_replace('secret_token', '***', $query->sql);
});
```
### Cache Redaction
```php
use Laravel\Nightwatch\Records\CacheEvent;
Nightwatch::redactCacheEvents(function (CacheEvent $cacheEvent) {
$cacheEvent->key = str_replace('user:', 'user:***:', $cacheEvent->key);
});
```
### Command Redaction
```php
use Laravel\Nightwatch\Records\Command;
Nightwatch::redactCommands(function (Command $command) {
$command->command = preg_replace('/--password=\S+/', '--password=***', $command->command);
});
```
### Exception Redaction
```php
use Laravel\Nightwatch\Records\Exception;
Nightwatch::redactExceptions(function (Exception $exception) {
$exception->message = str_replace('secret', '***', $exception->message);
});
```
### Mail Redaction
```php
use Laravel\Nightwatch\Records\Mail;
Nightwatch::redactMail(function (Mail $mail) {
$mail->subject = str_replace('Invoice #', 'Invoice ***', $mail->subject);
});
```
### Outgoing Request Redaction
```php
use Laravel\Nightwatch\Records\OutgoingRequest;
Nightwatch::redactOutgoingRequests(function (OutgoingRequest $outgoingRequest) {
$outgoingRequest->url = preg_replace('/api_key=\w+/', 'api_key=***', $outgoingRequest->url);
});
```

View file

@ -0,0 +1,108 @@
# Nightwatch Configuration Reference
## Configuration Summary by Event Type
| Event Type | Sampling | Filtering | Redaction |
| --------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------- |
| **Requests** | `NIGHTWATCH_REQUEST_SAMPLE_RATE`, Route middleware | Not applicable | Headers, payload, URL, IP |
| **Commands** | `NIGHTWATCH_COMMAND_SAMPLE_RATE`, Event listener | Not applicable | Command arguments |
| **Queries** | Parent context | `rejectQueries()`, `NIGHTWATCH_IGNORE_QUERIES` | SQL statement |
| **Cache** | Parent context | `rejectCacheKeys()`, `rejectCacheEvents()`, `NIGHTWATCH_IGNORE_CACHE_EVENTS` | Cache key |
| **Jobs** | Parent context, Queue::before | `rejectQueuedJobs()` | Not applicable |
| **Mail** | Parent context | `rejectMail()`, `NIGHTWATCH_IGNORE_MAIL` | Subject |
| **Notifications** | Parent context | `rejectNotifications()`, `NIGHTWATCH_IGNORE_NOTIFICATIONS` | Not applicable |
| **Outgoing Requests** | Parent context | `rejectOutgoingRequests()`, `NIGHTWATCH_IGNORE_OUTGOING_REQUESTS` | URL |
| **Exceptions** | `NIGHTWATCH_EXCEPTION_SAMPLE_RATE` | Not applicable | Exception message |
---
## Production Recommendations
### High-Traffic Applications
```bash
# Conservative sampling
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.01 # 1% of requests
NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1 # 10% of commands
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
# Filter noisy events
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
NIGHTWATCH_IGNORE_QUERIES=true # Or filter specific queries programmatically
```
### Privacy-Conscious Applications
```bash
# Disable sensitive data collection
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=false
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN
# Or use redaction in AppServiceProvider
```
### Balanced Configuration (Recommended Start)
```bash
# Sample rates
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0
# Filter obvious noise programmatically
# Redact PII as needed
```
---
## Verification Checklist
After configuration:
- [ ] Sampling rates appropriate for traffic volume
- [ ] Noisy events filtered (cache, certain queries)
- [ ] Sensitive data redacted (PII, tokens, credentials)
- [ ] Exceptions always captured for debugging
- [ ] Test in development with `NIGHTWATCH_REQUEST_SAMPLE_RATE=1.0`
- [ ] Monitor event quota usage in Nightwatch dashboard
---
## Common Patterns
### Filter Health Checks + Reduce Sampling
```php
Route::get('/health', fn() => ['status' => 'ok'])
->middleware(Sample::never());
```
### Exclude Internal/Vendor Queries
```php
Nightwatch::rejectQueries(fn($q) =>
str_contains($q->sql, 'telescope') ||
str_contains($q->sql, 'pulse')
);
```
### Protect User Data in Cache Keys
```php
Nightwatch::redactCacheEvents(fn($e) =>
$e->key = preg_replace('/user:\d+/', 'user:***', $e->key)
);
```

View file

@ -1,6 +1,6 @@
--- ---
name: fortify-development 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.' 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), passkeys, 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, passkeys, WebAuthn, 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 license: MIT
metadata: metadata:
author: laravel author: laravel
@ -32,6 +32,7 @@ ## Available Features
- `Features::updateProfileInformation()` - Profile updates - `Features::updateProfileInformation()` - Profile updates
- `Features::updatePasswords()` - Password changes - `Features::updatePasswords()` - Password changes
- `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes - `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes
- `Features::passkeys()` - Passwordless authentication with WebAuthn passkeys
> Use `search-docs` for feature configuration options and customization patterns. > Use `search-docs` for feature configuration options and customization patterns.
@ -50,6 +51,18 @@ ### Two-Factor Authentication Setup
> Use `search-docs` for TOTP implementation and recovery code handling patterns. > Use `search-docs` for TOTP implementation and recovery code handling patterns.
### Passkeys Setup
```
- [ ] Add PasskeyAuthenticatable trait to User model and implement PasskeyUser
- [ ] Enable passkeys feature in config/fortify.php
- [ ] If the passkeys table migration is missing, publish via `php artisan vendor:publish --tag=fortify-migrations` and migrate
- [ ] Configure passkeys relying_party_id, allowed_origins, user_handle_secret, and timeout if defaults are not suitable
- [ ] Build UI with @laravel/passkeys for registration, login, confirmation, and deletion
```
> Use `search-docs` for passkey configuration options. For `@laravel/passkeys` frontend usage, refer to the package's README on npm.
### Email Verification Setup ### Email Verification Setup
``` ```
@ -129,3 +142,10 @@ ## Key Endpoints
| 2FA Challenge | POST | `/two-factor-challenge` | | 2FA Challenge | POST | `/two-factor-challenge` |
| Get QR Code | GET | `/user/two-factor-qr-code` | | Get QR Code | GET | `/user/two-factor-qr-code` |
| Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` | | Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` |
| Passkey Login Options | GET | `/passkeys/login/options` |
| Passkey Login | POST | `/passkeys/login` |
| Passkey Confirm Options| GET | `/passkeys/confirm/options` |
| Passkey Confirm | POST | `/passkeys/confirm` |
| Passkey Options | GET | `/user/passkeys/options` |
| Register Passkey | POST | `/user/passkeys` |
| Delete Passkey | DELETE | `/user/passkeys/{passkey}` |

View file

@ -94,7 +94,7 @@ ### 8. Testing Patterns → `rules/testing.md`
### 9. Queue & Job Patterns → `rules/queue-jobs.md` ### 9. Queue & Job Patterns → `rules/queue-jobs.md`
- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]` - `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`
- `ShouldBeUnique` to prevent duplicates; `WithoutOverlapping::untilProcessing()` for concurrency - `ShouldBeUnique` to prevent duplicates; `ShouldBeUniqueUntilProcessing` for early lock release
- Always implement `failed()`; with `retryUntil()`, set `$tries = 0` - Always implement `failed()`; with `retryUntil()`, set `$tries = 0`
- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs - `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs
- Horizon for complex multi-queue scenarios - Horizon for complex multi-queue scenarios

View file

@ -82,7 +82,7 @@ ## Code to Interfaces
## Default Sort by Descending ## 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. When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.
Incorrect: Incorrect:
```php ```php

View file

@ -2,7 +2,7 @@ # Caching Best Practices
## Use `Cache::remember()` Instead of Manual Get/Put ## Use `Cache::remember()` Instead of Manual Get/Put
Atomic pattern prevents race conditions and removes boilerplate. Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.
Incorrect: Incorrect:
```php ```php

View file

@ -2,7 +2,7 @@ # Configuration Best Practices
## `env()` Only in Config Files ## `env()` Only in Config Files
Direct `env()` calls return `null` when config is cached. Direct `env()` calls may return `null` when config is cached.
Incorrect: Incorrect:
```php ```php

View file

@ -29,7 +29,11 @@ ## Always Queue Notifications
## Use `afterCommit()` on Notifications in Transactions ## Use `afterCommit()` on Notifications in Transactions
Same race condition as events — the queued notification job may run before the transaction commits. Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.
```php
$user->notify((new InvoicePaid($invoice))->afterCommit());
```
## Route Notification Channels to Dedicated Queues ## Route Notification Channels to Dedicated Queues

View file

@ -52,7 +52,7 @@ ## Use Retry with Backoff for External APIs
Only retry on specific errors: Only retry on specific errors:
```php ```php
$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) { $response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
return $exception instanceof ConnectionException return $exception instanceof ConnectionException
|| ($exception instanceof RequestException && $exception->response->serverError()); || ($exception instanceof RequestException && $exception->response->serverError());
})->post('https://api.example.com/data'); })->post('https://api.example.com/data');

View file

@ -10,7 +10,7 @@ ## Use `afterCommit()` on Mailables Inside Transactions
## Use `assertQueued()` Not `assertSent()` for Queued Mailables ## Use `assertQueued()` Not `assertSent()` for Queued Mailables
`Mail::assertSent()` only catches synchronous mail. Queued mailables silently pass `assertSent`, giving false confidence. `Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.
Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`. Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.

View file

@ -106,25 +106,23 @@ ## `retryUntil()` Needs `$tries = 0`
```php ```php
public $tries = 0; public $tries = 0;
public function retryUntil(): DateTime public function retryUntil(): \DateTimeInterface
{ {
return now()->addHours(4); return now()->addHours(4);
} }
``` ```
## Use `WithoutOverlapping::untilProcessing()` ## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release
Prevents concurrent execution while allowing new instances to queue. `ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue.
```php ```php
public function middleware(): array class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
{ {
return [new WithoutOverlapping($this->product->id)->untilProcessing()]; // Lock releases when processing begins, not when it finishes
} }
``` ```
Without `untilProcessing()`, the lock extends through queue wait time. With it, the lock releases when processing starts.
## Use Horizon for Complex Queue Scenarios ## Use Horizon for Complex Queue Scenarios
Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities. Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.

View file

@ -36,7 +36,8 @@ ## Use Resource Controllers
```php ```php
Route::resource('posts', PostController::class); Route::resource('posts', PostController::class);
Route::apiResource('api/posts', Api\PostController::class); // In routes/api.php — the /api prefix is applied automatically
Route::apiResource('posts', Api\PostController::class);
``` ```
## Keep Controllers Thin ## Keep Controllers Thin

View file

@ -32,7 +32,7 @@ ## Authorize Every Action
Incorrect: Incorrect:
```php ```php
public function update(Request $request, Post $post) public function update(UpdatePostRequest $request, Post $post)
{ {
$post->update($request->validated()); $post->update($request->validated());
} }
@ -90,7 +90,7 @@ ## Escape Output to Prevent XSS
## CSRF Protection ## CSRF Protection
Include `@csrf` in all POST/PUT/DELETE Blade forms. Not needed in Inertia. Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.
Incorrect: Incorrect:
```blade ```blade
@ -121,7 +121,7 @@ ## Rate Limit Auth and API Routes
## Validate File Uploads ## Validate File Uploads
Validate MIME type, extension, and size. Never trust client-provided filenames. Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.
```php ```php
public function rules(): array public function rules(): array

View file

@ -2,7 +2,7 @@ # Testing Best Practices
## Use `LazilyRefreshDatabase` Over `RefreshDatabase` ## 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. `RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date.
## Use Model Assertions Over Raw Database Assertions ## Use Model Assertions Over Raw Database Assertions

View file

@ -0,0 +1,96 @@
---
name: mcp-development
description: "Use this skill for Laravel MCP development only. Trigger when creating or editing MCP tools, resources, prompts, or servers in Laravel projects. Covers: artisan make:mcp-* generators, mcp:inspector, routes/ai.php, Tool/Resource/Prompt classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, and MCP debugging. Do not use for non-Laravel MCP projects or generic AI features without MCP."
license: MIT
metadata:
author: laravel
---
# MCP Development
## Documentation
Use `search-docs` for detailed Laravel MCP patterns and documentation.
## Basic Usage
Register MCP servers in `routes/ai.php`:
<!-- Register MCP Server -->
```php
use Laravel\Mcp\Facades\Mcp;
Mcp::web();
```
### Creating MCP Primitives
Create MCP tools, resources, prompts, and servers using artisan commands:
```bash
php artisan make:mcp-tool ToolName # Create a tool
php artisan make:mcp-resource ResourceName # Create a resource
php artisan make:mcp-prompt PromptName # Create a prompt
php artisan make:mcp-server ServerName # Create a server
```
After creating primitives, register them in your server's `$tools`, `$resources`, or `$prompts` properties.
### Tools
<!-- MCP Tool Example -->
```php
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Request;
use Laravel\Mcp\Server\Response;
class MyTool extends Tool
{
public function handle(Request $request): Response
{
return new Response(['result' => 'success']);
}
}
```
### Registering Primitives in a Server
Each MCP server must explicitly declare the tools, resources, and prompts it exposes.
<!-- Register Primitives in MCP Server -->
```php
use Laravel\Mcp\Server;
class AppServer extends Server
{
protected array $tools = [
\App\Mcp\Tools\MyTool::class,
];
protected array $resources = [
\App\Mcp\Resources\MyResource::class,
];
protected array $prompts = [
\App\Mcp\Prompts\MyPrompt::class,
];
}
```
## Verification
1. Check `routes/ai.php` for proper registration
2. Test tool via MCP client
## Common Pitfalls
- Running `mcp:start` command (it hangs waiting for input)
- Using HTTPS locally with Node-based MCP clients
- Not using `search-docs` for the latest MCP documentation
- Not registering MCP server routes in `routes/ai.php`
- Do not register `ai.php` in `bootstrap.php`; it is registered automatically.
- OAuth registration supports custom URI schemes (e.g., `cursor://`, `vscode://`) for native desktop clients via `mcp.custom_schemes` config

View file

@ -1,6 +1,6 @@
--- ---
name: pest-testing name: pest-testing
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." 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: test()/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 license: MIT
metadata: metadata:
author: laravel author: laravel
@ -18,6 +18,12 @@ ### Creating Tests
All tests must be written using Pest. Use `php artisan make:test --pest {name}`. All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
The `{name}` argument should include only the path and test name, but should not include the test suite.
- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`
- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`
- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`
- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`
### Test Organization ### Test Organization
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories. - Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
@ -26,6 +32,8 @@ ### Test Organization
### Basic Test Structure ### Basic Test Structure
Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.
<!-- Basic Pest Test Example --> <!-- Basic Pest Test Example -->
```php ```php
it('is true', function () { it('is true', function () {
@ -155,3 +163,4 @@ ## Common Pitfalls
- Forgetting datasets for repetitive validation tests - Forgetting datasets for repetitive validation tests
- Deleting tests without approval - Deleting tests without approval
- Forgetting `assertNoJavaScriptErrors()` in browser tests - Forgetting `assertNoJavaScriptErrors()` in browser tests
- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`

View file

@ -40,7 +40,10 @@ jobs:
# This will help ensure that our documentation remains accurate and up-to-date for all users. # This will help ensure that our documentation remains accurate and up-to-date for all users.
steps: steps:
- name: Add comment - name: Add comment
if: github.event.label.name == matrix.label if: >-
(github.event.label.name == matrix.label || github.event.label.name == '📑 Waiting for Docs PR')
&& contains(github.event.pull_request.labels.*.name, matrix.label)
&& contains(github.event.pull_request.labels.*.name, '📑 Waiting for Docs PR')
run: gh pr comment "$NUMBER" --body "$BODY" run: gh pr comment "$NUMBER" --body "$BODY"
env: env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

166
AGENTS.md
View file

@ -1,7 +1,147 @@
# AGENTS.md
This file provides guidance to agentic coding tools when working with code in this repository.
## Project Overview
Coolify is an open-source, self-hostable PaaS (alternative to Heroku/Netlify/Vercel). It manages servers, applications, databases, and services via SSH. Built with Laravel 12 (using Laravel 10 file structure), Livewire 3, and Tailwind CSS v4.
## Design Reference ## Design Reference
For UI/UX design specifications, principles, and visual standards, consult `DESIGN.md` in the [coollabsio/architecture](https://github.com/coollabsio/architecture) repo. For UI/UX design specifications, principles, and visual standards, consult `DESIGN.md` in the [coollabsio/architecture](https://github.com/coollabsio/architecture) repo.
## Development Environment
Docker Compose-based dev setup with services: coolify (app), postgres, redis, soketi (WebSockets), vite, testing-host, mailpit, minio.
```bash
# Start dev environment (uses docker-compose.dev.yml)
spin up # or: docker compose -f docker-compose.dev.yml up -d
spin down # stop services
```
The app runs at `localhost:8000` by default. Vite dev server on port 5173.
## Common Commands
```bash
# Tests (Pest 4)
php artisan test --compact # all tests
php artisan test --compact --filter=testName # single test
php artisan test --compact tests/Feature/SomeTest.php # specific file
# Code formatting (Pint, Laravel preset)
vendor/bin/pint --dirty --format agent # format changed files
# Frontend
npm run dev # vite dev server
npm run build # production build
```
## Browser Tests (Pest Browser Plugin)
Uses `pestphp/pest-plugin-browser` with Laravel Dusk 8. New browser tests go in `tests/v4/Browser/`.
```bash
# Run all browser tests
php artisan test --compact tests/v4/Browser/
# Run a specific browser test file
php artisan test --compact tests/v4/Browser/LoginTest.php
# Run a specific test by name
php artisan test --compact --filter='can login with valid credentials'
```
### Writing Browser Tests
- Place new tests in `tests/v4/Browser/` — legacy Dusk tests in `tests/Browser/` should not be used as reference.
- Use `RefreshDatabase` and seed required data (at minimum `InstanceSettings::create(['id' => 0])`) in `beforeEach`.
- Key API: `visit()`, `fill(field, value)`, `click(text)`, `assertSee()`, `assertDontSee()`, `assertPathIs()`, `screenshot()`.
- Always call `screenshot()` at the end of each test for debugging.
- For authenticated tests, create a helper function that logs in via the UI:
```php
function loginAsRoot(): mixed
{
return visit('/login')
->fill('email', 'test@example.com')
->fill('password', 'password')
->click('Login');
}
```
- See `tests/v4/Browser/LoginTest.php`, `tests/v4/Browser/DashboardTest.php`, and `tests/v4/Browser/RegistrationTest.php` for conventions.
- Chrome driver runs on `localhost:4444`, app on `localhost:8000` (configured in `tests/DuskTestCase.php`).
- Legacy Dusk macros in `app/Providers/DuskServiceProvider.php` use the old `type()`/`press()` API — do not mix with Pest Browser Plugin's `fill()`/`click()` API.
## Architecture
### Backend Structure (app/)
- **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.
- **Application** — A deployed app (from Git or Docker image) with environment variables, previews, deployment queue.
- **Service** — A pre-configured service stack from templates (`templates/service-templates-latest.json`).
- **Standalone Databases** — Individual database instances (Postgres, MySQL, MariaDB, MongoDB, Redis, Clickhouse, KeyDB, Dragonfly).
- **Project/Environment** — Organizational hierarchy: Team → Project → Environment → Resources.
- **Proxy** — Traefik reverse proxy managed per server.
### Frontend
- Livewire 3 components with Alpine.js for client-side interactivity
- Blade templates in `resources/views/livewire/`
- Tailwind CSS v4 with `@tailwindcss/forms` and `@tailwindcss/typography`
- Vite for asset bundling
### Laravel 10 Structure (NOT Laravel 11+ slim structure)
- 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/`
## Key Conventions
- Use `php artisan make:*` commands with `--no-interaction` to create files
- Use Eloquent relationships, avoid `DB::` facade — prefer `Model::query()`
- PHP 8.5: constructor property promotion, explicit return types, type hints
- 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. 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
- Main branch: `v4.x`
- Development branch: `next`
- PRs should target `v4.x`
<laravel-boost-guidelines> <laravel-boost-guidelines>
=== foundation rules === === foundation rules ===
@ -17,6 +157,7 @@ ## Foundational Context
- laravel/fortify (FORTIFY) - v1 - laravel/fortify (FORTIFY) - v1
- laravel/framework (LARAVEL) - v12 - laravel/framework (LARAVEL) - v12
- laravel/horizon (HORIZON) - v5 - laravel/horizon (HORIZON) - v5
- laravel/mcp (MCP) - v0
- laravel/nightwatch (NIGHTWATCH) - v1 - laravel/nightwatch (NIGHTWATCH) - v1
- laravel/pail (PAIL) - v1 - laravel/pail (PAIL) - v1
- laravel/prompts (PROMPTS) - v0 - laravel/prompts (PROMPTS) - v0
@ -25,29 +166,16 @@ ## Foundational Context
- livewire/livewire (LIVEWIRE) - v3 - livewire/livewire (LIVEWIRE) - v3
- laravel/boost (BOOST) - v2 - laravel/boost (BOOST) - v2
- laravel/dusk (DUSK) - v8 - laravel/dusk (DUSK) - v8
- laravel/mcp (MCP) - v0
- laravel/pint (PINT) - v1 - laravel/pint (PINT) - v1
- laravel/telescope (TELESCOPE) - v5 - laravel/telescope (TELESCOPE) - v5
- pestphp/pest (PEST) - v4 - pestphp/pest (PEST) - v4
- phpunit/phpunit (PHPUNIT) - v12 - phpunit/phpunit (PHPUNIT) - v12
- rector/rector (RECTOR) - v2 - rector/rector (RECTOR) - v2
- laravel-echo (ECHO) - v2
- tailwindcss (TAILWINDCSS) - v4 - tailwindcss (TAILWINDCSS) - v4
- vue (VUE) - v3
## Skills Activation ## 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. This project has domain-specific skills available in `**/skills/**`. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
- `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 ## Conventions
@ -107,7 +235,6 @@ ## Artisan
- 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. - 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`. - 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. - 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.
## Tinker ## Tinker
@ -122,10 +249,16 @@ # PHP
- Always use curly braces for control structures, even for single-line bodies. - Always use curly braces for control structures, even for single-line bodies.
- 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 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 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`. - Follow existing application Enum naming conventions.
- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic. - Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic.
- Use array shape type definitions in PHPDoc blocks. - Use array shape type definitions in PHPDoc blocks.
=== deployments rules ===
# Deployment
- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
=== tests rules === === tests rules ===
# Test Enforcement # Test Enforcement
@ -209,6 +342,7 @@ # Laravel Pint Code Formatter
## Pest ## Pest
- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`. - This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`.
- The `{name}` argument should not include the test suite directory. Use `php artisan make:test --pest SomeFeatureTest` instead of `php artisan make:test --pest Feature/SomeFeatureTest`.
- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`. - Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`.
- Do NOT delete tests without approval. - Do NOT delete tests without approval.

318
CLAUDE.md
View file

@ -1,318 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Coolify is an open-source, self-hostable PaaS (alternative to Heroku/Netlify/Vercel). It manages servers, applications, databases, and services via SSH. Built with Laravel 12 (using Laravel 10 file structure), Livewire 3, and Tailwind CSS v4.
## Design Reference
For UI/UX design specifications, principles, and visual standards, consult `DESIGN.md` in the [coollabsio/architecture](https://github.com/coollabsio/architecture) repo.
## Development Environment
Docker Compose-based dev setup with services: coolify (app), postgres, redis, soketi (WebSockets), vite, testing-host, mailpit, minio.
```bash
# Start dev environment (uses docker-compose.dev.yml)
spin up # or: docker compose -f docker-compose.dev.yml up -d
spin down # stop services
```
The app runs at `localhost:8000` by default. Vite dev server on port 5173.
## Common Commands
```bash
# Tests (Pest 4)
php artisan test --compact # all tests
php artisan test --compact --filter=testName # single test
php artisan test --compact tests/Feature/SomeTest.php # specific file
# Code formatting (Pint, Laravel preset)
vendor/bin/pint --dirty --format agent # format changed files
# Frontend
npm run dev # vite dev server
npm run build # production build
```
## Architecture
### Backend Structure (app/)
- **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.
- **Application** — A deployed app (from Git or Docker image) with environment variables, previews, deployment queue.
- **Service** — A pre-configured service stack from templates (`templates/service-templates-latest.json`).
- **Standalone Databases** — Individual database instances (Postgres, MySQL, MariaDB, MongoDB, Redis, Clickhouse, KeyDB, Dragonfly).
- **Project/Environment** — Organizational hierarchy: Team → Project → Environment → Resources.
- **Proxy** — Traefik reverse proxy managed per server.
### Frontend
- Livewire 3 components with Alpine.js for client-side interactivity
- Blade templates in `resources/views/livewire/`
- Tailwind CSS v4 with `@tailwindcss/forms` and `@tailwindcss/typography`
- Vite for asset bundling
### Laravel 10 Structure (NOT Laravel 11+ slim structure)
- 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/`
## 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
- 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. 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
- Main branch: `v4.x`
- Development branch: `next`
- PRs should target `v4.x`
<laravel-boost-guidelines>
=== foundation rules ===
# Laravel Boost Guidelines
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to ensure the best experience when building Laravel applications.
## 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.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
- laravel/telescope (TELESCOPE) - v5
- pestphp/pest (PEST) - v4
- phpunit/phpunit (PHPUNIT) - v12
- rector/rector (RECTOR) - v2
- laravel-echo (ECHO) - v2
- tailwindcss (TAILWINDCSS) - v4
- vue (VUE) - v3
## 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.
- `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
- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming.
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
- Check for existing components to reuse before writing a new one.
## Verification Scripts
- Do not create verification scripts or tinker when tests cover that functionality and prove they work. Unit and feature tests are more important.
## Application Structure & Architecture
- Stick to existing directory structure; don't create new base folders without approval.
- Do not change the application's dependencies without approval.
## Frontend Bundling
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them.
## Documentation Files
- You must only create documentation files if explicitly requested by the user.
## Replies
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
=== boost rules ===
# Laravel Boost
## 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
- 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.
## Tinker
- 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.
- 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 ===
# Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test --compact` with a specific filename or filter.
=== laravel/core rules ===
# 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 `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.
### Model Creation
- 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
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
## URL Generation
- When generating links to other pages, prefer named routes and the `route()` function.
## 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.
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
## Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.
=== laravel/v12 rules ===
# Laravel 12
- CRITICAL: ALWAYS use `search-docs` tool for version-specific Laravel documentation and updated code examples.
- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel file structure.
- This is perfectly fine and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the new Laravel structure unless the user explicitly requests it.
## Laravel 10 Structure
- Middleware typically lives in `app/Http/Middleware/` and service providers in `app/Providers/`.
- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure:
- Middleware registration happens in `app/Http/Kernel.php`
- Exception handling is in `app/Exceptions/Handler.php`
- Console commands and schedule register in `app/Console/Kernel.php`
- Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php`
## Database
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
### Models
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
=== livewire/core rules ===
# Livewire
- 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
- 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 ===
## 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.
</laravel-boost-guidelines>

1
CLAUDE.md Symbolic link
View file

@ -0,0 +1 @@
AGENTS.md

View file

@ -5,6 +5,7 @@
use App\Models\Subscription; use App\Models\Subscription;
use App\Models\User; use App\Models\User;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Stripe\Exception\InvalidRequestException;
use Stripe\StripeClient; use Stripe\StripeClient;
class CancelSubscription class CancelSubscription
@ -21,7 +22,7 @@ public function __construct(User $user, bool $isDryRun = false)
$this->isDryRun = $isDryRun; $this->isDryRun = $isDryRun;
if (! $isDryRun && isCloud()) { if (! $isDryRun && isCloud()) {
$this->stripe = new StripeClient(config('subscription.stripe_api_key')); $this->stripe = app(StripeClient::class);
} }
} }
@ -64,7 +65,7 @@ public function verifySubscriptionsInStripe(): array
]; ];
} }
$stripe = new StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
$subscriptions = $this->getSubscriptionsPreview(); $subscriptions = $this->getSubscriptionsPreview();
$verified = collect(); $verified = collect();
@ -88,7 +89,7 @@ public function verifySubscriptionsInStripe(): array
'reason' => "Status in Stripe: {$stripeSubscription->status}", 'reason' => "Status in Stripe: {$stripeSubscription->status}",
]); ]);
} }
} catch (\Stripe\Exception\InvalidRequestException $e) { } catch (InvalidRequestException $e) {
// Subscription doesn't exist in Stripe // Subscription doesn't exist in Stripe
$notFound->push([ $notFound->push([
'subscription' => $subscription, 'subscription' => $subscription,
@ -181,7 +182,7 @@ public static function cancelById(string $subscriptionId): bool
return false; return false;
} }
$stripe = new StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
$stripe->subscriptions->cancel($subscriptionId, []); $stripe->subscriptions->cancel($subscriptionId, []);
// Update local record if exists // Update local record if exists

View file

@ -3,6 +3,7 @@
namespace App\Actions\Stripe; namespace App\Actions\Stripe;
use App\Models\Team; use App\Models\Team;
use Stripe\Exception\InvalidRequestException;
use Stripe\StripeClient; use Stripe\StripeClient;
class CancelSubscriptionAtPeriodEnd class CancelSubscriptionAtPeriodEnd
@ -11,7 +12,7 @@ class CancelSubscriptionAtPeriodEnd
public function __construct(?StripeClient $stripe = null) public function __construct(?StripeClient $stripe = null)
{ {
$this->stripe = $stripe ?? new StripeClient(config('subscription.stripe_api_key')); $this->stripe = $stripe ?? app(StripeClient::class);
} }
/** /**
@ -47,7 +48,7 @@ public function execute(Team $team): array
\Log::info("Subscription {$subscription->stripe_subscription_id} set to cancel at period end for team {$team->name}"); \Log::info("Subscription {$subscription->stripe_subscription_id} set to cancel at period end for team {$team->name}");
return ['success' => true, 'error' => null]; return ['success' => true, 'error' => null];
} catch (\Stripe\Exception\InvalidRequestException $e) { } catch (InvalidRequestException $e) {
\Log::error("Stripe cancel at period end error for team {$team->id}: ".$e->getMessage()); \Log::error("Stripe cancel at period end error for team {$team->id}: ".$e->getMessage());
return ['success' => false, 'error' => 'Stripe error: '.$e->getMessage()]; return ['success' => false, 'error' => 'Stripe error: '.$e->getMessage()];

View file

@ -3,6 +3,8 @@
namespace App\Actions\Stripe; namespace App\Actions\Stripe;
use App\Models\Team; use App\Models\Team;
use Carbon\Carbon;
use Stripe\Exception\InvalidRequestException;
use Stripe\StripeClient; use Stripe\StripeClient;
class RefundSubscription class RefundSubscription
@ -13,7 +15,7 @@ class RefundSubscription
public function __construct(?StripeClient $stripe = null) public function __construct(?StripeClient $stripe = null)
{ {
$this->stripe = $stripe ?? new StripeClient(config('subscription.stripe_api_key')); $this->stripe = $stripe ?? app(StripeClient::class);
} }
/** /**
@ -39,7 +41,7 @@ public function checkEligibility(Team $team): array
try { try {
$stripeSubscription = $this->stripe->subscriptions->retrieve($subscription->stripe_subscription_id); $stripeSubscription = $this->stripe->subscriptions->retrieve($subscription->stripe_subscription_id);
} catch (\Stripe\Exception\InvalidRequestException $e) { } catch (InvalidRequestException $e) {
return $this->ineligible('Subscription not found in Stripe.'); return $this->ineligible('Subscription not found in Stripe.');
} }
@ -49,7 +51,7 @@ public function checkEligibility(Team $team): array
return $this->ineligible("Subscription status is '{$stripeSubscription->status}'.", $currentPeriodEnd); return $this->ineligible("Subscription status is '{$stripeSubscription->status}'.", $currentPeriodEnd);
} }
$startDate = \Carbon\Carbon::createFromTimestamp($stripeSubscription->start_date); $startDate = Carbon::createFromTimestamp($stripeSubscription->start_date);
$daysSinceStart = (int) $startDate->diffInDays(now()); $daysSinceStart = (int) $startDate->diffInDays(now());
$daysRemaining = self::REFUND_WINDOW_DAYS - $daysSinceStart; $daysRemaining = self::REFUND_WINDOW_DAYS - $daysSinceStart;
@ -130,7 +132,7 @@ public function execute(Team $team): array
\Log::info("Refunded and cancelled subscription {$subscription->stripe_subscription_id} for team {$team->name}"); \Log::info("Refunded and cancelled subscription {$subscription->stripe_subscription_id} for team {$team->name}");
return ['success' => true, 'error' => null]; return ['success' => true, 'error' => null];
} catch (\Stripe\Exception\InvalidRequestException $e) { } catch (InvalidRequestException $e) {
\Log::error("Stripe refund error for team {$team->id}: ".$e->getMessage()); \Log::error("Stripe refund error for team {$team->id}: ".$e->getMessage());
return ['success' => false, 'error' => 'Stripe error: '.$e->getMessage()]; return ['success' => false, 'error' => 'Stripe error: '.$e->getMessage()];

View file

@ -3,6 +3,7 @@
namespace App\Actions\Stripe; namespace App\Actions\Stripe;
use App\Models\Team; use App\Models\Team;
use Stripe\Exception\InvalidRequestException;
use Stripe\StripeClient; use Stripe\StripeClient;
class ResumeSubscription class ResumeSubscription
@ -11,7 +12,7 @@ class ResumeSubscription
public function __construct(?StripeClient $stripe = null) public function __construct(?StripeClient $stripe = null)
{ {
$this->stripe = $stripe ?? new StripeClient(config('subscription.stripe_api_key')); $this->stripe = $stripe ?? app(StripeClient::class);
} }
/** /**
@ -43,7 +44,7 @@ public function execute(Team $team): array
\Log::info("Subscription {$subscription->stripe_subscription_id} resumed for team {$team->name}"); \Log::info("Subscription {$subscription->stripe_subscription_id} resumed for team {$team->name}");
return ['success' => true, 'error' => null]; return ['success' => true, 'error' => null];
} catch (\Stripe\Exception\InvalidRequestException $e) { } catch (InvalidRequestException $e) {
\Log::error("Stripe resume subscription error for team {$team->id}: ".$e->getMessage()); \Log::error("Stripe resume subscription error for team {$team->id}: ".$e->getMessage());
return ['success' => false, 'error' => 'Stripe error: '.$e->getMessage()]; return ['success' => false, 'error' => 'Stripe error: '.$e->getMessage()];

View file

@ -17,7 +17,7 @@ class UpdateSubscriptionQuantity
public function __construct(?StripeClient $stripe = null) public function __construct(?StripeClient $stripe = null)
{ {
$this->stripe = $stripe ?? new StripeClient(config('subscription.stripe_api_key')); $this->stripe = $stripe ?? app(StripeClient::class);
} }
/** /**

View file

@ -4,6 +4,8 @@
use App\Models\Team; use App\Models\Team;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Stripe\Exception\InvalidRequestException;
use Stripe\StripeClient;
class CloudFixSubscription extends Command class CloudFixSubscription extends Command
{ {
@ -31,7 +33,7 @@ class CloudFixSubscription extends Command
*/ */
public function handle() public function handle()
{ {
$stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
if ($this->option('verify-all')) { if ($this->option('verify-all')) {
return $this->verifyAllActiveSubscriptions($stripe); return $this->verifyAllActiveSubscriptions($stripe);
@ -111,7 +113,7 @@ public function handle()
/** /**
* Fix canceled subscriptions in the database * Fix canceled subscriptions in the database
*/ */
private function fixCanceledSubscriptions(\Stripe\StripeClient $stripe) private function fixCanceledSubscriptions(StripeClient $stripe)
{ {
$isDryRun = $this->option('dry-run'); $isDryRun = $this->option('dry-run');
$checkOne = $this->option('one'); $checkOne = $this->option('one');
@ -220,7 +222,7 @@ private function fixCanceledSubscriptions(\Stripe\StripeClient $stripe)
break; break;
} }
} }
} catch (\Stripe\Exception\InvalidRequestException $e) { } catch (InvalidRequestException $e) {
if ($e->getStripeCode() === 'resource_missing') { if ($e->getStripeCode() === 'resource_missing') {
$toFixCount++; $toFixCount++;
@ -326,7 +328,7 @@ private function fixCanceledSubscriptions(\Stripe\StripeClient $stripe)
/** /**
* Verify all active subscriptions against Stripe API * Verify all active subscriptions against Stripe API
*/ */
private function verifyAllActiveSubscriptions(\Stripe\StripeClient $stripe) private function verifyAllActiveSubscriptions(StripeClient $stripe)
{ {
$isDryRun = $this->option('dry-run'); $isDryRun = $this->option('dry-run');
$shouldFix = $this->option('fix-verified'); $shouldFix = $this->option('fix-verified');
@ -570,7 +572,7 @@ private function verifyAllActiveSubscriptions(\Stripe\StripeClient $stripe)
break; break;
} }
} catch (\Stripe\Exception\InvalidRequestException $e) { } catch (InvalidRequestException $e) {
$this->error(' → Error: '.$e->getMessage()); $this->error(' → Error: '.$e->getMessage());
if ($e->getStripeCode() === 'resource_missing' || $e->getHttpStatus() === 404) { if ($e->getStripeCode() === 'resource_missing' || $e->getHttpStatus() === 404) {
@ -730,7 +732,7 @@ private function fixSubscription($team, $subscription, $status)
/** /**
* Search for subscriptions by customer ID * Search for subscriptions by customer ID
*/ */
private function searchSubscriptionsByCustomer(\Stripe\StripeClient $stripe, $customerId, $requireActive = false) private function searchSubscriptionsByCustomer(StripeClient $stripe, $customerId, $requireActive = false)
{ {
try { try {
$subscriptions = $stripe->subscriptions->all([ $subscriptions = $stripe->subscriptions->all([
@ -770,7 +772,7 @@ private function searchSubscriptionsByCustomer(\Stripe\StripeClient $stripe, $cu
/** /**
* Search for subscriptions by team member emails * Search for subscriptions by team member emails
*/ */
private function searchSubscriptionsByEmails(\Stripe\StripeClient $stripe, $emails) private function searchSubscriptionsByEmails(StripeClient $stripe, $emails)
{ {
$this->line(' → Searching by team member emails...'); $this->line(' → Searching by team member emails...');

View file

@ -18,6 +18,7 @@
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Mail\Message; use Illuminate\Mail\Message;
use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Str;
use Mail; use Mail;
use function Laravel\Prompts\confirm; use function Laravel\Prompts\confirm;

View file

@ -4,6 +4,7 @@
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Process;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
class Services extends Command class Services extends Command
@ -77,6 +78,7 @@ private function processFile(string $file): false|array
'category' => $data->get('category'), 'category' => $data->get('category'),
'logo' => $data->get('logo', 'svgs/default.webp'), 'logo' => $data->get('logo', 'svgs/default.webp'),
'minversion' => $data->get('minversion', '0.0.0'), 'minversion' => $data->get('minversion', '0.0.0'),
'template_last_updated_at' => $this->templateLastUpdatedAt($file),
]; ];
if ($port = $data->get('port')) { if ($port = $data->get('port')) {
@ -99,6 +101,26 @@ private function processFile(string $file): false|array
return $payload; return $payload;
} }
private function templateLastUpdatedAt(string $file): ?string
{
$process = Process::path(base_path())->run([
'git',
'log',
'-1',
'--format=%cI',
'--',
"templates/compose/{$file}",
]);
if ($process->failed()) {
return null;
}
$timestamp = trim($process->output());
return $timestamp === '' ? null : $timestamp;
}
private function generateServiceTemplatesWithFqdn(): void private function generateServiceTemplatesWithFqdn(): void
{ {
$serviceTemplatesWithFqdn = collect(array_merge( $serviceTemplatesWithFqdn = collect(array_merge(
@ -155,6 +177,7 @@ private function processFileWithFqdn(string $file): false|array
'category' => $data->get('category'), 'category' => $data->get('category'),
'logo' => $data->get('logo', 'svgs/default.webp'), 'logo' => $data->get('logo', 'svgs/default.webp'),
'minversion' => $data->get('minversion', '0.0.0'), 'minversion' => $data->get('minversion', '0.0.0'),
'template_last_updated_at' => $this->templateLastUpdatedAt($file),
]; ];
if ($port = $data->get('port')) { if ($port = $data->get('port')) {
@ -232,6 +255,7 @@ private function processFileWithFqdnRaw(string $file): false|array
'category' => $data->get('category'), 'category' => $data->get('category'),
'logo' => $data->get('logo', 'svgs/default.webp'), 'logo' => $data->get('logo', 'svgs/default.webp'),
'minversion' => $data->get('minversion', '0.0.0'), 'minversion' => $data->get('minversion', '0.0.0'),
'template_last_updated_at' => $this->templateLastUpdatedAt($file),
]; ];
if ($port = $data->get('port')) { if ($port = $data->get('port')) {

View file

@ -30,7 +30,6 @@
use OpenApi\Attributes as OA; use OpenApi\Attributes as OA;
use Spatie\Url\Url; use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
use Visus\Cuid2\Cuid2;
class ApplicationsController extends Controller class ApplicationsController extends Controller
{ {
@ -59,6 +58,10 @@ private function removeSensitiveData($application)
]); ]);
} }
if ($application->is_shown_once ?? false) {
$application->makeHidden(['value', 'real_value']);
}
return serializeApiResponse($application); return serializeApiResponse($application);
} }
@ -1193,7 +1196,7 @@ private function create_application(Request $request, $type)
$application->isConfigurationChanged(true); $application->isConfigurationChanged(true);
if ($instantDeploy) { if ($instantDeploy) {
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
@ -1432,7 +1435,7 @@ private function create_application(Request $request, $type)
$application->isConfigurationChanged(true); $application->isConfigurationChanged(true);
if ($instantDeploy) { if ($instantDeploy) {
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
@ -1641,7 +1644,7 @@ private function create_application(Request $request, $type)
$application->isConfigurationChanged(true); $application->isConfigurationChanged(true);
if ($instantDeploy) { if ($instantDeploy) {
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
@ -1687,7 +1690,7 @@ private function create_application(Request $request, $type)
], 422); ], 422);
} }
if (! $request->has('name')) { if (! $request->has('name')) {
$request->offsetSet('name', 'dockerfile-'.new Cuid2); $request->offsetSet('name', 'dockerfile-'.new_public_id());
} }
$return = $this->validateDataApplications($request, $server); $return = $this->validateDataApplications($request, $server);
@ -1761,7 +1764,7 @@ private function create_application(Request $request, $type)
$application->isConfigurationChanged(true); $application->isConfigurationChanged(true);
if ($instantDeploy) { if ($instantDeploy) {
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
@ -1805,7 +1808,7 @@ private function create_application(Request $request, $type)
], 422); ], 422);
} }
if (! $request->has('name')) { if (! $request->has('name')) {
$request->offsetSet('name', 'docker-image-'.new Cuid2); $request->offsetSet('name', 'docker-image-'.new_public_id());
} }
$return = $this->validateDataApplications($request, $server); $return = $this->validateDataApplications($request, $server);
if ($return instanceof JsonResponse) { if ($return instanceof JsonResponse) {
@ -1880,7 +1883,7 @@ private function create_application(Request $request, $type)
$application->isConfigurationChanged(true); $application->isConfigurationChanged(true);
if ($instantDeploy) { if ($instantDeploy) {
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
@ -2678,7 +2681,7 @@ public function update_by_uuid(Request $request)
]); ]);
if ($instantDeploy) { if ($instantDeploy) {
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
@ -2873,8 +2876,12 @@ public function update_env_by_uuid(Request $request)
$this->authorize('manageEnvironment', $application); $this->authorize('manageEnvironment', $application);
if ($request->has('key')) {
$request->merge(['key' => ValidationPatterns::normalizeEnvironmentVariableKey((string) $request->key)]);
}
$validator = customApiValidator($request->all(), [ $validator = customApiValidator($request->all(), [
'key' => 'string|required', 'key' => ValidationPatterns::environmentVariableKeyRules(),
'value' => 'string|nullable', 'value' => 'string|nullable',
'is_preview' => 'boolean', 'is_preview' => 'boolean',
'is_literal' => 'boolean', 'is_literal' => 'boolean',
@ -3097,12 +3104,18 @@ public function create_bulk_envs(Request $request)
], 400); ], 400);
} }
$bulk_data = collect($bulk_data)->map(function ($item) { $bulk_data = collect($bulk_data)->map(function ($item) {
return collect($item)->only(['key', 'value', 'is_preview', 'is_literal', 'is_multiline', 'is_shown_once', 'is_runtime', 'is_buildtime', 'comment']); $item = collect($item)->only(['key', 'value', 'is_preview', 'is_literal', 'is_multiline', 'is_shown_once', 'is_runtime', 'is_buildtime', 'comment']);
if ($item->has('key')) {
$item->put('key', ValidationPatterns::normalizeEnvironmentVariableKey((string) $item->get('key')));
}
return $item;
}); });
$returnedEnvs = collect(); $returnedEnvs = collect();
foreach ($bulk_data as $item) { foreach ($bulk_data as $item) {
$validator = customApiValidator($item, [ $validator = customApiValidator($item, [
'key' => 'string|required', 'key' => ValidationPatterns::environmentVariableKeyRules(),
'value' => 'string|nullable', 'value' => 'string|nullable',
'is_preview' => 'boolean', 'is_preview' => 'boolean',
'is_literal' => 'boolean', 'is_literal' => 'boolean',
@ -3299,8 +3312,12 @@ public function create_env(Request $request)
$this->authorize('manageEnvironment', $application); $this->authorize('manageEnvironment', $application);
if ($request->has('key')) {
$request->merge(['key' => ValidationPatterns::normalizeEnvironmentVariableKey((string) $request->key)]);
}
$validator = customApiValidator($request->all(), [ $validator = customApiValidator($request->all(), [
'key' => 'string|required', 'key' => ValidationPatterns::environmentVariableKeyRules(),
'value' => 'string|nullable', 'value' => 'string|nullable',
'is_preview' => 'boolean', 'is_preview' => 'boolean',
'is_literal' => 'boolean', 'is_literal' => 'boolean',
@ -3585,7 +3602,7 @@ public function action_deploy(Request $request)
$this->authorize('deploy', $application); $this->authorize('deploy', $application);
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
@ -3783,7 +3800,7 @@ public function action_restart(Request $request)
$this->authorize('deploy', $application); $this->authorize('deploy', $application);
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,

View file

@ -177,6 +177,7 @@ public function show(Request $request)
if (is_null($token)) { if (is_null($token)) {
return response()->json(['message' => 'Cloud provider token not found.'], 404); return response()->json(['message' => 'Cloud provider token not found.'], 404);
} }
$this->authorize('view', $token);
return response()->json($this->removeSensitiveData($token)); return response()->json($this->removeSensitiveData($token));
} }
@ -243,6 +244,7 @@ public function store(Request $request)
if (is_null($teamId)) { if (is_null($teamId)) {
return invalidTokenResponse(); return invalidTokenResponse();
} }
$this->authorize('create', [CloudProviderToken::class]);
$return = validateIncomingRequest($request); $return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) { if ($return instanceof JsonResponse) {
@ -394,6 +396,7 @@ public function update(Request $request)
if (! $token) { if (! $token) {
return response()->json(['message' => 'Cloud provider token not found.'], 404); return response()->json(['message' => 'Cloud provider token not found.'], 404);
} }
$this->authorize('update', $token);
$token->update(array_intersect_key($body, array_flip($allowedFields))); $token->update(array_intersect_key($body, array_flip($allowedFields)));
@ -475,6 +478,7 @@ public function destroy(Request $request)
if (! $token) { if (! $token) {
return response()->json(['message' => 'Cloud provider token not found.'], 404); return response()->json(['message' => 'Cloud provider token not found.'], 404);
} }
$this->authorize('delete', $token);
if ($token->hasServers()) { if ($token->hasServers()) {
return response()->json(['message' => 'Cannot delete token that is used by servers.'], 400); return response()->json(['message' => 'Cannot delete token that is used by servers.'], 400);
@ -545,9 +549,18 @@ public function validateToken(Request $request)
if (! $cloudToken) { if (! $cloudToken) {
return response()->json(['message' => 'Cloud provider token not found.'], 404); return response()->json(['message' => 'Cloud provider token not found.'], 404);
} }
$this->authorize('view', $cloudToken);
$validation = $this->validateProviderToken($cloudToken->provider, $cloudToken->token); $validation = $this->validateProviderToken($cloudToken->provider, $cloudToken->token);
auditLog('api.cloud_token.validated', [
'team_id' => $teamId,
'cloud_token_uuid' => $cloudToken->uuid,
'cloud_token_name' => $cloudToken->name,
'provider' => $cloudToken->provider,
'valid' => $validation['valid'],
]);
return response()->json([ return response()->json([
'valid' => $validation['valid'], 'valid' => $validation['valid'],
'message' => $validation['valid'] ? 'Token is valid.' : $validation['error'], 'message' => $validation['valid'] ? 'Token is valid.' : $validation['error'],

View file

@ -3133,8 +3133,12 @@ public function update_env_by_uuid(Request $request)
$this->authorize('manageEnvironment', $database); $this->authorize('manageEnvironment', $database);
if ($request->has('key')) {
$request->merge(['key' => ValidationPatterns::normalizeEnvironmentVariableKey((string) $request->key)]);
}
$validator = customApiValidator($request->all(), [ $validator = customApiValidator($request->all(), [
'key' => 'string|required', 'key' => ValidationPatterns::environmentVariableKeyRules(),
'value' => 'string|nullable', 'value' => 'string|nullable',
'is_literal' => 'boolean', 'is_literal' => 'boolean',
'is_multiline' => 'boolean', 'is_multiline' => 'boolean',
@ -3281,8 +3285,12 @@ public function create_bulk_envs(Request $request)
$updatedEnvs = collect(); $updatedEnvs = collect();
foreach ($bulk_data as $item) { foreach ($bulk_data as $item) {
if (array_key_exists('key', $item)) {
$item['key'] = ValidationPatterns::normalizeEnvironmentVariableKey((string) $item['key']);
}
$validator = customApiValidator($item, [ $validator = customApiValidator($item, [
'key' => 'string|required', 'key' => ValidationPatterns::environmentVariableKeyRules(),
'value' => 'string|nullable', 'value' => 'string|nullable',
'is_literal' => 'boolean', 'is_literal' => 'boolean',
'is_multiline' => 'boolean', 'is_multiline' => 'boolean',
@ -3399,8 +3407,12 @@ public function create_env(Request $request)
$this->authorize('manageEnvironment', $database); $this->authorize('manageEnvironment', $database);
if ($request->has('key')) {
$request->merge(['key' => ValidationPatterns::normalizeEnvironmentVariableKey((string) $request->key)]);
}
$validator = customApiValidator($request->all(), [ $validator = customApiValidator($request->all(), [
'key' => 'string|required', 'key' => ValidationPatterns::environmentVariableKeyRules(),
'value' => 'string|nullable', 'value' => 'string|nullable',
'is_literal' => 'boolean', 'is_literal' => 'boolean',
'is_multiline' => 'boolean', 'is_multiline' => 'boolean',

View file

@ -15,7 +15,6 @@
use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use OpenApi\Attributes as OA; use OpenApi\Attributes as OA;
use Visus\Cuid2\Cuid2;
class DeployController extends Controller class DeployController extends Controller
{ {
@ -511,7 +510,7 @@ public function deploy_resource($resource, bool $force = false, int $pr = 0, ?st
if ($dockerTag !== null && $resource->build_pack !== 'dockerimage') { if ($dockerTag !== null && $resource->build_pack !== 'dockerimage') {
return ['message' => 'docker_tag can only be used with Docker Image applications.', 'deployment_uuid' => null]; return ['message' => 'docker_tag can only be used with Docker Image applications.', 'deployment_uuid' => null];
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $resource, application: $resource,
deployment_uuid: $deployment_uuid, deployment_uuid: $deployment_uuid,

View file

@ -183,6 +183,7 @@ public function create_github_app(Request $request)
if (is_null($teamId)) { if (is_null($teamId)) {
return invalidTokenResponse(); return invalidTokenResponse();
} }
$this->authorize('create', [GithubApp::class]);
$return = validateIncomingRequest($request); $return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) { if ($return instanceof JsonResponse) {
return $return; return $return;
@ -564,6 +565,7 @@ public function update_github_app(Request $request, $github_app_id)
$githubApp = GithubApp::where('id', $github_app_id) $githubApp = GithubApp::where('id', $github_app_id)
->where('team_id', $teamId) ->where('team_id', $teamId)
->firstOrFail(); ->firstOrFail();
$this->authorize('update', $githubApp);
// Define allowed fields for update // Define allowed fields for update
$allowedFields = [ $allowedFields = [
@ -737,6 +739,7 @@ public function delete_github_app($github_app_id)
$githubApp = GithubApp::where('id', $github_app_id) $githubApp = GithubApp::where('id', $github_app_id)
->where('team_id', $teamId) ->where('team_id', $teamId)
->firstOrFail(); ->firstOrFail();
$this->authorize('delete', $githubApp);
// Check if the GitHub app is being used by any applications // Check if the GitHub app is being used by any applications
if ($githubApp->applications->isNotEmpty()) { if ($githubApp->applications->isNotEmpty()) {

View file

@ -116,6 +116,7 @@ public function locations(Request $request)
if (! $token) { if (! $token) {
return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404); return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404);
} }
$this->authorize('view', $token);
try { try {
$hetznerService = new HetznerService($token->token); $hetznerService = new HetznerService($token->token);
@ -237,6 +238,7 @@ public function serverTypes(Request $request)
if (! $token) { if (! $token) {
return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404); return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404);
} }
$this->authorize('view', $token);
try { try {
$hetznerService = new HetznerService($token->token); $hetznerService = new HetznerService($token->token);
@ -336,6 +338,7 @@ public function images(Request $request)
if (! $token) { if (! $token) {
return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404); return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404);
} }
$this->authorize('view', $token);
try { try {
$hetznerService = new HetznerService($token->token); $hetznerService = new HetznerService($token->token);
@ -445,6 +448,7 @@ public function sshKeys(Request $request)
if (! $token) { if (! $token) {
return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404); return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404);
} }
$this->authorize('view', $token);
try { try {
$hetznerService = new HetznerService($token->token); $hetznerService = new HetznerService($token->token);
@ -550,6 +554,7 @@ public function createServer(Request $request)
if (is_null($teamId)) { if (is_null($teamId)) {
return invalidTokenResponse(); return invalidTokenResponse();
} }
$this->authorize('create', [Server::class]);
$return = validateIncomingRequest($request); $return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) { if ($return instanceof JsonResponse) {
@ -620,6 +625,7 @@ public function createServer(Request $request)
if (! $token) { if (! $token) {
return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404); return response()->json(['message' => 'Hetzner cloud provider token not found.'], 404);
} }
$this->authorize('view', $token);
// Validate private key // Validate private key
$privateKey = PrivateKey::whereTeamId($teamId)->whereUuid($request->private_key_uuid)->first(); $privateKey = PrivateKey::whereTeamId($teamId)->whereUuid($request->private_key_uuid)->first();

View file

@ -97,6 +97,7 @@ public function project_by_uuid(Request $request)
if (! $project) { if (! $project) {
return response()->json(['message' => 'Project not found.'], 404); return response()->json(['message' => 'Project not found.'], 404);
} }
$this->authorize('view', $project);
$project->load(['environments']); $project->load(['environments']);
@ -233,6 +234,7 @@ public function create_project(Request $request)
if (is_null($teamId)) { if (is_null($teamId)) {
return invalidTokenResponse(); return invalidTokenResponse();
} }
$this->authorize('create', [Project::class]);
$return = validateIncomingRequest($request); $return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) { if ($return instanceof JsonResponse) {
@ -385,6 +387,7 @@ public function update_project(Request $request)
if (! $project) { if (! $project) {
return response()->json(['message' => 'Project not found.'], 404); return response()->json(['message' => 'Project not found.'], 404);
} }
$this->authorize('update', $project);
$project->update($request->only($allowedFields)); $project->update($request->only($allowedFields));
@ -469,6 +472,7 @@ public function delete_project(Request $request)
if (! $project) { if (! $project) {
return response()->json(['message' => 'Project not found.'], 404); return response()->json(['message' => 'Project not found.'], 404);
} }
$this->authorize('delete', $project);
if (! $project->isEmpty()) { if (! $project->isEmpty()) {
return response()->json(['message' => 'Project has resources, so it cannot be deleted.'], 400); return response()->json(['message' => 'Project has resources, so it cannot be deleted.'], 400);
} }
@ -652,6 +656,7 @@ public function create_environment(Request $request)
if (! $project) { if (! $project) {
return response()->json(['message' => 'Project not found.'], 404); return response()->json(['message' => 'Project not found.'], 404);
} }
$this->authorize('update', $project);
$existingEnvironment = $project->environments()->where('name', $request->name)->first(); $existingEnvironment = $project->environments()->where('name', $request->name)->first();
if ($existingEnvironment) { if ($existingEnvironment) {
@ -746,6 +751,7 @@ public function delete_environment(Request $request)
if (! $environment) { if (! $environment) {
return response()->json(['message' => 'Environment not found.'], 404); return response()->json(['message' => 'Environment not found.'], 404);
} }
$this->authorize('delete', $environment);
if (! $environment->isEmpty()) { if (! $environment->isEmpty()) {
return response()->json(['message' => 'Environment has resources, so it cannot be deleted.'], 400); return response()->json(['message' => 'Environment has resources, so it cannot be deleted.'], 400);

View file

@ -110,6 +110,7 @@ public function key_by_uuid(Request $request)
'message' => 'Private Key not found.', 'message' => 'Private Key not found.',
], 404); ], 404);
} }
$this->authorize('view', $key);
return response()->json($this->removeSensitiveData($key)); return response()->json($this->removeSensitiveData($key));
} }
@ -176,6 +177,7 @@ public function create_key(Request $request)
if (is_null($teamId)) { if (is_null($teamId)) {
return invalidTokenResponse(); return invalidTokenResponse();
} }
$this->authorize('create', [PrivateKey::class]);
$return = validateIncomingRequest($request); $return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) { if ($return instanceof JsonResponse) {
return $return; return $return;
@ -338,6 +340,7 @@ public function update_key(Request $request)
'message' => 'Private Key not found.', 'message' => 'Private Key not found.',
], 404); ], 404);
} }
$this->authorize('update', $foundKey);
$foundKey->update($request->only($allowedFields)); $foundKey->update($request->only($allowedFields));
auditLog('api.private_key.updated', [ auditLog('api.private_key.updated', [
@ -421,6 +424,7 @@ public function delete_key(Request $request)
if (is_null($key)) { if (is_null($key)) {
return response()->json(['message' => 'Private Key not found.'], 404); return response()->json(['message' => 'Private Key not found.'], 404);
} }
$this->authorize('delete', $key);
if ($key->isInUse()) { if ($key->isInUse()) {
return response()->json([ return response()->json([

View file

@ -97,12 +97,12 @@ public function push(Request $request)
if ($this->shouldDispatchUpdate($server, $data)) { if ($this->shouldDispatchUpdate($server, $data)) {
PushServerUpdateJob::dispatch($server, $data); PushServerUpdateJob::dispatch($server, $data);
}
auditLog('sentinel.metrics_pushed', [ auditLog('sentinel.metrics_pushed', [
'server_uuid' => $server->uuid, 'server_uuid' => $server->uuid,
'team_id' => $server->team_id, 'team_id' => $server->team_id,
]); ]);
}
return response()->json(['message' => 'ok'], 200); return response()->json(['message' => 'ok'], 200);
} }

View file

@ -148,6 +148,7 @@ public function server_by_uuid(Request $request)
if (is_null($server)) { if (is_null($server)) {
return response()->json(['message' => 'Server not found.'], 404); return response()->json(['message' => 'Server not found.'], 404);
} }
$this->authorize('view', $server);
if ($with_resources) { if ($with_resources) {
$server['resources'] = $server->definedResources()->map(function ($resource) { $server['resources'] = $server->definedResources()->map(function ($resource) {
$payload = [ $payload = [
@ -477,6 +478,7 @@ public function create_server(Request $request)
if (is_null($teamId)) { if (is_null($teamId)) {
return invalidTokenResponse(); return invalidTokenResponse();
} }
$this->authorize('create', [ModelsServer::class]);
$return = validateIncomingRequest($request); $return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) { if ($return instanceof JsonResponse) {
@ -701,6 +703,7 @@ public function update_server(Request $request)
if (! $server) { if (! $server) {
return response()->json(['message' => 'Server not found.'], 404); return response()->json(['message' => 'Server not found.'], 404);
} }
$this->authorize('update', $server);
if ($request->proxy_type) { if ($request->proxy_type) {
$validProxyTypes = collect(ProxyTypes::cases())->map(function ($proxyType) { $validProxyTypes = collect(ProxyTypes::cases())->map(function ($proxyType) {
return str($proxyType->value)->lower(); return str($proxyType->value)->lower();
@ -825,6 +828,7 @@ public function delete_server(Request $request)
if (! $server) { if (! $server) {
return response()->json(['message' => 'Server not found.'], 404); return response()->json(['message' => 'Server not found.'], 404);
} }
$this->authorize('delete', $server);
$force = filter_var($request->query('force', false), FILTER_VALIDATE_BOOLEAN); $force = filter_var($request->query('force', false), FILTER_VALIDATE_BOOLEAN);
@ -924,6 +928,7 @@ public function validate_server(Request $request)
if (! $server) { if (! $server) {
return response()->json(['message' => 'Server not found.'], 404); return response()->json(['message' => 'Server not found.'], 404);
} }
$this->authorize('update', $server);
ValidateServer::dispatch($server); ValidateServer::dispatch($server);
auditLog('api.server.validated', [ auditLog('api.server.validated', [

View file

@ -39,6 +39,10 @@ private function removeSensitiveData($service)
]); ]);
} }
if ($service->is_shown_once ?? false) {
$service->makeHidden(['value', 'real_value']);
}
return serializeApiResponse($service); return serializeApiResponse($service);
} }
@ -1247,8 +1251,12 @@ public function update_env_by_uuid(Request $request)
$this->authorize('manageEnvironment', $service); $this->authorize('manageEnvironment', $service);
if ($request->has('key')) {
$request->merge(['key' => ValidationPatterns::normalizeEnvironmentVariableKey((string) $request->key)]);
}
$validator = customApiValidator($request->all(), [ $validator = customApiValidator($request->all(), [
'key' => 'string|required', 'key' => ValidationPatterns::environmentVariableKeyRules(),
'value' => 'string|nullable', 'value' => 'string|nullable',
'is_literal' => 'boolean', 'is_literal' => 'boolean',
'is_multiline' => 'boolean', 'is_multiline' => 'boolean',
@ -1396,8 +1404,12 @@ public function create_bulk_envs(Request $request)
$updatedEnvs = collect(); $updatedEnvs = collect();
foreach ($bulk_data as $item) { foreach ($bulk_data as $item) {
if (array_key_exists('key', $item)) {
$item['key'] = ValidationPatterns::normalizeEnvironmentVariableKey((string) $item['key']);
}
$validator = customApiValidator($item, [ $validator = customApiValidator($item, [
'key' => 'string|required', 'key' => ValidationPatterns::environmentVariableKeyRules(),
'value' => 'string|nullable', 'value' => 'string|nullable',
'is_literal' => 'boolean', 'is_literal' => 'boolean',
'is_multiline' => 'boolean', 'is_multiline' => 'boolean',
@ -1515,8 +1527,12 @@ public function create_env(Request $request)
$this->authorize('manageEnvironment', $service); $this->authorize('manageEnvironment', $service);
if ($request->has('key')) {
$request->merge(['key' => ValidationPatterns::normalizeEnvironmentVariableKey((string) $request->key)]);
}
$validator = customApiValidator($request->all(), [ $validator = customApiValidator($request->all(), [
'key' => 'string|required', 'key' => ValidationPatterns::environmentVariableKeyRules(),
'value' => 'string|nullable', 'value' => 'string|nullable',
'is_literal' => 'boolean', 'is_literal' => 'boolean',
'is_multiline' => 'boolean', 'is_multiline' => 'boolean',

View file

@ -110,6 +110,7 @@ public function team_by_id(Request $request)
if (is_null($team)) { if (is_null($team)) {
return response()->json(['message' => 'Team not found.'], 404); return response()->json(['message' => 'Team not found.'], 404);
} }
$this->authorize('view', $team);
$team = $this->removeSensitiveData($team); $team = $this->removeSensitiveData($team);
return response()->json( return response()->json(
@ -168,6 +169,7 @@ public function members_by_id(Request $request)
if (is_null($team)) { if (is_null($team)) {
return response()->json(['message' => 'Team not found.'], 404); return response()->json(['message' => 'Team not found.'], 404);
} }
$this->authorize('view', $team);
$members = $team->members; $members = $team->members;
$members->makeHidden([ $members->makeHidden([
'pivot', 'pivot',

View file

@ -3,6 +3,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Support\DatabaseBackupFileValidator; use App\Support\DatabaseBackupFileValidator;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
@ -12,6 +13,8 @@
class UploadController extends BaseController class UploadController extends BaseController
{ {
use AuthorizesRequests;
private const MAX_BYTES = 10 * 1024 * 1024 * 1024; // 10 GiB private const MAX_BYTES = 10 * 1024 * 1024 * 1024; // 10 GiB
private const ALLOWED_EXTENSIONS = DatabaseBackupFileValidator::ALLOWED_EXTENSIONS; private const ALLOWED_EXTENSIONS = DatabaseBackupFileValidator::ALLOWED_EXTENSIONS;
@ -24,6 +27,8 @@ public function upload(Request $request)
return response()->json(['error' => 'You do not have permission for this database'], 500); return response()->json(['error' => 'You do not have permission for this database'], 500);
} }
$this->authorize('uploadBackup', $resource);
$chunk = $request->file('file'); $chunk = $request->file('file');
$originalName = $chunk instanceof UploadedFile ? $chunk->getClientOriginalName() : null; $originalName = $chunk instanceof UploadedFile ? $chunk->getClientOriginalName() : null;
if (blank($originalName) || ! self::hasAllowedExtension($originalName)) { if (blank($originalName) || ! self::hasAllowedExtension($originalName)) {

View file

@ -10,7 +10,6 @@
use App\Models\ApplicationPreview; use App\Models\ApplicationPreview;
use Exception; use Exception;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Visus\Cuid2\Cuid2;
class Bitbucket extends Controller class Bitbucket extends Controller
{ {
@ -141,7 +140,7 @@ public function manual(Request $request)
continue; continue;
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
deployment_uuid: $deployment_uuid, deployment_uuid: $deployment_uuid,
@ -192,7 +191,7 @@ public function manual(Request $request)
continue; continue;
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first(); $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found) { if (! $found) {
if ($application->build_pack === 'dockercompose') { if ($application->build_pack === 'dockercompose') {

View file

@ -11,7 +11,6 @@
use Exception; use Exception;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Visus\Cuid2\Cuid2;
class Gitea extends Controller class Gitea extends Controller
{ {
@ -127,7 +126,7 @@ public function manual(Request $request)
continue; continue;
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
deployment_uuid: $deployment_uuid, deployment_uuid: $deployment_uuid,
@ -194,7 +193,7 @@ public function manual(Request $request)
continue; continue;
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first(); $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found) { if (! $found) {
if ($application->build_pack === 'dockercompose') { if ($application->build_pack === 'dockercompose') {

View file

@ -17,7 +17,6 @@
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Visus\Cuid2\Cuid2;
class Github extends Controller class Github extends Controller
{ {
@ -144,7 +143,7 @@ public function manual(Request $request)
continue; continue;
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
deployment_uuid: $deployment_uuid, deployment_uuid: $deployment_uuid,
@ -262,6 +261,16 @@ public function normal(Request $request)
return response('Nothing to do. No GitHub App found.'); return response('Nothing to do. No GitHub App found.');
} }
$webhook_secret = data_get($github_app, 'webhook_secret'); $webhook_secret = data_get($github_app, 'webhook_secret');
if (empty($webhook_secret)) {
auditLogWebhookFailure('github', 'webhook_secret_missing', [
'mode' => 'app',
'github_app_id' => $github_app->id,
'github_app_name' => $github_app->name,
'installation_target_id' => $x_github_hook_installation_target_id,
]);
return response('Invalid signature.');
}
$hmac = hash_hmac('sha256', $request->getContent(), $webhook_secret); $hmac = hash_hmac('sha256', $request->getContent(), $webhook_secret);
if (config('app.env') !== 'local') { if (config('app.env') !== 'local') {
if (! hash_equals($x_hub_signature_256, $hmac)) { if (! hash_equals($x_hub_signature_256, $hmac)) {
@ -362,7 +371,7 @@ public function normal(Request $request)
continue; continue;
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
deployment_uuid: $deployment_uuid, deployment_uuid: $deployment_uuid,

View file

@ -11,7 +11,6 @@
use Exception; use Exception;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Visus\Cuid2\Cuid2;
class Gitlab extends Controller class Gitlab extends Controller
{ {
@ -168,7 +167,7 @@ public function manual(Request $request)
continue; continue;
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$result = queue_application_deployment( $result = queue_application_deployment(
application: $application, application: $application,
deployment_uuid: $deployment_uuid, deployment_uuid: $deployment_uuid,
@ -236,7 +235,7 @@ public function manual(Request $request)
continue; continue;
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
$found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first(); $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found) { if (! $found) {
if ($application->build_pack === 'dockercompose') { if ($application->build_pack === 'dockercompose') {

View file

@ -7,9 +7,34 @@
class ApiAbility extends CheckForAnyAbility class ApiAbility extends CheckForAnyAbility
{ {
/**
* Permissions that only admins/owners may use.
*/
private const MEMBER_DISALLOWED_ABILITIES = [
'root',
'write',
'write:sensitive',
'deploy',
'read:sensitive',
];
public function handle($request, $next, ...$abilities) public function handle($request, $next, ...$abilities)
{ {
try { try {
$token = $request->user()->currentAccessToken();
$teamId = data_get($token, 'team_id');
if ($teamId !== null && ! $request->user()->isAdminOfTeam((int) $teamId)) {
$tokenAbilities = $token->abilities ?? [];
$disallowed = array_intersect($tokenAbilities, self::MEMBER_DISALLOWED_ABILITIES);
if (! empty($disallowed)) {
return response()->json([
'message' => 'This API token has permissions ('.implode(', ', $disallowed).') that exceed your current role as a team member. Members are restricted to read-only API access. Please revoke this token and create a new one with only read permissions.',
], 403);
}
}
if ($request->user()->tokenCan('root')) { if ($request->user()->tokenCan('root')) {
return $next($request); return $next($request);
} }

View file

@ -10,10 +10,13 @@ class ApiSensitiveData
public function handle(Request $request, Closure $next) public function handle(Request $request, Closure $next)
{ {
$token = $request->user()->currentAccessToken(); $token = $request->user()->currentAccessToken();
$hasTokenPermission = $token->can('root') || $token->can('read:sensitive');
$teamId = (int) data_get($token, 'team_id');
$isAdmin = $teamId ? $request->user()->isAdminOfTeam($teamId) : false;
// Allow access to sensitive data if token has root or read:sensitive permission // Allow access to sensitive data only if token has permission AND user is admin/owner
$request->attributes->add([ $request->attributes->add([
'can_read_sensitive' => $token->can('root') || $token->can('read:sensitive'), 'can_read_sensitive' => $hasTokenPermission && $isAdmin,
]); ]);
return $next($request); return $next($request);

View file

@ -37,7 +37,6 @@
use Spatie\Url\Url; use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
use Throwable; use Throwable;
use Visus\Cuid2\Cuid2;
class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
{ {
@ -2207,7 +2206,7 @@ private function deploy_to_additional_destinations()
continue; continue;
} }
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
queue_application_deployment( queue_application_deployment(
deployment_uuid: $deployment_uuid, deployment_uuid: $deployment_uuid,
application: $this->application, application: $this->application,
@ -2307,6 +2306,8 @@ private function check_git_if_build_needed()
], ],
[ [
executeInDocker($this->deployment_uuid, "echo '{$private_key}' | base64 -d | tee {$customSshKeyLocation} > /dev/null"), executeInDocker($this->deployment_uuid, "echo '{$private_key}' | base64 -d | tee {$customSshKeyLocation} > /dev/null"),
'hidden' => true,
'skip_command_log' => true,
], ],
[ [
executeInDocker($this->deployment_uuid, "chmod 600 {$customSshKeyLocation}"), executeInDocker($this->deployment_uuid, "chmod 600 {$customSshKeyLocation}"),
@ -2366,12 +2367,7 @@ private function clone_repository()
if ($this->pull_request_id !== 0) { if ($this->pull_request_id !== 0) {
$this->application_deployment_queue->addLogEntry("Checking out tag pull/{$this->pull_request_id}/head."); $this->application_deployment_queue->addLogEntry("Checking out tag pull/{$this->pull_request_id}/head.");
} }
$this->execute_remote_command( $this->execute_remote_command(...$this->gitCommandDefinitions($importCommands));
[
$importCommands,
'hidden' => true,
]
);
$this->create_workdir(); $this->create_workdir();
$this->execute_remote_command( $this->execute_remote_command(
[ [
@ -2401,6 +2397,39 @@ private function generate_git_import_commands()
return $commands; return $commands;
} }
private function gitCommandDefinitions(Collection|array|string $commands): array
{
if (is_string($commands)) {
return [
[
$commands,
'hidden' => true,
],
];
}
return collect($commands)
->map(function ($command): array {
if (is_string($command)) {
return [
$command,
'hidden' => true,
];
}
if (is_array($command)) {
return $command + ['hidden' => true];
}
return [
'command' => $command,
'hidden' => true,
];
})
->values()
->all();
}
private function cleanup_git() private function cleanup_git()
{ {
$this->execute_remote_command( $this->execute_remote_command(

View file

@ -27,7 +27,6 @@
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Throwable; use Throwable;
use Visus\Cuid2\Cuid2;
class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue
{ {
@ -309,7 +308,7 @@ public function handle(): void
// Generate unique UUID for each database backup execution // Generate unique UUID for each database backup execution
$attempts = 0; $attempts = 0;
do { do {
$this->backup_log_uuid = (string) new Cuid2; $this->backup_log_uuid = new_public_id();
$exists = ScheduledDatabaseBackupExecution::where('uuid', $this->backup_log_uuid)->exists(); $exists = ScheduledDatabaseBackupExecution::where('uuid', $this->backup_log_uuid)->exists();
$attempts++; $attempts++;
if ($attempts >= 3 && $exists) { if ($attempts >= 3 && $exists) {

View file

@ -14,7 +14,7 @@
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Visus\Cuid2\Cuid2; use Throwable;
class ProcessGithubPullRequestWebhook implements ShouldBeEncrypted, ShouldQueue class ProcessGithubPullRequestWebhook implements ShouldBeEncrypted, ShouldQueue
{ {
@ -71,16 +71,25 @@ private function handleClosedAction(Application $application): void
->first(); ->first();
if ($found) { if ($found) {
ApplicationPullRequestUpdateJob::dispatchSync( try {
application: $application, $this->dispatchPullRequestClosedUpdate($application, $found);
preview: $found, } catch (Throwable $e) {
status: ProcessStatus::CLOSED report($e);
); } finally {
CleanupPreviewDeployment::run($application, $this->pullRequestId, $found);
CleanupPreviewDeployment::run($application, $this->pullRequestId, $found); }
} }
} }
protected function dispatchPullRequestClosedUpdate(Application $application, ApplicationPreview $preview): void
{
ApplicationPullRequestUpdateJob::dispatchSync(
application: $application,
preview: $preview,
status: ProcessStatus::CLOSED
);
}
private function handleOpenAction(Application $application, ?GithubApp $githubApp): void private function handleOpenAction(Application $application, ?GithubApp $githubApp): void
{ {
if (! $application->isPRDeployable()) { if (! $application->isPRDeployable()) {
@ -156,7 +165,7 @@ private function handleOpenAction(Application $application, ?GithubApp $githubAp
} }
// Queue the deployment // Queue the deployment
$deployment_uuid = new Cuid2; $deployment_uuid = new_public_id();
queue_application_deployment( queue_application_deployment(
application: $application, application: $application,
pull_request_id: $this->pullRequestId, pull_request_id: $this->pullRequestId,

View file

@ -36,7 +36,7 @@ public function handle(): void
$data = data_get($this->event, 'data.object'); $data = data_get($this->event, 'data.object');
switch ($type) { switch ($type) {
case 'radar.early_fraud_warning.created': case 'radar.early_fraud_warning.created':
$stripe = new StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
$id = data_get($data, 'id'); $id = data_get($data, 'id');
$charge = data_get($data, 'charge'); $charge = data_get($data, 'charge');
if ($charge) { if ($charge) {
@ -100,7 +100,7 @@ public function handle(): void
if ($subscription->stripe_subscription_id) { if ($subscription->stripe_subscription_id) {
try { try {
$stripe = new StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
$stripeSubscription = $stripe->subscriptions->retrieve( $stripeSubscription = $stripe->subscriptions->retrieve(
$subscription->stripe_subscription_id $subscription->stripe_subscription_id
); );
@ -166,7 +166,7 @@ public function handle(): void
// Verify payment status with Stripe API before sending failure notification // Verify payment status with Stripe API before sending failure notification
if ($paymentIntentId) { if ($paymentIntentId) {
try { try {
$stripe = new StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
$paymentIntent = $stripe->paymentIntents->retrieve($paymentIntentId); $paymentIntent = $stripe->paymentIntents->retrieve($paymentIntentId);
if (in_array($paymentIntent->status, ['processing', 'succeeded', 'requires_action', 'requires_confirmation'])) { if (in_array($paymentIntent->status, ['processing', 'succeeded', 'requires_action', 'requires_confirmation'])) {
@ -260,7 +260,10 @@ public function handle(): void
$comment = data_get($data, 'cancellation_details.comment'); $comment = data_get($data, 'cancellation_details.comment');
$lookup_key = data_get($data, 'items.data.0.price.lookup_key'); $lookup_key = data_get($data, 'items.data.0.price.lookup_key');
if (str($lookup_key)->contains('dynamic')) { if (str($lookup_key)->contains('dynamic')) {
$quantity = min((int) data_get($data, 'items.data.0.quantity', 2), UpdateSubscriptionQuantity::MAX_SERVER_LIMIT); $quantity = max(
UpdateSubscriptionQuantity::MIN_SERVER_LIMIT,
min((int) data_get($data, 'items.data.0.quantity', 2), UpdateSubscriptionQuantity::MAX_SERVER_LIMIT)
);
$team = data_get($subscription, 'team'); $team = data_get($subscription, 'team');
if ($team) { if ($team) {
$team->update([ $team->update([

View file

@ -10,6 +10,7 @@
use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Stripe\StripeClient;
class SubscriptionInvoiceFailedJob implements ShouldBeEncrypted, ShouldQueue class SubscriptionInvoiceFailedJob implements ShouldBeEncrypted, ShouldQueue
{ {
@ -27,7 +28,7 @@ public function handle()
$subscription = $this->team->subscription; $subscription = $this->team->subscription;
if ($subscription && $subscription->stripe_customer_id) { if ($subscription && $subscription->stripe_customer_id) {
try { try {
$stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
if ($subscription->stripe_subscription_id) { if ($subscription->stripe_subscription_id) {
$stripeSubscription = $stripe->subscriptions->retrieve($subscription->stripe_subscription_id); $stripeSubscription = $stripe->subscriptions->retrieve($subscription->stripe_subscription_id);

View file

@ -9,6 +9,7 @@
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Stripe\StripeClient;
class SyncStripeSubscriptionsJob implements ShouldBeEncrypted, ShouldQueue class SyncStripeSubscriptionsJob implements ShouldBeEncrypted, ShouldQueue
{ {
@ -33,7 +34,7 @@ public function handle(?\Closure $onProgress = null): array
->where('stripe_invoice_paid', true) ->where('stripe_invoice_paid', true)
->get(); ->get();
$stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
// Bulk fetch all valid subscription IDs from Stripe (active + past_due) // Bulk fetch all valid subscription IDs from Stripe (active + past_due)
$validStripeIds = $this->fetchValidStripeSubscriptionIds($stripe, $onProgress); $validStripeIds = $this->fetchValidStripeSubscriptionIds($stripe, $onProgress);
@ -123,7 +124,7 @@ public function handle(?\Closure $onProgress = null): array
* *
* @return array{email: string, customer_id: string, subscription_id: string, status: string}|null * @return array{email: string, customer_id: string, subscription_id: string, status: string}|null
*/ */
private function findActiveSubscriptionByEmail(\Stripe\StripeClient $stripe, string $customerId): ?array private function findActiveSubscriptionByEmail(StripeClient $stripe, string $customerId): ?array
{ {
try { try {
$customer = $stripe->customers->retrieve($customerId); $customer = $stripe->customers->retrieve($customerId);
@ -177,7 +178,7 @@ private function findActiveSubscriptionByEmail(\Stripe\StripeClient $stripe, str
* *
* @return array<string> * @return array<string>
*/ */
private function fetchValidStripeSubscriptionIds(\Stripe\StripeClient $stripe, ?\Closure $onProgress = null): array private function fetchValidStripeSubscriptionIds(StripeClient $stripe, ?\Closure $onProgress = null): array
{ {
$validIds = []; $validIds = [];
$fetched = 0; $fetched = 0;

View file

@ -9,6 +9,7 @@
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Stripe\StripeClient;
class VerifyStripeSubscriptionStatusJob implements ShouldBeEncrypted, ShouldQueue class VerifyStripeSubscriptionStatusJob implements ShouldBeEncrypted, ShouldQueue
{ {
@ -29,7 +30,7 @@ public function handle(): void
if (! $this->subscription->stripe_subscription_id && if (! $this->subscription->stripe_subscription_id &&
$this->subscription->stripe_customer_id) { $this->subscription->stripe_customer_id) {
try { try {
$stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
$subscriptions = $stripe->subscriptions->all([ $subscriptions = $stripe->subscriptions->all([
'customer' => $this->subscription->stripe_customer_id, 'customer' => $this->subscription->stripe_customer_id,
'limit' => 1, 'limit' => 1,
@ -50,7 +51,7 @@ public function handle(): void
} }
try { try {
$stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $stripe = app(StripeClient::class);
$stripeSubscription = $stripe->subscriptions->retrieve( $stripeSubscription = $stripe->subscriptions->retrieve(
$this->subscription->stripe_subscription_id $this->subscription->stripe_subscription_id
); );

View file

@ -54,6 +54,9 @@ public function submitSearch()
public function getSubscribers() public function getSubscribers()
{ {
if (Auth::id() !== 0 && ! session('impersonating')) {
return redirect()->route('dashboard');
}
$this->inactiveSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', false)->count(); $this->inactiveSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', false)->count();
$this->activeSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->count(); $this->activeSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->count();
} }

View file

@ -9,13 +9,15 @@
use App\Models\Team; use App\Models\Team;
use App\Services\ConfigurationRepository; use App\Services\ConfigurationRepository;
use App\Support\ValidationPatterns; use App\Support\ValidationPatterns;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Livewire\Attributes\Url; use Livewire\Attributes\Url;
use Livewire\Component; use Livewire\Component;
use Visus\Cuid2\Cuid2;
class Index extends Component class Index extends Component
{ {
use AuthorizesRequests;
protected $listeners = [ protected $listeners = [
'refreshBoardingIndex' => 'validateServer', 'refreshBoardingIndex' => 'validateServer',
'prerequisitesInstalled' => 'handlePrerequisitesInstalled', 'prerequisitesInstalled' => 'handlePrerequisitesInstalled',
@ -174,6 +176,9 @@ public function restartBoarding()
public function skipBoarding() public function skipBoarding()
{ {
if (auth()->user()?->isMember()) {
return redirect()->route('dashboard');
}
Team::find(currentTeam()->id)->update([ Team::find(currentTeam()->id)->update([
'show_boarding' => false, 'show_boarding' => false,
]); ]);
@ -276,6 +281,7 @@ public function savePrivateKey()
]); ]);
try { try {
$this->authorize('create', PrivateKey::class);
$privateKey = PrivateKey::createAndStore([ $privateKey = PrivateKey::createAndStore([
'name' => $this->privateKeyName, 'name' => $this->privateKeyName,
'description' => $this->privateKeyDescription, 'description' => $this->privateKeyDescription,
@ -294,6 +300,12 @@ public function saveServer()
{ {
$this->validate(); $this->validate();
try {
$this->authorize('create', Server::class);
} catch (\Throwable $e) {
return handleError($e, $this);
}
$this->privateKey = formatPrivateKey($this->privateKey); $this->privateKey = formatPrivateKey($this->privateKey);
$foundServer = Server::whereIp($this->remoteServerHost)->first(); $foundServer = Server::whereIp($this->remoteServerHost)->first();
if ($foundServer) { if ($foundServer) {
@ -457,7 +469,7 @@ public function createNewProject()
$this->createdProject = Project::create([ $this->createdProject = Project::create([
'name' => 'My first project', 'name' => 'My first project',
'team_id' => currentTeam()->id, 'team_id' => currentTeam()->id,
'uuid' => (string) new Cuid2, 'uuid' => new_public_id(),
]); ]);
$this->currentState = 'create-resource'; $this->currentState = 'create-resource';
} }

View file

@ -9,7 +9,6 @@
use Livewire\Attributes\Locked; use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate; use Livewire\Attributes\Validate;
use Livewire\Component; use Livewire\Component;
use Visus\Cuid2\Cuid2;
class Docker extends Component class Docker extends Component
{ {
@ -35,7 +34,7 @@ class Docker extends Component
public function mount(?string $server_id = null): void public function mount(?string $server_id = null): void
{ {
$this->network = (string) new Cuid2; $this->network = new_public_id();
$this->servers = Server::isUsable()->get(); $this->servers = Server::isUsable()->get();
if (filled($server_id)) { if (filled($server_id)) {
@ -68,7 +67,7 @@ public function updatedServerId(): void
public function generateName(): void public function generateName(): void
{ {
$name = data_get($this->selectedServer, 'name', new Cuid2); $name = data_get($this->selectedServer, 'name', new_public_id());
$this->name = str("{$name}-{$this->network}")->kebab(); $this->name = str("{$name}-{$this->network}")->kebab();
} }

View file

@ -3,6 +3,7 @@
namespace App\Livewire\Destination; namespace App\Livewire\Destination;
use App\Models\StandaloneDocker; use App\Models\StandaloneDocker;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked; use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate; use Livewire\Attributes\Validate;
@ -31,8 +32,12 @@ public function mount(string $destination_uuid)
if (! $destination) { if (! $destination) {
return redirect()->route('destination.index'); return redirect()->route('destination.index');
} }
$this->authorize('view', $destination);
$this->destination = $destination; $this->destination = $destination;
$this->syncData(); $this->syncData();
} catch (AuthorizationException) {
abort(403);
} catch (\Throwable $e) { } catch (\Throwable $e) {
return handleError($e, $this); return handleError($e, $this);
} }

View file

@ -1053,6 +1053,7 @@ private function loadCreatableItems()
'quickcommand' => '(type: new postgresql)', 'quickcommand' => '(type: new postgresql)',
'type' => 'postgresql', 'type' => 'postgresql',
'category' => 'Databases', 'category' => 'Databases',
'logo' => 'svgs/postgresql.svg',
'resourceType' => 'database', 'resourceType' => 'database',
]); ]);
@ -1062,6 +1063,7 @@ private function loadCreatableItems()
'quickcommand' => '(type: new mysql)', 'quickcommand' => '(type: new mysql)',
'type' => 'mysql', 'type' => 'mysql',
'category' => 'Databases', 'category' => 'Databases',
'logo' => 'svgs/mysql.svg',
'resourceType' => 'database', 'resourceType' => 'database',
]); ]);
@ -1071,6 +1073,7 @@ private function loadCreatableItems()
'quickcommand' => '(type: new mariadb)', 'quickcommand' => '(type: new mariadb)',
'type' => 'mariadb', 'type' => 'mariadb',
'category' => 'Databases', 'category' => 'Databases',
'logo' => 'svgs/mariadb.svg',
'resourceType' => 'database', 'resourceType' => 'database',
]); ]);
@ -1080,6 +1083,7 @@ private function loadCreatableItems()
'quickcommand' => '(type: new redis)', 'quickcommand' => '(type: new redis)',
'type' => 'redis', 'type' => 'redis',
'category' => 'Databases', 'category' => 'Databases',
'logo' => 'svgs/redis.svg',
'resourceType' => 'database', 'resourceType' => 'database',
]); ]);
@ -1089,6 +1093,7 @@ private function loadCreatableItems()
'quickcommand' => '(type: new keydb)', 'quickcommand' => '(type: new keydb)',
'type' => 'keydb', 'type' => 'keydb',
'category' => 'Databases', 'category' => 'Databases',
'logo' => 'svgs/keydb.svg',
'resourceType' => 'database', 'resourceType' => 'database',
]); ]);
@ -1098,6 +1103,7 @@ private function loadCreatableItems()
'quickcommand' => '(type: new dragonfly)', 'quickcommand' => '(type: new dragonfly)',
'type' => 'dragonfly', 'type' => 'dragonfly',
'category' => 'Databases', 'category' => 'Databases',
'logo' => 'svgs/dragonfly.svg',
'resourceType' => 'database', 'resourceType' => 'database',
]); ]);
@ -1107,6 +1113,7 @@ private function loadCreatableItems()
'quickcommand' => '(type: new mongodb)', 'quickcommand' => '(type: new mongodb)',
'type' => 'mongodb', 'type' => 'mongodb',
'category' => 'Databases', 'category' => 'Databases',
'logo' => 'svgs/mongodb.svg',
'resourceType' => 'database', 'resourceType' => 'database',
]); ]);
@ -1116,6 +1123,7 @@ private function loadCreatableItems()
'quickcommand' => '(type: new clickhouse)', 'quickcommand' => '(type: new clickhouse)',
'type' => 'clickhouse', 'type' => 'clickhouse',
'category' => 'Databases', 'category' => 'Databases',
'logo' => 'svgs/clickhouse-icon.svg',
'resourceType' => 'database', 'resourceType' => 'database',
]); ]);
} }

View file

@ -4,7 +4,6 @@
// use Livewire\Component; // use Livewire\Component;
use Illuminate\View\Component; use Illuminate\View\Component;
use Visus\Cuid2\Cuid2;
class MonacoEditor extends Component class MonacoEditor extends Component
{ {
@ -40,7 +39,7 @@ public function __construct(
public function render() public function render()
{ {
if (is_null($this->id)) { if (is_null($this->id)) {
$this->id = new Cuid2; $this->id = new_public_id();
} }
if (is_null($this->name)) { if (is_null($this->name)) {

View file

@ -2,12 +2,16 @@
namespace App\Livewire; namespace App\Livewire;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Livewire\Component; use Livewire\Component;
class NavbarDeleteTeam extends Component class NavbarDeleteTeam extends Component
{ {
use AuthorizesRequests;
public $team; public $team;
public function mount() public function mount()
@ -17,27 +21,35 @@ public function mount()
public function delete($password, $selectedActions = []) public function delete($password, $selectedActions = [])
{ {
if (! verifyPasswordConfirmation($password, $this)) { try {
return 'The provided password is incorrect.'; if (! verifyPasswordConfirmation($password, $this)) {
return 'The provided password is incorrect.';
}
$currentTeam = currentTeam();
$this->authorize('delete', $currentTeam);
$currentTeam->members->each(function ($user) use ($currentTeam) {
if ($user->id === Auth::id()) {
return;
}
$user->teams()->detach($currentTeam);
$session = DB::table('sessions')->where('user_id', $user->id)->first();
if ($session) {
DB::table('sessions')->where('id', $session->id)->delete();
}
});
Cache::forget('user:'.Auth::id().':team:'.$currentTeam->id);
$currentTeam->delete();
$newTeam = Auth::user()->teams()->first();
refreshSession($newTeam);
return redirect()->route('team.index');
} catch (\Throwable $e) {
return handleError($e, $this);
} }
$currentTeam = currentTeam();
$currentTeam->delete();
$currentTeam->members->each(function ($user) use ($currentTeam) {
if ($user->id === Auth::id()) {
return;
}
$user->teams()->detach($currentTeam);
$session = DB::table('sessions')->where('user_id', $user->id)->first();
if ($session) {
DB::table('sessions')->where('id', $session->id)->delete();
}
});
refreshSession();
return redirectRoute($this, 'team.index');
} }
public function render() public function render()

View file

@ -110,7 +110,9 @@ public function syncData(bool $toModel = false)
refreshSession(); refreshSession();
} else { } else {
$this->discordEnabled = $this->settings->discord_enabled; $this->discordEnabled = $this->settings->discord_enabled;
$this->discordWebhookUrl = $this->settings->discord_webhook_url; $this->discordWebhookUrl = auth()->user()->can('update', $this->settings)
? $this->settings->discord_webhook_url
: null;
$this->deploymentSuccessDiscordNotifications = $this->settings->deployment_success_discord_notifications; $this->deploymentSuccessDiscordNotifications = $this->settings->deployment_success_discord_notifications;
$this->deploymentFailureDiscordNotifications = $this->settings->deployment_failure_discord_notifications; $this->deploymentFailureDiscordNotifications = $this->settings->deployment_failure_discord_notifications;

View file

@ -113,8 +113,13 @@ public function syncData(bool $toModel = false)
refreshSession(); refreshSession();
} else { } else {
$this->pushoverEnabled = $this->settings->pushover_enabled; $this->pushoverEnabled = $this->settings->pushover_enabled;
$this->pushoverUserKey = $this->settings->pushover_user_key; if (auth()->user()->can('update', $this->settings)) {
$this->pushoverApiToken = $this->settings->pushover_api_token; $this->pushoverUserKey = $this->settings->pushover_user_key;
$this->pushoverApiToken = $this->settings->pushover_api_token;
} else {
$this->pushoverUserKey = null;
$this->pushoverApiToken = null;
}
$this->deploymentSuccessPushoverNotifications = $this->settings->deployment_success_pushover_notifications; $this->deploymentSuccessPushoverNotifications = $this->settings->deployment_success_pushover_notifications;
$this->deploymentFailurePushoverNotifications = $this->settings->deployment_failure_pushover_notifications; $this->deploymentFailurePushoverNotifications = $this->settings->deployment_failure_pushover_notifications;

View file

@ -110,7 +110,9 @@ public function syncData(bool $toModel = false)
refreshSession(); refreshSession();
} else { } else {
$this->slackEnabled = $this->settings->slack_enabled; $this->slackEnabled = $this->settings->slack_enabled;
$this->slackWebhookUrl = $this->settings->slack_webhook_url; $this->slackWebhookUrl = auth()->user()->can('update', $this->settings)
? $this->settings->slack_webhook_url
: null;
$this->deploymentSuccessSlackNotifications = $this->settings->deployment_success_slack_notifications; $this->deploymentSuccessSlackNotifications = $this->settings->deployment_success_slack_notifications;
$this->deploymentFailureSlackNotifications = $this->settings->deployment_failure_slack_notifications; $this->deploymentFailureSlackNotifications = $this->settings->deployment_failure_slack_notifications;

View file

@ -169,8 +169,13 @@ public function syncData(bool $toModel = false)
$this->settings->save(); $this->settings->save();
} else { } else {
$this->telegramEnabled = $this->settings->telegram_enabled; $this->telegramEnabled = $this->settings->telegram_enabled;
$this->telegramToken = $this->settings->telegram_token; if (auth()->user()->can('update', $this->settings)) {
$this->telegramChatId = $this->settings->telegram_chat_id; $this->telegramToken = $this->settings->telegram_token;
$this->telegramChatId = $this->settings->telegram_chat_id;
} else {
$this->telegramToken = null;
$this->telegramChatId = null;
}
$this->deploymentSuccessTelegramNotifications = $this->settings->deployment_success_telegram_notifications; $this->deploymentSuccessTelegramNotifications = $this->settings->deployment_success_telegram_notifications;
$this->deploymentFailureTelegramNotifications = $this->settings->deployment_failure_telegram_notifications; $this->deploymentFailureTelegramNotifications = $this->settings->deployment_failure_telegram_notifications;

Some files were not shown because too many files have changed in this diff Show more