From d018c97be49de8b716e0441ae734a67c8fef05ba Mon Sep 17 00:00:00 2001 From: Lars Stommer Date: Thu, 22 Oct 2026 23:01:44 +0200 Subject: [PATCH] Operating mode in the admin (test mode sends all mail to a test recipient until switched live), bot protection for booking requests, mail rendering tests, mail:test command Co-Authored-By: Claude Opus 5.5 --- .env.production.example | 2 +- AGENTS.md | 2 +- CLAUDE.md | 2 +- app/Console/Commands/SendTestMail.php | 47 +++++++ app/Filament/Pages/Operations.php | 113 ++++++++++++++++ app/Livewire/BookingRequest.php | 62 ++++++++- app/Models/Setting.php | 12 ++ app/Providers/AppServiceProvider.php | 8 +- app/Providers/Filament/AdminPanelProvider.php | 4 + app/Support/Settings.php | 92 +++++++++++++ config/fewo.php | 18 ++- ...026_10_22_225545_create_settings_table.php | 29 ++++ docs/BETRIEB.md | 11 +- docs/KONZEPT.md | 1 + docs/STATUS.md | 11 +- .../views/filament/test-mode-banner.blade.php | 9 ++ tests/Feature/BookingRequestPageTest.php | 3 + tests/Feature/ChannelSyncTest.php | 3 + tests/Feature/GuestRelationsTest.php | 3 + tests/Feature/MailRenderingTest.php | 128 ++++++++++++++++++ tests/Feature/OperationsModeTest.php | 78 +++++++++++ tests/Feature/SpamProtectionTest.php | 83 ++++++++++++ 22 files changed, 698 insertions(+), 23 deletions(-) create mode 100644 app/Console/Commands/SendTestMail.php create mode 100644 app/Filament/Pages/Operations.php create mode 100644 app/Models/Setting.php create mode 100644 app/Support/Settings.php create mode 100644 database/migrations/2026_10_22_225545_create_settings_table.php create mode 100644 resources/views/filament/test-mode-banner.blade.php create mode 100644 tests/Feature/MailRenderingTest.php create mode 100644 tests/Feature/OperationsModeTest.php create mode 100644 tests/Feature/SpamProtectionTest.php diff --git a/.env.production.example b/.env.production.example index be93f5a..2870152 100644 --- a/.env.production.example +++ b/.env.production.example @@ -43,7 +43,7 @@ MAIL_FROM_NAME="${APP_NAME}" FEWO_OWNER_NAME="Brigitte Stommer" FEWO_OWNER_EMAIL=fewo@stommer.de FEWO_NOTIFICATION_EMAIL=fewo@stommer.de -# Nur Testbetrieb: alle E-Mails ausschließlich an diese Adresse (leer = normaler Versand) +# Harte Umleitung aller E-Mails (gilt immer). Normal leer lassen – Testbetrieb/Scharfschalten: Admin › System › Betrieb FEWO_MAIL_REDIRECT_TO= FEWO_BANK_ACCOUNT_HOLDER= FEWO_BANK_IBAN= diff --git a/AGENTS.md b/AGENTS.md index 434a921..b35f1dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ # Ferienwohnung Stommer - Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make `, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request. - Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`. - Deployment: `scripts/deploy.sh setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy//`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`. -- Strato specifics: `public/index.php` strips the internal `/releases//public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; test environments redirect all mail via `FEWO_MAIL_REDIRECT_TO`. +- Strato specifics: `public/index.php` strips the internal `/releases//public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0. - Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR). - PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there). - Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`. diff --git a/CLAUDE.md b/CLAUDE.md index 434a921..b35f1dd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,7 +17,7 @@ # Ferienwohnung Stommer - Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make `, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request. - Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`. - Deployment: `scripts/deploy.sh setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy//`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`. -- Strato specifics: `public/index.php` strips the internal `/releases//public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; test environments redirect all mail via `FEWO_MAIL_REDIRECT_TO`. +- Strato specifics: `public/index.php` strips the internal `/releases//public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0. - Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR). - PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there). - Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`. diff --git a/app/Console/Commands/SendTestMail.php b/app/Console/Commands/SendTestMail.php new file mode 100644 index 0000000..ed5ab27 --- /dev/null +++ b/app/Console/Commands/SendTestMail.php @@ -0,0 +1,47 @@ +argument('to') ?: config('fewo.notification_email')); + $mailer = (string) config('mail.default'); + $redirect = Settings::mailRedirect(); + + $this->line("Versandweg: {$mailer}".($mailer === 'smtp' ? ' ('.config('mail.mailers.smtp.host').':'.config('mail.mailers.smtp.port').')' : '').' · Absender: '.config('mail.from.address')); + if (filled($redirect)) { + $this->line("Umleitung aktiv: die Mail geht an {$redirect} statt an {$to}."); + } + if ($mailer === 'log') { + $this->warn('Versandweg "log": es wird nichts zugestellt. Zum echten Versand MAIL_MAILER=smtp und MAIL_PASSWORD setzen (docs/BETRIEB.md §5a).'); + } + + try { + Mail::raw("Testmail der Ferienwohnung Stommer\n\nGesendet am ".now()->format('d.m.Y H:i:s').' von '.config('app.url').".\nWenn diese Mail ankommt, funktioniert der Versand.", function ($message) use ($to): void { + $message->to($to)->subject('Testmail Ferienwohnung Stommer – '.now()->format('d.m.Y H:i')); + }); + } catch (Throwable $exception) { + $this->error('Versand fehlgeschlagen: '.$exception->getMessage()); + + return self::FAILURE; + } + + $this->info('Übergeben an den Mailserver – bitte Posteingang (und Spam-Ordner) prüfen.'); + + return self::SUCCESS; + } +} diff --git a/app/Filament/Pages/Operations.php b/app/Filament/Pages/Operations.php new file mode 100644 index 0000000..9004882 --- /dev/null +++ b/app/Filament/Pages/Operations.php @@ -0,0 +1,113 @@ + */ + public array $data = []; + + public static function canAccess(): bool + { + return (bool) auth()->user()?->hasRole(UserRole::Admin); + } + + public function mount(): void + { + $this->form->fill([ + 'mode' => Settings::get(Settings::MODE, Settings::MODE_TEST), + 'test_recipient' => Settings::get(Settings::TEST_RECIPIENT) ?? auth()->user()?->email, + ]); + } + + public function form(Schema $schema): Schema + { + return $schema + ->statePath('data') + ->components([ + Section::make('E-Mail-Versand') + ->description('Im Testbetrieb gehen alle E-Mails – Eingangsbestätigungen, Angebote, Bestätigungen, Erinnerungen, Benachrichtigungen – ausschließlich an die Testadresse, egal welche Adresse auf der Webseite eingetragen wurde.') + ->schema([ + Radio::make('mode') + ->label('Betriebsart') + ->options([ + Settings::MODE_TEST => 'Testbetrieb – alle E-Mails an die Testadresse', + Settings::MODE_LIVE => 'Scharf geschaltet – E-Mails an Gäste und Vermieterin', + ]) + ->required() + ->live(), + TextInput::make('test_recipient') + ->label('Testadresse') + ->email() + ->required(fn (Get $get): bool => $get('mode') === Settings::MODE_TEST) + ->visible(fn (Get $get): bool => $get('mode') === Settings::MODE_TEST), + Text::make(fn (): string => filled(config('fewo.mail_redirect_to')) + ? 'Hinweis: Auf diesem Server ist zusätzlich FEWO_MAIL_REDIRECT_TO='.config('fewo.mail_redirect_to').' gesetzt – diese Umleitung gilt immer, auch wenn hier scharf geschaltet ist.' + : ''), + ]), + ]); + } + + public function content(Schema $schema): Schema + { + return $schema->components([ + Form::make([EmbeddedSchema::make('form')]) + ->id('form') + ->livewireSubmitHandler('save') + ->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]), + ]); + } + + public function save(): void + { + $data = $this->form->getState(); + + if ($data['mode'] === Settings::MODE_LIVE && Settings::get(Settings::MODE) !== Settings::MODE_LIVE) { + Notification::make()->title('Scharf geschaltet')->body('Ab jetzt erhalten Gäste und Vermieterin die E-Mails direkt.')->warning()->send(); + } else { + Notification::make()->title('Gespeichert')->success()->send(); + } + + Settings::save([ + Settings::MODE => $data['mode'], + Settings::TEST_RECIPIENT => $data['test_recipient'] ?? Settings::get(Settings::TEST_RECIPIENT), + ]); + } +} diff --git a/app/Livewire/BookingRequest.php b/app/Livewire/BookingRequest.php index d73e3a7..cbdebb3 100644 --- a/app/Livewire/BookingRequest.php +++ b/app/Livewire/BookingRequest.php @@ -5,6 +5,7 @@ use App\Actions\CreateReservation; use App\Actions\RequestMarketingConsent; use App\Availability\AvailabilityChecker; +use App\Enums\BookingStatus; use App\Enums\ReferralSource; use App\Exceptions\ReservationException; use App\Models\Booking; @@ -77,12 +78,17 @@ class BookingRequest extends Component /** Honeypot, must stay empty. */ public string $website = ''; + /** When the form was opened (time trap against bots); cannot be changed by the browser. */ + #[Locked] + public int $openedAt = 0; + #[Locked] public ?int $bookingId = null; public function mount(?Property $property = null): void { $this->propertyId = ($property ?? Property::query()->where('is_active', true)->firstOrFail())->id; + $this->openedAt = now()->getTimestamp(); $this->month = CarbonImmutable::today()->format('Y-m'); $this->prefillFromSearch(); $this->utm = collect(request()->only(['utm_source', 'utm_medium', 'utm_campaign'])) @@ -215,17 +221,22 @@ public function submit(CreateReservation $createReservation): void { $this->validate(); - if ($this->website !== '') { + // Bots: honeypot filled or submitted faster than a human can fill the form – silently ignored. + if ($this->website !== '' || now()->getTimestamp() - $this->openedAt < config('fewo.spam.min_seconds')) { return; } - $rateLimitKey = 'booking-request:'.request()->ip(); - if (RateLimiter::tooManyAttempts($rateLimitKey, 5)) { + if ($this->tooManyRequests()) { $this->addError('email', 'Zu viele Anfragen. Bitte versuchen Sie es später erneut oder rufen Sie uns an.'); return; } - RateLimiter::hit($rateLimitKey, 3600); + + if ($this->openRequestsOfEmail() >= config('fewo.spam.open_requests_per_email')) { + $this->addError('email', 'Zu dieser E-Mail-Adresse liegen bereits offene Anfragen vor. Wir melden uns in Kürze – bei Fragen rufen Sie uns gern an.'); + + return; + } try { $booking = $createReservation->handle( @@ -260,6 +271,39 @@ public function submit(CreateReservation $createReservation): void /** * @return array> */ + /** + * Rate limits per IP address, per e-mail address and for all requests together (counted when they pass). + */ + private function tooManyRequests(): bool + { + $limits = [ + 'booking-request:'.request()->ip() => [config('fewo.spam.per_ip_per_hour'), 3600], + 'booking-request-email:'.sha1(mb_strtolower($this->email)) => [config('fewo.spam.per_email_per_day'), 86400], + 'booking-request-all' => [config('fewo.spam.total_per_hour'), 3600], + ]; + + foreach ($limits as $key => [$max]) { + if (RateLimiter::tooManyAttempts($key, $max)) { + return true; + } + } + + foreach ($limits as $key => [, $decay]) { + RateLimiter::hit($key, $decay); + } + + return false; + } + + private function openRequestsOfEmail(): int + { + return Booking::query() + ->whereIn('status', BookingStatus::holding()) + ->where('hold_expires_at', '>', now()) + ->whereHas('guest', fn ($query) => $query->where('email', mb_strtolower($this->email))) + ->count(); + } + protected function rules(): array { return [ @@ -268,14 +312,18 @@ protected function rules(): array 'guests' => ['required', 'integer', 'min:1', 'max:'.$this->property->max_guests], 'extras.*' => ['nullable', 'integer', 'min:0', 'max:10'], 'promoCode' => ['nullable', 'string', 'max:50'], - 'firstName' => ['required', 'string', 'max:255'], - 'lastName' => ['required', 'string', 'max:255'], + 'firstName' => ['required', 'string', 'max:255', 'not_regex:/https?:|www\.|<|>/i'], + 'lastName' => ['required', 'string', 'max:255', 'not_regex:/https?:|www\.|<|>/i'], 'email' => ['required', 'email', 'max:255'], 'phone' => ['nullable', 'string', 'max:50'], 'street' => ['nullable', 'string', 'max:255'], 'postalCode' => ['nullable', 'string', 'max:20'], 'city' => ['nullable', 'string', 'max:255'], - 'message' => ['nullable', 'string', 'max:5000'], + 'message' => ['nullable', 'string', 'max:5000', function (string $attribute, mixed $value, \Closure $fail): void { + if (preg_match_all('~https?://|www\.~i', (string) $value) > config('fewo.spam.max_links')) { + $fail('Bitte schreiben Sie Ihre Nachricht ohne Links.'); + } + }], 'referralSource' => ['nullable', Rule::enum(ReferralSource::class)], 'privacyAccepted' => ['accepted'], ]; diff --git a/app/Models/Setting.php b/app/Models/Setting.php new file mode 100644 index 0000000..8e540df --- /dev/null +++ b/app/Models/Setting.php @@ -0,0 +1,12 @@ + StripImageMetadata::strip($event->media)); diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index 4591a74..499096c 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -16,7 +16,9 @@ use Filament\PanelProvider; use Filament\Support\Colors\Color; use Filament\Support\Icons\Heroicon; +use Filament\View\PanelsRenderHook; use Filament\Widgets\AccountWidget; +use Illuminate\Contracts\View\View; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; use Illuminate\Cookie\Middleware\EncryptCookies; use Illuminate\Foundation\Http\Middleware\PreventRequestForgery; @@ -58,6 +60,8 @@ public function panel(Panel $panel): Panel }), ]) ->brandName('FeWo Stommer · Verwaltung') + // As long as the site is not switched live, every page shows where the e-mails go. + ->renderHook(PanelsRenderHook::BODY_START, fn (): View => view('filament.test-mode-banner')) ->navigationGroups(['Vermietung', 'Webseite', 'System']) ->colors([ 'primary' => Color::Sky, diff --git a/app/Support/Settings.php b/app/Support/Settings.php new file mode 100644 index 0000000..b7b6f7f --- /dev/null +++ b/app/Support/Settings.php @@ -0,0 +1,92 @@ + Setting::query()->pluck('value', 'key')->all()); + } catch (Throwable) { + return $default; // e.g. before the migrations ran + } + + return $values[$key] ?? $default; + } + + /** + * @param array $values + */ + public static function save(array $values): void + { + foreach ($values as $key => $value) { + Setting::query()->updateOrCreate(['key' => $key], ['value' => $value]); + } + + Cache::forget(self::CACHE_KEY); + self::applyMailRouting(); + } + + public static function isLive(): bool + { + return self::get(self::MODE, self::MODE_TEST) === self::MODE_LIVE; + } + + /** + * Where all e-mails go instead of their real recipients, or null when mails are delivered normally. + * FEWO_MAIL_REDIRECT_TO in .env always wins (hard override for test servers). + */ + public static function mailRedirect(): ?string + { + $override = config('fewo.mail_redirect_to'); + if (filled($override)) { + return (string) $override; + } + + if (self::isLive()) { + return null; + } + + return self::get(self::TEST_RECIPIENT) ?: (config('fewo.notification_email') ?: null); + } + + /** + * Applies the redirect to the mailer; called at boot and after saving. + */ + public static function applyMailRouting(): void + { + $manager = Mail::getFacadeRoot(); + if (! $manager instanceof MailManager) { + return; // Mail::fake() in tests + } + + $redirect = self::mailRedirect(); + $manager->purge(); + + if (filled($redirect)) { + $manager->alwaysTo($redirect); + } + } +} diff --git a/config/fewo.php b/config/fewo.php index 1a48498..5f1d5f6 100644 --- a/config/fewo.php +++ b/config/fewo.php @@ -50,9 +50,25 @@ | Further retention periods (docs/LOESCHKONZEPT.md). The defaults are PROPOSALS – please have them | confirmed according to the general legal opinion (tax advisor / legal advice) and adjust here. */ - // Test environments: every e-mail goes to this address only (instead of guests/landlord). Empty = normal delivery. + // Hard override: every e-mail goes to this address only, regardless of the operating mode in the admin + // (System › Betrieb). Empty = the admin setting decides (test mode → test recipient, live → real recipients). 'mail_redirect_to' => env('FEWO_MAIL_REDIRECT_TO'), + // Protection of the booking form against bots (no external captcha service – GDPR). Every request holds + // the dates for the hold time, so automated requests could block the calendar. + 'spam' => [ + // Faster than this after opening the page = bot; silently ignored. + 'min_seconds' => (int) env('FEWO_SPAM_MIN_SECONDS', 4), + 'per_ip_per_hour' => (int) env('FEWO_SPAM_PER_IP_PER_HOUR', 5), + 'per_email_per_day' => (int) env('FEWO_SPAM_PER_EMAIL_PER_DAY', 3), + // Requests/offers of one e-mail address that hold dates at the same time. + 'open_requests_per_email' => (int) env('FEWO_SPAM_OPEN_REQUESTS_PER_EMAIL', 2), + // All website requests together (flood protection). + 'total_per_hour' => (int) env('FEWO_SPAM_TOTAL_PER_HOUR', 30), + // Links allowed in the message. + 'max_links' => (int) env('FEWO_SPAM_MAX_LINKS', 1), + ], + // Daily database backup (php artisan backup:database): number of dumps kept in storage/app/private/backups. 'backup' => [ 'keep' => (int) env('FEWO_BACKUP_KEEP', 14), diff --git a/database/migrations/2026_10_22_225545_create_settings_table.php b/database/migrations/2026_10_22_225545_create_settings_table.php new file mode 100644 index 0000000..b9170a7 --- /dev/null +++ b/database/migrations/2026_10_22_225545_create_settings_table.php @@ -0,0 +1,29 @@ +id(); + $table->string('key')->unique(); + $table->text('value')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('settings'); + } +}; diff --git a/docs/BETRIEB.md b/docs/BETRIEB.md index 8d84dc1..4bb0f8e 100644 --- a/docs/BETRIEB.md +++ b/docs/BETRIEB.md @@ -72,9 +72,13 @@ ## 5. Konfiguration auf dem Server (`shared/.env`) | `FEWO_BANK_*` | leer | für Verträge/Angebote noch einzutragen | | `FEWO_HEALTH_TOKEN`, `FEWO_SCHEDULER_TOKEN`, `FEWO_AUTOMATION_SECRET` | gesetzt | für n8n (Überwachung, Scheduler-Ersatz, Webhooks) | -## 5a. E-Mail im Testbetrieb +## 5a. E-Mail: Testbetrieb und scharf schalten -Standard: `MAIL_MAILER=log` (nichts wird versendet). Zum Testen der echten Mails: in `shared/.env` `MAIL_MAILER=smtp` und `MAIL_PASSWORD=` (nur selbst eintragen), dann `bash scripts/deploy.sh staging artisan optimize`. Weil `FEWO_MAIL_REDIRECT_TO=lars@stommer.com` gesetzt ist, gehen **alle** Mails – auch die an Gäste und an die Vermieterin – nur an diese Adresse. In der Produktion `FEWO_MAIL_REDIRECT_TO` leer lassen. +- **Betriebsart** in der Verwaltung: **System › Betrieb** (nur Administratoren). Jede Installation beginnt im **Testbetrieb**: alle E-Mails (an Gäste, Vermieterin, Benachrichtigungen) gehen ausschließlich an die dort eingetragene **Testadresse** (ohne Eintrag: `FEWO_NOTIFICATION_EMAIL`), egal was auf der Webseite eingetragen wurde. Ein gelber Hinweis oben in der Verwaltung zeigt das an. Erst „Scharf geschaltet“ liefert an die echten Empfänger. +- `FEWO_MAIL_REDIRECT_TO` in `shared/.env` ist eine **harte Überschreibung** für Testserver (gilt auch bei „scharf“); normalerweise leer lassen. +- **Versandweg:** Standard `MAIL_MAILER=log` – dann wird gar nichts zugestellt (auch nicht im Protokoll gespeichert). Für echten Versand in `shared/.env` `MAIL_MAILER=smtp` und `MAIL_PASSWORD=` (nur selbst eintragen), dann `bash scripts/deploy.sh staging artisan optimize`. +- **Versand prüfen:** `bash scripts/deploy.sh staging artisan mail:test` – zeigt Versandweg, Umleitung und Fehler (z. B. SMTP-Anmeldung) und schickt eine Testmail. +- Dass jede Mail-Vorlage fehlerfrei aufgebaut wird (17 Mail-Typen, in ihrem echten Zustand), prüft `tests/Feature/MailRenderingTest.php`. ## 6. Erledigt / offen im Testbetrieb @@ -82,7 +86,7 @@ ## 6. Erledigt / offen im Testbetrieb Offen: - **Konto für Brigitte** anlegen: System › Benutzer, Rolle Administrator, Ansicht Einfach (§7). -- **E-Mail im Testbetrieb** einschalten (§5a). +- **E-Mail im Testbetrieb** einschalten (§5a): Versandweg SMTP + Passwort; Betriebsart steht auf Testbetrieb mit Testadresse lars@stommer.com. - **Cronjob** (Kundenlogin › Cronjobs), jede Minute: `/opt/RZphp84/bin/php-cli /mnt/web508/e3/26/51539426/htdocs/test.fewo-stommer.de/current/artisan schedule:run` Falls Strato nicht minütlich erlaubt: n8n ruft jede Minute `https://stommer.info/automation/scheduler` mit Header `Authorization: Bearer ` auf. @@ -134,6 +138,7 @@ ## 7a. Datensicherung, Löschfristen, Automationen ``` Regelmäßig z. B. per Aufgabenplanung des NAS/PC ausführen (braucht den SSH-Schlüssel aus §4). - **Löschfristen** (Vorschläge, rechtlich zu bestätigen – `config/fewo.php` bzw. `.env`): Gästedaten 10 Jahre nach letztem Aufenthalt (`FEWO_GUEST_RETENTION_YEARS`), nie verbindlich gewordene Anfragen/Angebote 6 Monate (`FEWO_RETENTION_INQUIRY_MONTHS`), Textauszüge von Portal-Mails 90 Tage (`FEWO_RETENTION_PORTAL_EMAIL_EXCERPT_DAYS`), Herkunftsangaben/UTM 24 Monate (`FEWO_RETENTION_ATTRIBUTION_MONTHS`). Läuft täglich 03:00. Anonymisierung ersetzt Name, Kontaktdaten, Nachrichten, Notizen, Herkunft und Bewertungs-Anzeigenamen; Buchung, Preise und Zahlungen bleiben als Beleg. +- **Bot-Schutz der Buchungsanfrage** (ohne externen Captcha-Dienst, `config/fewo.php › spam`): verstecktes Köderfeld, Zeitsperre (Absenden schneller als 4 s nach dem Öffnen = Bot, wird still ignoriert), höchstens 5 Anfragen/Stunde je IP, 3/Tag je E-Mail-Adresse, 30/Stunde insgesamt, höchstens 2 gleichzeitig vorgemerkte Anfragen je E-Mail-Adresse (sonst könnten Bots den Kalender blockieren), keine Links in Namen und höchstens 1 Link in der Nachricht. - **Automationen (n8n):** Token bitte als Header `Authorization: Bearer ` senden (landet nicht in Server-Logs); `?token=` funktioniert übergangsweise weiter. - **Fotos:** Beim Hochladen werden Metadaten (GPS, Kamera) aus dem Original entfernt; bestehende Fotos einmalig: `php artisan photos:strip-metadata` (`--force` bearbeitet auch bereits markierte erneut). Hinweis: bewusst mit GD – Imagick (auf Strato installiert) behält EXIF beim Speichern. diff --git a/docs/KONZEPT.md b/docs/KONZEPT.md index f5c5ba5..4f5b939 100644 --- a/docs/KONZEPT.md +++ b/docs/KONZEPT.md @@ -127,6 +127,7 @@ ### 6b. Weitere Festlegungen (22.10.2026) - **Lösch- und Aufbewahrungsfristen** nach allgemeiner Rechtsauffassung festlegen (fachkundig bestätigen lassen); technisch als Einstellungen umsetzen (Vorschläge: docs/LOESCHKONZEPT.md). - **Auftragsverarbeitung mit Strato:** Strato stellt dafür nach unserem Kenntnisstand einen Standardvertrag im Kundenbereich bereit – dort prüfen/abschließen. - **Portalgäste** = Gäste, die über ein Buchungsportal (FeWo-direkt u. a.) buchen; ihre Daten erreichen uns nur über die Portal-Benachrichtigungen. Wir betreiben selbst kein Portal. +- **Testbetrieb vs. scharf geschaltet** (System › Betrieb): bis zum Scharfschalten gehen alle E-Mails nur an eine einstellbare Testadresse. **Bot-Schutz** der Anfrage ohne externe Dienste (DSGVO). - **Verwaltung:** mehrere Verwalter-Konten (mindestens Lars und Brigitte Stommer); **einfache Ansicht** (Anfragen/Buchungen/Verträge, Sperrzeiten, Gäste, Portal-Aufgaben, Bewertungen) und **Expertenansicht** (alle Einstellungen), umschaltbar je Benutzer – umgesetzt. - Die Dokumente BUCHUNGSPROZESS, DATENMODELL-KONZEPT, GAP-DELTA, GO-LIVE-CHECKLISTE, LOESCHKONZEPT und DATENSCHUTZ-* wurden von einem Analyse-Agenten erstellt; die dort genannten „verbindlichen Entscheidungen E1–E7“ sind **dessen Annahmen**. Maßgeblich sind die Festlegungen in diesem Dokument. diff --git a/docs/STATUS.md b/docs/STATUS.md index 1055614..fda507b 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,6 +1,6 @@ # Projektstand -Stand: 22.10.2026, Abend · letzter ausgelieferter Stand: Git-Tag `deploy/staging/20261022203959` auf https://stommer.info · 187 Tests grün +Stand: 22.10.2026, spätabends · ausgelieferter Stand: siehe neuester Git-Tag `deploy/staging/*` · 200 Tests grün > Dieses Dokument ist der Einstieg für jede neue Arbeitssitzung. Bitte bei größeren Änderungen fortschreiben (Abschnitte „Fertig“, „Offen“, „Nächste Schritte“). @@ -44,7 +44,9 @@ ## 1. Fertig (umgesetzt, getestet, auf stommer.info) - Anonymisierung und Löschfristen (Vorschläge) laufen täglich. - Sicherheits-Header sind gesetzt; Automations-Tokens werden per Header übergeben. - Keine externen Quellen (Schriften selbst gehostet). -- **Testbetrieb:** `noindex`; Mails gehen nur an `FEWO_MAIL_REDIRECT_TO`, sobald SMTP eingeschaltet ist. +- **Betriebsart** (System › Betrieb): Testbetrieb (Standard) schickt alle Mails nur an eine Testadresse, „scharf geschaltet“ an die echten Empfänger; Hinweisbanner in der Verwaltung. `mail:test` prüft den Versand; alle 17 Mail-Typen werden in Tests vollständig aufgebaut. +- **Bot-Schutz der Buchungsanfrage:** Köderfeld, Zeitsperre, Begrenzungen je IP/E-Mail/gesamt, höchstens 2 gleichzeitige Vormerkungen je E-Mail, keine Links (ohne externen Captcha-Dienst). +- **Testbetrieb:** `noindex`. ## 2. Stand auf stommer.info (Testbetrieb) @@ -52,7 +54,7 @@ ## 2. Stand auf stommer.info (Testbetrieb) |---|---| | Konten | `lars@stommer.com` (Administrator); Konto für Brigitte noch anzulegen (Administrator, **einfache Ansicht**) | | Daten | Wohnung, Preise 2026, 39 Fotos, Seiten, 5 Erscheinungsbilder; **Testbuchung 2026-0002** („E2E Testgast“, angenommenes Angebot) – darf gelöscht werden | -| E-Mail | `MAIL_MAILER=log` (geht nirgendwohin). Einschalten: `MAIL_MAILER=smtp` + `MAIL_PASSWORD` in `shared/.env` (selbst eintragen), Umleitung an `lars@stommer.com` ist gesetzt | +| E-Mail | Betriebsart **Testbetrieb** (System › Betrieb), Testadresse `lars@stommer.com` – alle Mails gingen nur dorthin. Versandweg aber noch `log` (nichts wird zugestellt): `MAIL_MAILER=smtp` + `MAIL_PASSWORD` in `shared/.env` selbst eintragen, dann `artisan mail:test` (BETRIEB.md §5a) | | Cronjob | **noch nicht eingerichtet** – ohne ihn laufen Fristabläufe, Erinnerungen, Kalenderabgleich, Backups nicht automatisch (BETRIEB.md §6) | | Typischer Anreisetag | noch nicht eingetragen (Preise & Angebote › Saisons › Regeln Mindestaufenthalt) | @@ -82,7 +84,8 @@ ## 3. Offen ## 4. Nächste Schritte (Vorschlag) -1. Cronjob einrichten; SMTP im Testbetrieb einschalten; Konto für Brigitte anlegen. +1. Cronjob einrichten; SMTP einschalten und mit `mail:test` prüfen (Mails landen wegen Testbetrieb nur bei Lars); Konto für Brigitte anlegen. +1a. Vor dem Go-Live: System › Betrieb auf „scharf geschaltet“ stellen – erst dann erhalten Gäste die Mails. 2. Brigitte probt Anfrage → Angebot → Annahme mit einem eigenen Test (Angebotslink über die Aktion „Angebotslink“). 3. Design-Theme auf dem privaten Rechner (eigene Session, siehe ZUSAMMENARBEIT.md). 4. Rechtstexte und Bedingungen einpflegen, Produktion einrichten, Umzug von WordPress. diff --git a/resources/views/filament/test-mode-banner.blade.php b/resources/views/filament/test-mode-banner.blade.php new file mode 100644 index 0000000..19a3e06 --- /dev/null +++ b/resources/views/filament/test-mode-banner.blade.php @@ -0,0 +1,9 @@ +@php($redirect = \App\Support\Settings::mailRedirect()) +@if ($redirect) +
+ Testbetrieb: Alle E-Mails gehen nur an {{ $redirect }}. + @if (auth()->user()?->hasRole(\App\Enums\UserRole::Admin)) + Betrieb einstellen + @endif +
+@endif diff --git a/tests/Feature/BookingRequestPageTest.php b/tests/Feature/BookingRequestPageTest.php index 884850d..139aa84 100644 --- a/tests/Feature/BookingRequestPageTest.php +++ b/tests/Feature/BookingRequestPageTest.php @@ -22,6 +22,9 @@ protected function setUp(): void { parent::setUp(); + // These tests submit the form instantly; the bot time trap is tested in SpamProtectionTest. + config(['fewo.spam.min_seconds' => 0]); + $this->travelTo(CarbonImmutable::parse('2026-10-22 10:00')); $this->seed([PropertySeeder::class, SiteSeeder::class]); Mail::fake(); diff --git a/tests/Feature/ChannelSyncTest.php b/tests/Feature/ChannelSyncTest.php index 3b8988b..daad725 100644 --- a/tests/Feature/ChannelSyncTest.php +++ b/tests/Feature/ChannelSyncTest.php @@ -47,6 +47,9 @@ protected function setUp(): void { parent::setUp(); + // These tests submit the form instantly; the bot time trap is tested in SpamProtectionTest. + config(['fewo.spam.min_seconds' => 0]); + $this->travelTo(CarbonImmutable::parse('2026-10-22 10:00')); $this->seed(PropertySeeder::class); $this->property = Property::sole(); diff --git a/tests/Feature/GuestRelationsTest.php b/tests/Feature/GuestRelationsTest.php index c6bb48a..39b7d16 100644 --- a/tests/Feature/GuestRelationsTest.php +++ b/tests/Feature/GuestRelationsTest.php @@ -40,6 +40,9 @@ protected function setUp(): void { parent::setUp(); + // These tests submit the form instantly; the bot time trap is tested in SpamProtectionTest. + config(['fewo.spam.min_seconds' => 0]); + $this->travelTo(CarbonImmutable::parse('2026-10-22 10:00')); $this->seed(PropertySeeder::class); $this->property = Property::sole(); diff --git a/tests/Feature/MailRenderingTest.php b/tests/Feature/MailRenderingTest.php new file mode 100644 index 0000000..3a7eb17 --- /dev/null +++ b/tests/Feature/MailRenderingTest.php @@ -0,0 +1,128 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed(PropertySeeder::class); + Mail::fake(); + Storage::fake('local'); + } + + public function test_every_mail_along_the_booking_path_renders_in_its_state(): void + { + $booking = app(CreateReservation::class)->handle( + Property::sole(), + new StayRequest(CarbonImmutable::parse('2026-12-01'), CarbonImmutable::parse('2026-12-05'), 2), + ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'erika@example.com', 'street' => 'Seeweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn'], + 'Wir kommen mit Hund – ist das in Ordnung?', + sendMails: false, + ); + $this->assertRenders(new ReservationReceived($booking), 'vorgemerkt'); + $this->assertRenders(new NewReservation($booking), 'Erika Muster'); + + $send = app(SendOffer::class); + $booking = $send->handle($booking, ['price_adjustment' => -1500, 'offer_message' => 'Hund ist willkommen.'], sendMail: false); + $this->assertRenders(new OfferMade($booking, $send->offerUrl($booking)), 'Angebot ansehen und annehmen', attachments: 1); + $this->assertRenders(new ReservationExpired($booking), 'Angebot abgelaufen'); + $this->assertRenders(new BookingDeclined($booking), 'Erika'); + + app(AcceptOffer::class)->handle($booking, $booking->offer_version); + $booking->refresh(); + $this->assertRenders(new OfferAnswered($booking, accepted: true), 'Angebot angenommen'); + $this->assertRenders(new OfferAnswered($booking, accepted: false), 'abgelehnt'); + $this->assertRenders(new BookingConfirmed($booking), 'Sie haben unser Angebot', attachments: 1); + + foreach ([PaymentReminder::DEPOSIT_OVERDUE, PaymentReminder::BALANCE_REQUEST, PaymentReminder::BALANCE_OVERDUE] as $kind) { + $this->assertRenders(new PaymentReminder($booking, $kind), 'Erika Muster'); + } + $this->assertRenders(new ArrivalInformation($booking), 'Erika'); + $this->assertRenders(new ReviewRequest($booking), 'Erika'); + } + + public function test_directly_confirmed_booking_and_other_notifications_render(): void + { + $booking = Booking::factory()->for(Property::sole())->create(['confirmed_at' => now(), 'deposit_due_on' => now()->addWeek()->toDateString()]); + $this->assertRenders(new BookingConfirmed($booking), 'verbindlich zu bestätigen'); + + $channel = Channel::factory()->for(Property::sole())->create(['name' => 'FeWo-direkt']); + $this->assertRenders(new ChannelSyncAlert($channel), 'FeWo-direkt'); + $this->assertRenders(new ChannelConflict($channel, ['14.11.–17.11.2026 überschneidet Buchung 2026-0001']), 'überschneidet'); + $this->assertRenders(new ChannelTasksNotification([ChannelTask::factory()->for($channel)->create()]), 'FeWo-direkt'); + $this->assertRenders(new MailboxAlert('Login fehlgeschlagen'), 'Login fehlgeschlagen'); + $this->assertRenders(new MarketingConsentRequest($booking->guest), $booking->guest->first_name); + $this->assertRenders(new NewReview(Review::factory()->create(['booking_id' => $booking->id, 'title' => 'Wunderbar'])), 'Wunderbar'); + $this->assertRenders(new PortalMailNotification(PortalEmail::query()->create([ + 'channel_id' => $channel->id, 'message_id' => 'm1@portal', 'from' => 'noreply@portal.example', 'subject' => 'Neue Buchung', + 'received_at' => now(), 'type' => PortalEmailType::Booking, 'status' => PortalEmailStatus::Blocked, 'starts_on' => '2026-11-14', 'ends_on' => '2026-11-17', + ])), 'Neue Buchung'); + } + + public function test_test_mail_command_sends_and_respects_the_redirect(): void + { + config(['fewo.mail_redirect_to' => 'test@example.com']); + + $this->artisan('mail:test', ['to' => 'gast@example.com']) + ->expectsOutputToContain('Umleitung aktiv') + ->assertSuccessful(); + } + + private function assertRenders(Mailable $mail, string $expected, int $attachments = 0): void + { + $html = $mail->render(); + + $this->assertNotEmpty($mail->envelope()->subject, $mail::class.' needs a subject'); + $this->assertStringContainsString(e($expected), $html, $mail::class); + if (method_exists($mail, 'attachments')) { + $this->assertCount($attachments, $mail->attachments(), $mail::class.' attachments'); + } + } +} diff --git a/tests/Feature/OperationsModeTest.php b/tests/Feature/OperationsModeTest.php new file mode 100644 index 0000000..63e900a --- /dev/null +++ b/tests/Feature/OperationsModeTest.php @@ -0,0 +1,78 @@ + null, 'fewo.notification_email' => 'fewo@example.com']); + + $this->assertFalse(Settings::isLive()); + $this->assertSame('fewo@example.com', Settings::mailRedirect()); + } + + public function test_in_test_mode_every_mail_goes_to_the_test_recipient_only(): void + { + config(['fewo.mail_redirect_to' => null, 'mail.default' => 'array']); + Settings::save([Settings::MODE => Settings::MODE_TEST, Settings::TEST_RECIPIENT => 'test@example.com']); + + Mail::raw('Hallo', fn ($message) => $message->to('gast@example.com')->cc('vermieterin@example.com')->subject('Angebot')); + + $sent = app(MailManager::class)->mailer('array')->getSymfonyTransport()->messages()->last(); + $this->assertSame(['test@example.com'], array_map(fn ($address) => $address->getAddress(), $sent->getEnvelope()->getRecipients())); + } + + public function test_switched_live_mails_reach_their_real_recipients(): void + { + config(['fewo.mail_redirect_to' => null, 'mail.default' => 'array']); + Settings::save([Settings::MODE => Settings::MODE_LIVE]); + + Mail::raw('Hallo', fn ($message) => $message->to('gast@example.com')->subject('Angebot')); + + $sent = app(MailManager::class)->mailer('array')->getSymfonyTransport()->messages()->last(); + $this->assertSame(['gast@example.com'], array_map(fn ($address) => $address->getAddress(), $sent->getEnvelope()->getRecipients())); + $this->assertNull(Settings::mailRedirect()); + } + + public function test_server_override_always_wins(): void + { + config(['fewo.mail_redirect_to' => 'server@example.com']); + Settings::save([Settings::MODE => Settings::MODE_LIVE]); + + $this->assertSame('server@example.com', Settings::mailRedirect()); + } + + public function test_administrator_switches_the_mode_in_the_admin_and_sees_the_banner(): void + { + config(['fewo.mail_redirect_to' => null]); + $this->actingAs(User::factory()->create()); + + $this->get(Operations::getUrl())->assertOk()->assertSee('Testbetrieb:'); + + Livewire::test(Operations::class) + ->set('data.mode', Settings::MODE_TEST) + ->set('data.test_recipient', 'lars@example.com') + ->call('save') + ->assertHasNoErrors(); + $this->assertSame('lars@example.com', Settings::mailRedirect()); + + Livewire::test(Operations::class)->set('data.mode', Settings::MODE_LIVE)->call('save')->assertNotified('Scharf geschaltet'); + $this->assertTrue(Settings::isLive()); + + $this->actingAs(User::factory()->role(UserRole::Rentals)->create()); + $this->get(Operations::getUrl())->assertForbidden(); + } +} diff --git a/tests/Feature/SpamProtectionTest.php b/tests/Feature/SpamProtectionTest.php new file mode 100644 index 0000000..886dfff --- /dev/null +++ b/tests/Feature/SpamProtectionTest.php @@ -0,0 +1,83 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed(PropertySeeder::class); + Mail::fake(); + } + + public function test_form_sent_faster_than_a_human_is_ignored_silently(): void + { + $this->filled('anna@example.com')->call('submit')->assertHasNoErrors(); + + $this->assertSame(0, Booking::count()); + } + + public function test_honeypot_request_is_ignored(): void + { + $form = $this->filled('anna@example.com')->set('website', 'https://spam.example'); + $this->travel(10)->seconds(); + $form->call('submit'); + + $this->assertSame(0, Booking::count()); + } + + public function test_human_request_after_a_few_seconds_is_accepted(): void + { + $form = $this->filled('anna@example.com'); + $this->travel(10)->seconds(); + $form->call('submit')->assertHasNoErrors()->assertSee('Vielen Dank, Anna!'); + + $this->assertSame(1, Booking::count()); + } + + public function test_one_email_address_cannot_hold_many_dates_at_once(): void + { + foreach ([['2026-11-07', '2026-11-10'], ['2026-11-14', '2026-11-17'], ['2026-11-21', '2026-11-24']] as [$arrival, $departure]) { + $form = $this->filled('anna@example.com', $arrival, $departure); + $this->travel(10)->seconds(); + $form->call('submit'); + } + + $this->assertSame(2, Booking::count()); + } + + public function test_links_in_names_or_many_links_in_the_message_are_rejected(): void + { + $form = $this->filled('anna@example.com')->set('firstName', 'Cheap https://pills.example')->set('message', 'see www.a.example and https://b.example'); + $this->travel(10)->seconds(); + + $form->call('submit')->assertHasErrors(['firstName', 'message']); + $this->assertSame(0, Booking::count()); + } + + private function filled(string $email, string $arrival = '2026-11-07', string $departure = '2026-11-10'): Testable + { + return Livewire::test(BookingRequest::class) + ->set('arrival', $arrival) + ->set('departure', $departure) + ->set('firstName', 'Anna') + ->set('lastName', 'Muster') + ->set('email', $email) + ->set('privacyAccepted', true); + } +}