diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a28ab54..3b8fe21a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ Neueste Version oben. Jeder Abschnitt beginnt mit `## MAJOR.MINOR.PATCH` und enthält kurze Stichpunkte für Anwenderinnen und Anwender – keine Commit-Texte. Der Self-Updater zeigt diese Abschnitte bei neuen Versionen an. +## 0.2.0 + +- Aktualisierung per Klick im Admin-Bereich – ohne Serverzugang, mit Wartungsseite und Fortschrittsanzeige +- Lizenz hinterlegen und prüfen, Laufzeit und belegte Geräteplätze einsehen +- Update-Kanäle „Stabil“ und „Entwicklung“ +- Datenbank wird nach einem Update automatisch auf den neuen Stand gebracht +- Änderungsprotokoll im Admin-Bereich + ## 0.1.0 - Erste Fassung des Mitarbeiterportals diff --git a/app/Filament/Pages/Updates.php b/app/Filament/Pages/Updates.php new file mode 100644 index 00000000..3bbd4bd6 --- /dev/null +++ b/app/Filament/Pages/Updates.php @@ -0,0 +1,131 @@ +licenseEmail = (string) $license->email(); + } + + public function saveLicense(LicenseStore $license, LicenseService $service): void + { + $this->validate([ + 'licenseEmail' => ['required', 'email', 'max:255'], + 'licenseKey' => [$license->hasLicense() ? 'nullable' : 'required', 'string', 'max:500'], + ], attributes: ['licenseEmail' => 'Lizenz-E-Mail', 'licenseKey' => 'Lizenzschlüssel']); + + $license->setLicense($this->licenseEmail, filled($this->licenseKey) ? $this->licenseKey : (string) $license->key()); + $this->licenseKey = ''; + Audit::log('license.saved', ['email' => $this->licenseEmail]); + + $this->checkLicense($service); + } + + public function checkLicense(LicenseService $service): void + { + $this->licenseError = null; + + try { + $service->check(); + + Notification::make()->success()->title('Lizenz geprüft')->send(); + } catch (ServerError $e) { + $this->licenseError = ServerMessages::for($e); + } catch (Throwable $e) { + $this->licenseError = 'Die Lizenz konnte nicht geprüft werden: '.$e->getMessage(); + } + } + + public function releaseDevice(LicenseService $service, LicenseStore $license): void + { + try { + $service->releaseDevice(); + Audit::log('license.device_released', ['device_label' => $license->deviceLabel()]); + + Notification::make() + ->success() + ->title('Installation abgemeldet') + ->body('Der Geräteplatz ist wieder frei. Updates sind erst nach erneuter Lizenzprüfung wieder möglich.') + ->send(); + } catch (ServerError $e) { + Notification::make()->danger()->title('Abmelden fehlgeschlagen')->body(ServerMessages::for($e))->send(); + } + } + + /** + * @return array + */ + protected function getViewData(): array + { + $version = app(InstalledVersion::class); + $license = app(LicenseStore::class); + $channels = app(Channels::class); + + try { + $migrations = app(Migrations::class)->status(); + } catch (Throwable) { + $migrations = []; + } + + return [ + 'release' => $version->release(), + 'shortSha' => $version->short(), + 'channels' => $channels->all(), + 'activeChannel' => $channels->active(), + 'progress' => app(UpdateProgress::class)->get(), + 'migrations' => $migrations, + 'pendingMigrations' => count(array_filter($migrations, fn (array $m) => ! $m['ran'])), + 'changelog' => app(Changelog::class)->sections(), + 'hasLicense' => $license->hasLicense(), + 'maskedKey' => ($key = $license->key()) ? str_repeat('•', 8).substr($key, -4) : null, + 'licenseSummary' => app(LicenseService::class)->summary(), + 'licenseStatusError' => ($code = $license->lastStatus()['error_code'] ?? null) + ? ServerMessages::for(new ServerError($code, 0, $code)) + : null, + 'deviceLabel' => $license->deviceLabel(), + ]; + } +} diff --git a/app/Http/Controllers/Admin/UpdateController.php b/app/Http/Controllers/Admin/UpdateController.php new file mode 100644 index 00000000..c80f7781 --- /dev/null +++ b/app/Http/Controllers/Admin/UpdateController.php @@ -0,0 +1,97 @@ +json(['ok' => true, 'result' => $check->run()]); + } catch (ServerError $e) { + return $this->serverError($e); + } + } + + public function install(Request $request, Updater $updater, UpdateProgress $progress): JsonResponse + { + if ($progress->isRunning()) { + return response()->json(['ok' => false, 'message' => 'Es läuft bereits eine Aktualisierung.'], 409); + } + + // Der Ablauf läuft serverseitig zu Ende, auch wenn der Browser die Verbindung trennt. + @set_time_limit(0); + @ignore_user_abort(true); + + try { + $result = $updater->installUpdate($request->user()?->id); + + return response()->json(['ok' => true, 'result' => $result]); + } catch (ServerError $e) { + return $this->serverError($e); + } catch (Throwable $e) { + return response()->json(['ok' => false, 'message' => $e->getMessage()], 500); + } + } + + public function progress(UpdateProgress $progress): JsonResponse + { + return response()->json($progress->get()); + } + + public function channel(Request $request, Channels $channels): JsonResponse + { + $validated = $request->validate([ + 'channel' => ['required', 'string', Rule::in(array_keys($channels->all()))], + ]); + + $channels->setActive($validated['channel']); + Audit::log('update.channel_changed', ['channel' => $validated['channel']]); + + return response()->json(['ok' => true, 'channel' => $validated['channel']]); + } + + public function migrations(Migrations $migrations): JsonResponse + { + @set_time_limit(0); + + try { + $count = $migrations->run(); + @file_put_contents(storage_path('.migrations-fingerprint'), $migrations->fingerprint()); + Audit::log('update.migrations', ['migrations' => $count]); + + return response()->json(['ok' => true, 'count' => $count, 'status' => $migrations->status()]); + } catch (Throwable $e) { + Audit::log('update.migrations_failed', ['error' => $e->getMessage()]); + + return response()->json(['ok' => false, 'message' => 'Migrationen fehlgeschlagen: '.$e->getMessage()], 500); + } + } + + private function serverError(ServerError $e): JsonResponse + { + return response()->json([ + 'ok' => false, + 'code' => $e->errorCode, + 'message' => ServerMessages::for($e), + 'license_input' => $e->needsLicenseInput(), + ], 200); + } +} diff --git a/app/Http/Middleware/EnsureNotInMaintenance.php b/app/Http/Middleware/EnsureNotInMaintenance.php new file mode 100644 index 00000000..d3140f73 --- /dev/null +++ b/app/Http/Middleware/EnsureNotInMaintenance.php @@ -0,0 +1,35 @@ +maintenance->isActive() || $request->is(...self::EXCEPT)) { + return $next($request); + } + + $retryAfter = $this->maintenance->retryAfter(); + + if ($request->expectsJson() || $request->header('X-Inertia')) { + return response()->json(['message' => 'Das Portal wird gerade aktualisiert.'], 503, ['Retry-After' => $retryAfter]); + } + + return response()->view('maintenance', ['retryAfter' => $retryAfter], 503, ['Retry-After' => $retryAfter]); + } +} diff --git a/app/Http/Middleware/RunPendingMigrations.php b/app/Http/Middleware/RunPendingMigrations.php new file mode 100644 index 00000000..3d030c3b --- /dev/null +++ b/app/Http/Middleware/RunPendingMigrations.php @@ -0,0 +1,72 @@ +runningUnitTests() || ! Installation::isInstalled()) { + return $next($request); + } + + $stored = @file_get_contents(storage_path('.migrations-fingerprint')); + + try { + $current = $this->migrations->fingerprint(); + + if ($stored !== $current) { + $this->migrateWithLock($current); + } + } catch (Throwable $e) { + Log::error('Automatische Migration fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]); + } + + return $next($request); + } + + private function migrateWithLock(string $fingerprint): void + { + $lock = @fopen(storage_path('.migrate.lock'), 'c'); + + if ($lock === false || ! flock($lock, LOCK_EX | LOCK_NB)) { + return; // Läuft gerade in einer anderen Anfrage. + } + + try { + // Nach dem Warten auf die Sperre erneut prüfen – vielleicht war jemand schneller. + if (@file_get_contents(storage_path('.migrations-fingerprint')) === $fingerprint) { + return; + } + + @set_time_limit(300); + $count = $this->migrations->run(); + file_put_contents(storage_path('.migrations-fingerprint'), $fingerprint); + + if ($count > 0) { + Log::info("Automatische Migration: {$count} Migration(en) ausgeführt."); + } + } finally { + flock($lock, LOCK_UN); + fclose($lock); + } + } +} diff --git a/app/Models/AuditLog.php b/app/Models/AuditLog.php new file mode 100644 index 00000000..b44d36d5 --- /dev/null +++ b/app/Models/AuditLog.php @@ -0,0 +1,29 @@ + 'array', + 'created_at' => 'datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 934e6a58..fe18b4d1 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,12 +2,18 @@ namespace App\Providers; +use App\Models\User; use App\Support\Avatars; use App\Support\Branding; +use App\Support\License\LicenseStore; use App\Support\Navigation; use App\Support\QuickLinks; use App\Support\Settings; +use App\Support\Update\InstalledVersion; +use App\Support\Update\MaintenanceFlag; +use App\Support\Update\UpdateProgress; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Rules\Password; @@ -20,6 +26,10 @@ class AppServiceProvider extends ServiceProvider $this->app->singleton(Avatars::class); $this->app->singleton(Navigation::class); $this->app->singleton(QuickLinks::class); + $this->app->singleton(LicenseStore::class); + $this->app->singleton(InstalledVersion::class); + $this->app->singleton(UpdateProgress::class); + $this->app->singleton(MaintenanceFlag::class); } public function boot(): void @@ -27,6 +37,9 @@ class AppServiceProvider extends ServiceProvider // N+1-Abfragen in Entwicklung und Tests sofort sichtbar machen (docs/PLAN.md, Performance). Model::preventLazyLoading(! $this->app->isProduction()); + // Vorläufig: Administratoren über is_admin – wird in Phase 2 durch Rollen ersetzt. + Gate::define('admin', fn (User $user) => $user->is_admin && $user->is_active); + Password::defaults(fn () => Password::min(10)->letters()->numbers()); } } diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index c355f28c..cfd8aa47 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -37,7 +37,7 @@ class AdminPanelProvider extends PanelProvider ->colors(fn () => [ 'primary' => app(Branding::class)->palette(), ]) - ->navigationGroups(['Inhalte', 'Portal']) + ->navigationGroups(['Inhalte', 'Portal', 'System']) ->navigationItems([ NavigationItem::make('Zum Portal') ->url('/') diff --git a/app/Support/Audit.php b/app/Support/Audit.php new file mode 100644 index 00000000..346b6863 --- /dev/null +++ b/app/Support/Audit.php @@ -0,0 +1,30 @@ + $data + */ + public static function log(string $action, array $data = [], ?int $userId = null): void + { + $userId ??= auth()->id(); + + Log::info("audit: {$action}", [...$data, 'user_id' => $userId]); + + try { + AuditLog::query()->create(['user_id' => $userId, 'action' => $action, 'data' => $data]); + } catch (Throwable $e) { + Log::warning('Audit-Eintrag konnte nicht gespeichert werden: '.$e->getMessage()); + } + } +} diff --git a/app/Support/Installation.php b/app/Support/Installation.php new file mode 100644 index 00000000..90ebbdd1 --- /dev/null +++ b/app/Support/Installation.php @@ -0,0 +1,20 @@ +environment('local'); + } + + public static function markInstalled(): void + { + file_put_contents(storage_path('.installed'), date(DATE_ATOM)); + } +} diff --git a/app/Support/License/LicenseService.php b/app/Support/License/LicenseService.php new file mode 100644 index 00000000..04feb350 --- /dev/null +++ b/app/Support/License/LicenseService.php @@ -0,0 +1,84 @@ + Antwort von /license (zusätzlich gespeichert) + * + * @throws ServerError + */ + public function check(): array + { + try { + $info = $this->channels->client()->license(); + $this->store->rememberStatus($info); + + return $info; + } catch (ServerError $e) { + Log::notice("Lizenzprüfung: {$e->errorCode}"); + $this->store->rememberStatus(null, $e->errorCode); + + throw $e; + } + } + + /** + * Gibt den Geräteplatz dieser Installation frei. + * + * @throws ServerError + */ + public function releaseDevice(): void + { + $response = VendorHttp::guard(fn () => $this->http->request((int) config('updater.timeouts.json'), identifyDevice: false) + ->post(rtrim(config('updater.api_url'), '/').'/license/release-device?software='.config('updater.software'))); + + if (! $response->successful()) { + throw VendorHttp::errorFrom($response); + } + } + + /** + * Aufbereitete Lizenzdaten für die Anzeige (aus der letzten Prüfung). + * + * @return array|null + */ + public function summary(): ?array + { + $info = $this->store->lastStatus()['info'] ?? null; + + if (! is_array($info)) { + return null; + } + + $license = $info['license'] ?? []; + $unlimited = (bool) ($license['unlimited'] ?? false); + $days = $license['days_remaining'] ?? null; + + return [ + 'status' => $license['status'] ?? null, + // valid_until = null zusammen mit unlimited = true heißt UNBEFRISTET – kein Fehler. + 'unlimited' => $unlimited, + 'valid_until' => $license['valid_until'] ?? null, + 'days_remaining' => is_numeric($days) ? (int) $days : null, + 'expired' => ! $unlimited && (bool) ($license['expired'] ?? false), + 'expires_soon' => ! $unlimited && is_numeric($days) && (int) $days >= 0 && (int) $days < 30, + 'registered_to' => $info['registered_to'] ?? [], + 'devices' => $info['devices'] ?? [], + ]; + } +} diff --git a/app/Support/License/LicenseStore.php b/app/Support/License/LicenseStore.php new file mode 100644 index 00000000..cf4e49d7 --- /dev/null +++ b/app/Support/License/LicenseStore.php @@ -0,0 +1,161 @@ +|null */ + private ?array $data = null; + + public function __construct(private readonly ?string $file = null) {} + + public function email(): ?string + { + return $this->read()['email'] ?? null; + } + + public function key(): ?string + { + $encrypted = $this->read()['key'] ?? null; + + if (! is_string($encrypted) || $encrypted === '') { + return null; + } + + try { + return Crypt::decryptString($encrypted); + } catch (Throwable) { + // APP_KEY hat sich geändert – Schlüssel muss neu eingegeben werden. + return null; + } + } + + public function hasLicense(): bool + { + return filled($this->email()) && filled($this->key()); + } + + public function setLicense(string $email, string $key): void + { + $this->write([ + 'email' => trim($email), + 'key' => Crypt::encryptString(trim($key)), + ]); + } + + public function clearLicense(): void + { + $this->write(['email' => null, 'key' => null, 'device_token' => null]); + } + + public function deviceId(): string + { + $id = $this->read()['device_id'] ?? null; + + if (! is_string($id) || ! preg_match('/^[0-9a-f]{32}$/', $id)) { + $id = bin2hex(random_bytes(16)); + $this->write(['device_id' => $id]); + } + + return $id; + } + + public function deviceToken(): ?string + { + $token = $this->read()['device_token'] ?? null; + + return is_string($token) && $token !== '' ? $token : null; + } + + /** + * Neues Gerätetoken sofort speichern – auch wenn die Antwort ein Fehler war. + */ + public function saveDeviceToken(string $token): void + { + if ($token !== '' && $token !== $this->deviceToken()) { + $this->write(['device_token' => $token]); + } + } + + public function hostname(): string + { + return (string) (gethostname() ?: 'unbekannt'); + } + + /** + * „web01:/var/www/kunde“ – damit der Kunde im Portal erkennt, welcher Geräteplatz welcher ist. + */ + public function deviceLabel(): string + { + return $this->hostname().':'.base_path(); + } + + /** + * Letztes Ergebnis der Lizenzprüfung (für die Anzeige ohne erneute Anfrage). + * + * @param array|null $info + */ + public function rememberStatus(?array $info, ?string $errorCode = null): void + { + $this->write(['last_status' => [ + 'info' => $info, + 'error_code' => $errorCode, + 'checked_at' => time(), + ]]); + } + + /** + * @return array{info: array|null, error_code: string|null, checked_at: int}|null + */ + public function lastStatus(): ?array + { + $status = $this->read()['last_status'] ?? null; + + return is_array($status) ? $status : null; + } + + /** + * @return array + */ + private function read(): array + { + if ($this->data === null) { + $decoded = json_decode((string) @file_get_contents($this->path()), true); + $this->data = is_array($decoded) ? $decoded : []; + } + + return $this->data; + } + + /** + * @param array $changes + */ + private function write(array $changes): void + { + // Immer frisch von der Platte lesen: parallele Anfragen können das Token rotiert haben. + $this->data = null; + $data = array_merge($this->read(), $changes); + + AtomicFile::write($this->path(), json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); + @chmod($this->path(), 0600); + + $this->data = $data; + } + + private function path(): string + { + return $this->file ?? storage_path('app/license.json'); + } +} diff --git a/app/Support/License/ServerError.php b/app/Support/License/ServerError.php new file mode 100644 index 00000000..f0bcae9a --- /dev/null +++ b/app/Support/License/ServerError.php @@ -0,0 +1,38 @@ + $payload + */ + public function __construct( + public readonly string $errorCode, + public readonly int $status, + string $message, + public readonly array $payload = [], + public readonly ?int $retryAfter = null, + ) { + parent::__construct($message); + } + + /** + * Lizenzfehler, bei denen die Eingabemaske die richtige Reaktion ist. + */ + public function needsLicenseInput(): bool + { + return in_array($this->errorCode, ['license_required', 'invalid_key', 'email_mismatch'], true); + } + + public function isTemporary(): bool + { + return in_array($this->errorCode, ['mirror_pending', 'not_released', 'rate_limited', 'maintenance', 'upstream_unavailable', 'unreachable'], true); + } +} diff --git a/app/Support/License/ServerMessages.php b/app/Support/License/ServerMessages.php new file mode 100644 index 00000000..083653bf --- /dev/null +++ b/app/Support/License/ServerMessages.php @@ -0,0 +1,44 @@ +retryAfter ? ' Bitte in etwa '.self::duration($error->retryAfter).' erneut versuchen.' : ' Bitte später erneut versuchen.'; + + return match ($error->errorCode) { + 'license_required' => 'Für Updates ist eine Lizenz nötig. Bitte Lizenz-E-Mail und Lizenzschlüssel hinterlegen.', + 'invalid_key' => 'Der Lizenzschlüssel ist unbekannt. Bitte die Eingabe prüfen.', + 'email_mismatch' => 'Die E-Mail-Adresse passt nicht zu diesem Lizenzschlüssel. Bitte die auf der Lizenz hinterlegte Adresse verwenden.', + 'license_expired' => 'Die Lizenz ist abgelaufen. Updates sind erst nach einer Verlängerung wieder verfügbar – das Portal läuft unverändert weiter.', + 'license_revoked' => 'Die Lizenz wurde gesperrt. Bitte wenden Sie sich an den Support.', + 'device_limit_reached' => sprintf( + 'Alle Geräteplätze der Lizenz sind belegt (%s von %s). Geben Sie im Kundenportal einen Platz frei oder erweitern Sie die Lizenz.', + $error->payload['devices_used'] ?? '?', + $error->payload['devices_max'] ?? '?', + ), + 'device_cloned' => 'Die Lizenz wird offenbar in einer kopierten Installation mehrfach genutzt. Bitte wenden Sie sich an den Support.', + 'device_id_required' => 'Die Lizenz ist gerätegebunden, es wurde aber keine Gerätekennung übermittelt. Bitte wenden Sie sich an den Support.', + 'rate_limited' => 'Zu viele Anfragen in kurzer Zeit.'.$wait, + 'maintenance' => 'Der Update-Server wird gerade gewartet.'.$wait, + 'upstream_unavailable' => 'Der Update-Server ist vorübergehend nicht erreichbar. Die installierte Version bleibt unverändert.'.$wait, + 'mirror_pending' => 'Die neue Version wird gerade bereitgestellt.'.$wait, + 'not_released' => 'Es ist noch keine Version zur Auslieferung freigegeben.'.$wait, + 'unknown_tool' => 'Dieser Update-Kanal ist beim Hersteller noch nicht eingerichtet. Bitte den Kanal „Stabil“ verwenden.', + 'unreachable' => 'Der Update-Server ist nicht erreichbar. Bitte die Internetverbindung des Servers prüfen (ausgehende HTTPS-Verbindungen müssen erlaubt sein).', + 'invalid_response' => 'Der Update-Server hat eine unerwartete Antwort geliefert.'.$wait, + default => 'Der Update-Server meldet einen Fehler ('.$error->errorCode.').'.$wait, + }; + } + + private static function duration(int $seconds): string + { + return $seconds < 90 ? "{$seconds} Sekunden" : (int) ceil($seconds / 60).' Minuten'; + } +} diff --git a/app/Support/License/VendorHttp.php b/app/Support/License/VendorHttp.php new file mode 100644 index 00000000..5297dd2e --- /dev/null +++ b/app/Support/License/VendorHttp.php @@ -0,0 +1,136 @@ +connectTimeout(10) + ->acceptJson() + ->withUserAgent('Inhaus/'.Version::VERSION.' (PHP '.PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION.'; '.PHP_OS_FAMILY.')') + ->withOptions([ + 'allow_redirects' => [ + 'max' => (int) config('updater.max_redirects', 3), + 'protocols' => ['https'], + 'strict' => true, + ], + ]) + ->withResponseMiddleware(fn (ResponseInterface $response) => $this->captureDeviceToken($response)); + + // Ohne hinterlegte Lizenz gar keine Lizenz-Kopfzeilen – nie leere oder erfundene Werte. + if ($this->license->hasLicense()) { + $headers = [ + 'X-License-Email' => $this->license->email(), + 'X-Device-Id' => $this->license->deviceId(), + ]; + + if ($token = $this->license->deviceToken()) { + $headers['X-Device-Token'] = $token; + } + + $request->withToken($this->license->key())->withHeaders($headers); + } + + if ($identifyDevice) { + $request->withQueryParameters(array_filter([ + 'hostname' => $this->license->hostname(), + 'device_label' => $this->license->deviceLabel(), + 'os' => self::operatingSystem(), + 'app_version' => Version::VERSION, + ])); + } + + return $request; + } + + /** + * Wandelt Verbindungsfehler in einen ServerError mit Code „unreachable“ um. + * + * @template T + * + * @param callable(): T $callback + * @return T + */ + public static function guard(callable $callback): mixed + { + try { + return $callback(); + } catch (ConnectionException|ConnectException $e) { + throw new ServerError('unreachable', 0, $e->getMessage()); + } + } + + /** + * Fehlerantwort in einen ServerError übersetzen (Code aus dem JSON, nie aus dem Text). + */ + public static function errorFrom(Response $response, ?string $body = null): ServerError + { + $data = json_decode($body ?? $response->body(), true); + $data = is_array($data) ? $data : []; + $retryAfter = $data['retry_after'] ?? $response->header('Retry-After'); + + return new ServerError( + errorCode: (string) ($data['code'] ?? 'http_'.$response->status()), + status: $response->status(), + message: (string) ($data['error'] ?? $data['message'] ?? 'HTTP '.$response->status()), + payload: $data, + retryAfter: is_numeric($retryAfter) ? (int) $retryAfter : null, + ); + } + + public static function operatingSystem(): string + { + return trim(php_uname('s').' '.php_uname('r')); + } + + private function captureDeviceToken(ResponseInterface $response): ResponseInterface + { + $token = $response->getHeaderLine('X-Device-Token'); + + if ($token === '' && str_contains($response->getHeaderLine('Content-Type'), 'json')) { + $body = $response->getBody(); + $data = json_decode((string) $body, true); + + if ($body->isSeekable()) { + $body->rewind(); + } + + $token = is_array($data) && is_string($data['device_token'] ?? null) ? $data['device_token'] : ''; + } + + if ($token !== '') { + $this->license->saveDeviceToken($token); + } + + return $response; + } +} diff --git a/app/Support/Update/AtomicFile.php b/app/Support/Update/AtomicFile.php new file mode 100644 index 00000000..21e8592a --- /dev/null +++ b/app/Support/Update/AtomicFile.php @@ -0,0 +1,33 @@ +“-Abschnitten und rendert Markdown + * sicher (kein Roh-HTML, keine unsicheren Links). + */ +class Changelog +{ + /** + * @return list + */ + public function sections(?string $markdown = null): array + { + $markdown ??= (string) @file_get_contents(base_path('CHANGELOG.md')); + $parts = preg_split('/^## +/m', $markdown) ?: []; + array_shift($parts); // Einleitung vor dem ersten Abschnitt + + return array_values(array_map(function (string $part) { + [$heading, $body] = array_pad(explode("\n", $part, 2), 2, ''); + $heading = trim($heading); + preg_match('/\d+\.\d+\.\d+(?:[-+][\w.]+)?/', $heading, $m); + + return [ + 'version' => $m[0] ?? $heading, + 'heading' => $heading, + 'html' => $this->toHtml(trim($body)), + ]; + }, $parts)); + } + + public function toHtml(string $markdown): string + { + $converter = new GithubFlavoredMarkdownConverter([ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, + 'max_nesting_level' => 20, + ]); + + return (string) $converter->convert($markdown); + } +} diff --git a/app/Support/Update/Channels.php b/app/Support/Update/Channels.php new file mode 100644 index 00000000..334c8183 --- /dev/null +++ b/app/Support/Update/Channels.php @@ -0,0 +1,65 @@ + Schlüssel => Bezeichnung + */ + public function all(): array + { + return collect(config('updater.channels'))->map(fn (array $c) => $c['label'])->all(); + } + + public function active(): string + { + try { + $channel = $this->settings->get('updater.channel'); + } catch (Throwable) { + $channel = null; // Datenbank nicht erreichbar – Standardkanal. + } + + return is_string($channel) && $this->exists($channel) ? $channel : config('updater.default_channel', 'stable'); + } + + public function setActive(string $channel): void + { + $this->assertExists($channel); + $this->settings->set('updater.channel', $channel); + } + + public function client(?string $channel = null): UpdateClient + { + $channel ??= $this->active(); + $this->assertExists($channel); + + return new UpdateClient($this->http, config("updater.channels.{$channel}.url")); + } + + public function exists(string $channel): bool + { + return is_array(config("updater.channels.{$channel}")); + } + + private function assertExists(string $channel): void + { + if (! $this->exists($channel)) { + throw new InvalidArgumentException("Unbekannter Update-Kanal: {$channel}"); + } + } +} diff --git a/app/Support/Update/Filesystem.php b/app/Support/Update/Filesystem.php new file mode 100644 index 00000000..46e130e1 --- /dev/null +++ b/app/Support/Update/Filesystem.php @@ -0,0 +1,28 @@ +isDir() && ! $item->isLink() ? @rmdir($item->getPathname()) : @unlink($item->getPathname()); + } + + @rmdir($dir); + } +} diff --git a/app/Support/Update/InstalledVersion.php b/app/Support/Update/InstalledVersion.php new file mode 100644 index 00000000..d7b329c8 --- /dev/null +++ b/app/Support/Update/InstalledVersion.php @@ -0,0 +1,60 @@ +path()); + + return is_string($sha) && self::isSha(trim($sha)) ? strtolower(trim($sha)) : null; + } + + public function save(string $sha): void + { + if (! self::isSha($sha)) { + throw new InvalidArgumentException('Ungültiger Commit-Stand: erwartet werden 40 Hex-Zeichen.'); + } + + AtomicFile::write($this->path(), strtolower($sha)); + } + + public function short(): ?string + { + return ($sha = $this->current()) ? substr($sha, 0, 7) : null; + } + + public function release(): string + { + return Version::VERSION; + } + + /** + * „1.4.2 (a1b2c3d)“ bzw. nur „1.4.2“, solange kein Stand bekannt ist. + */ + public function full(): string + { + return $this->release().(($short = $this->short()) ? " ({$short})" : ''); + } + + public static function isSha(string $value): bool + { + return (bool) preg_match('/^[0-9a-f]{40}$/i', $value); + } + + private function path(): string + { + return $this->file ?? storage_path('.version'); + } +} diff --git a/app/Support/Update/MaintenanceFlag.php b/app/Support/Update/MaintenanceFlag.php new file mode 100644 index 00000000..dec64578 --- /dev/null +++ b/app/Support/Update/MaintenanceFlag.php @@ -0,0 +1,59 @@ +path(), json_encode([ + 'since' => time(), + 'until' => time() + $maxSeconds, + ])); + } + + public function deactivate(): void + { + @unlink($this->path()); + } + + public function isActive(): bool + { + if (! is_file($this->path())) { + return false; + } + + $data = json_decode((string) @file_get_contents($this->path()), true); + $until = is_array($data) ? (int) ($data['until'] ?? 0) : 0; + + if ($until <= time()) { + $this->deactivate(); + + return false; + } + + return true; + } + + public function retryAfter(): int + { + $data = json_decode((string) @file_get_contents($this->path()), true); + $remaining = is_array($data) ? (int) ($data['until'] ?? 0) - time() : 0; + + return max(5, min(60, $remaining)); + } + + private function path(): string + { + return $this->file ?? storage_path('.maintenance'); + } +} diff --git a/app/Support/Update/Migrations.php b/app/Support/Update/Migrations.php new file mode 100644 index 00000000..178fa42e --- /dev/null +++ b/app/Support/Update/Migrations.php @@ -0,0 +1,81 @@ + + */ + public function status(): array + { + $ran = $this->ran(); + + return array_map(fn (string $name) => [ + 'name' => $name, + 'ran' => in_array($name, $ran, true), + ], array_keys($this->files())); + } + + /** + * @return list + */ + public function pending(): array + { + return array_values(array_diff(array_keys($this->files()), $this->ran())); + } + + /** + * Führt ausstehende Migrationen aus und gibt deren Anzahl zurück. + */ + public function run(): int + { + $before = count($this->ran()); + + Artisan::call('migrate', ['--force' => true]); + + return count($this->ran()) - $before; + } + + /** + * Fingerabdruck über die Liste der Migrationsdateien. Ändert sich nur, wenn + * Migrationen dazukommen – dann lohnt sich ein Blick auf die Datenbank. + */ + public function fingerprint(): string + { + return sha1(implode("\n", array_keys($this->files()))); + } + + /** + * @return array Name => Pfad + */ + private function files(): array + { + $files = $this->migrator->getMigrationFiles(array_merge( + [database_path('migrations')], + $this->migrator->paths(), + )); + + ksort($files); + + return $files; + } + + /** + * @return list + */ + private function ran(): array + { + $repository = $this->migrator->getRepository(); + + return $repository->repositoryExists() ? $repository->getRan() : []; + } +} diff --git a/app/Support/Update/ProtectedPaths.php b/app/Support/Update/ProtectedPaths.php new file mode 100644 index 00000000..8b16534e --- /dev/null +++ b/app/Support/Update/ProtectedPaths.php @@ -0,0 +1,37 @@ + $paths + */ + public function __construct(private readonly array $paths) {} + + public static function fromConfig(): self + { + return new self(config('updater.protected_paths', [])); + } + + public function isProtected(string $relativePath): bool + { + $path = ltrim(str_replace('\\', '/', $relativePath), '/'); + + foreach ($this->paths as $protected) { + if (str_ends_with($protected, '/')) { + if (str_starts_with($path.'/', $protected)) { + return true; + } + } elseif ($path === $protected) { + return true; + } + } + + return false; + } +} diff --git a/app/Support/Update/StagingApplier.php b/app/Support/Update/StagingApplier.php new file mode 100644 index 00000000..ba98ff44 --- /dev/null +++ b/app/Support/Update/StagingApplier.php @@ -0,0 +1,77 @@ +isDir() || $file->isLink()) { + continue; + } + + $relative = ltrim(str_replace('\\', '/', substr($file->getPathname(), strlen($stagingDir))), '/'); + + if ($this->protected->isProtected($relative)) { + $skipped++; + + continue; + } + + $destination = rtrim($targetDir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$relative; + $directory = dirname($destination); + + if (! is_dir($directory) && ! @mkdir($directory, 0775, true) && ! is_dir($directory)) { + throw new RuntimeException("Verzeichnis {$directory} kann nicht angelegt werden. Bitte Schreibrechte für das Installationsverzeichnis prüfen."); + } + + $temporary = $destination.'.update-'.bin2hex(random_bytes(3)); + + if (! @copy($file->getPathname(), $temporary)) { + throw new RuntimeException("Datei {$relative} ist nicht schreibbar. Bitte Schreibrechte für {$directory} prüfen."); + } + + if (is_file($destination)) { + @chmod($temporary, fileperms($destination) & 0777); + } + + if (! @rename($temporary, $destination)) { + @unlink($temporary); + + throw new RuntimeException("Datei {$relative} kann nicht ersetzt werden. Bitte Schreibrechte für {$directory} prüfen."); + } + + $copied++; + } + + return ['copied' => $copied, 'skipped' => $skipped]; + } +} diff --git a/app/Support/Update/UpdateCheck.php b/app/Support/Update/UpdateCheck.php new file mode 100644 index 00000000..0f003a06 --- /dev/null +++ b/app/Support/Update/UpdateCheck.php @@ -0,0 +1,53 @@ + + */ + public function run(?string $channel = null): array + { + $current = $this->version->current(); + $result = $this->channels->client($channel)->check($current); + $latest = $result['latest_sha'] ?? null; + + // Frische Installation: Die erste Prüfung liefert den Stand zum Merken. + if ($current === null && is_string($latest) && InstalledVersion::isSha($latest)) { + $this->version->save($latest); + } + + $preview = $result['changelog_preview'] ?? null; + $entries = is_array($preview['entries'] ?? null) ? $preview['entries'] : []; + + return [ + 'has_update' => (bool) ($result['has_update'] ?? false), + 'latest_sha' => is_string($latest) ? $latest : null, + 'latest_short' => is_string($latest) ? substr($latest, 0, 7) : null, + 'version' => $result['version'] ?? null, + 'released_at' => $result['released_at'] ?? null, + 'versions_behind' => (int) ($result['versions_behind'] ?? 0), + 'channel_switch' => $result['channel_switch'] ?? null, + // Feld kann fehlen – dann gibt es nichts zu berichten (kein leerer Kasten). + 'changelog' => array_map(fn (array $entry) => [ + 'version' => $entry['version'] ?? null, + 'heading' => $entry['heading'] ?? null, + 'html' => $this->changelog->toHtml((string) ($entry['text'] ?? '')), + ], $entries), + 'changelog_complete' => $preview === null ? true : (bool) ($preview['complete'] ?? true), + 'changelog_url' => config('updater.changelog_url'), + ]; + } +} diff --git a/app/Support/Update/UpdateClient.php b/app/Support/Update/UpdateClient.php new file mode 100644 index 00000000..a65a2856 --- /dev/null +++ b/app/Support/Update/UpdateClient.php @@ -0,0 +1,114 @@ + + */ + public function version(): array + { + return $this->json('version'); + } + + /** + * @return array + */ + public function check(?string $currentSha): array + { + return $this->json('check', $currentSha ? ['current_sha' => $currentSha] : []); + } + + /** + * @return array + */ + public function license(): array + { + return $this->json('license'); + } + + public function changelog(): string + { + $response = $this->send(fn () => $this->http->request((int) config('updater.timeouts.json')) + ->accept('text/markdown') + ->get($this->url('changelog'), ['format' => 'raw'])); + + return $response->body(); + } + + /** + * ZIP in eine Datei streamen – nicht in den Speicher. + * + * @return array{sha: string|null, sha256: string|null} + */ + public function downloadZip(string $sha, string $target): array + { + $response = $this->send(fn () => $this->http->request((int) config('updater.timeouts.zip')) + ->accept('application/zip') + ->sink($target) + ->get($this->url('zip'), ['ref' => $sha]), sinkedTo: $target); + + return [ + 'sha' => $response->header('X-Commit-Sha') ?: null, + 'sha256' => $response->header('X-Content-Sha256') ?: null, + ]; + } + + /** + * @param array $query + * @return array + */ + private function json(string $path, array $query = []): array + { + $response = $this->send(fn () => $this->http->request((int) config('updater.timeouts.json')) + ->get($this->url($path), $query)); + + $data = $response->json(); + + if (! is_array($data)) { + throw new ServerError('invalid_response', $response->status(), 'Antwort ist kein JSON.'); + } + + return $data; + } + + /** + * @param callable(): Response $callback + */ + private function send(callable $callback, ?string $sinkedTo = null): Response + { + $response = VendorHttp::guard($callback); + + if (! $response->successful()) { + // Bei Downloads steht die Fehlerantwort in der Zieldatei. + $body = $sinkedTo && is_file($sinkedTo) ? (string) file_get_contents($sinkedTo) : null; + + throw VendorHttp::errorFrom($response, $body); + } + + return $response; + } + + private function url(string $path): string + { + return rtrim($this->baseUrl, '/').'/'.$path; + } +} diff --git a/app/Support/Update/UpdateProgress.php b/app/Support/Update/UpdateProgress.php new file mode 100644 index 00000000..ac07a695 --- /dev/null +++ b/app/Support/Update/UpdateProgress.php @@ -0,0 +1,70 @@ +path(), json_encode([ + 'pct' => $pct, + 'step' => $step, + 'text' => $text, + 'ts' => time(), + ], JSON_UNESCAPED_UNICODE)); + } + + /** + * Fehlerzustand: pct = -1 unterscheidet ihn eindeutig von „0 % erledigt“. + */ + public function fail(string $text): void + { + $this->set(-1, 'error', $text); + } + + /** + * @return array{pct: int, step: string, text: string, ts: int} + */ + public function get(): array + { + $data = json_decode((string) @file_get_contents($this->path()), true); + + if (! is_array($data) || ! isset($data['pct'], $data['step'])) { + return ['pct' => 0, 'step' => 'idle', 'text' => '', 'ts' => 0]; + } + + return [ + 'pct' => (int) $data['pct'], + 'step' => (string) $data['step'], + 'text' => (string) ($data['text'] ?? ''), + 'ts' => (int) ($data['ts'] ?? 0), + ]; + } + + public function isRunning(): bool + { + $progress = $this->get(); + + return ! in_array($progress['step'], ['idle', 'done', 'error'], true) + && time() - $progress['ts'] < self::STALE_AFTER_SECONDS; + } + + public function clear(): void + { + @unlink($this->path()); + } + + private function path(): string + { + return $this->file ?? storage_path('.update-progress'); + } +} diff --git a/app/Support/Update/Updater.php b/app/Support/Update/Updater.php new file mode 100644 index 00000000..10ecced8 --- /dev/null +++ b/app/Support/Update/Updater.php @@ -0,0 +1,139 @@ +channels->active(); + $zipFile = storage_path('app/update-'.bin2hex(random_bytes(4)).'.zip'); + $staging = storage_path('.update-staging'); + $targetSha = null; + $migrationCount = 0; + + try { + $this->progress->set(0, 'maintenance', 'Wartungsmodus wird aktiviert …'); + $this->maintenance->activate((int) config('updater.maintenance_max_seconds', 600)); + + $this->progress->set(5, 'version', 'Neueste Version wird ermittelt …'); + $client = $this->channels->client($channel); + $targetSha = (string) ($client->version()['sha'] ?? ''); + + if (! InstalledVersion::isSha($targetSha)) { + throw new RuntimeException('Der Update-Server hat keinen gültigen Versionsstand gemeldet.'); + } + + $this->progress->set(20, 'download', 'Neue Version wird heruntergeladen …'); + $headers = $client->downloadZip($targetSha, $zipFile); + $this->verifyZip($zipFile, $headers); + + $this->progress->set(50, 'extract', 'Archiv wird entpackt …'); + $this->extractor->extract($zipFile, $staging); + + $this->progress->set(65, 'apply', 'Dateien werden übernommen …'); + $result = (new StagingApplier(ProtectedPaths::fromConfig()))->apply($staging, $this->basePath ?? base_path()); + + $this->progress->set(80, 'migrate', 'Datenbank wird aktualisiert …'); + $migrationCount = $this->migrations->run(); + + $this->progress->set(90, 'cache', 'Zwischenspeicher werden geleert …'); + $this->clearCaches(); + + $this->version->save($targetSha); + @file_put_contents(storage_path('.migrations-fingerprint'), $this->migrations->fingerprint()); + + Audit::log('update.installed', [ + 'channel' => $channel, + 'sha' => $targetSha, + 'migrations' => $migrationCount, + 'files' => $result['copied'], + ], $userId); + + $this->progress->set(100, 'done', 'Aktualisierung abgeschlossen.'); + + return ['sha' => $targetSha, 'migrations' => $migrationCount, 'files' => $result['copied']]; + } catch (Throwable $e) { + $message = $e instanceof ServerError ? ServerMessages::for($e) : $e->getMessage(); + + $this->progress->fail($message); + Log::error('Update fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]); + Audit::log('update.failed', [ + 'channel' => $channel, + 'sha' => $targetSha, + 'migrations' => $migrationCount, + 'error' => $message, + 'code' => $e instanceof ServerError ? $e->errorCode : null, + ], $userId); + + throw $e; + } finally { + $this->maintenance->deactivate(); + @unlink($zipFile); + Filesystem::deleteDirectory($staging); + } + } + + /** + * @param array{sha: string|null, sha256: string|null} $headers + */ + private function verifyZip(string $file, array $headers): void + { + $handle = @fopen($file, 'rb'); + $magic = $handle ? fread($handle, 2) : ''; + + if ($handle) { + fclose($handle); + } + + if ($magic !== 'PK') { + throw new RuntimeException('Die Antwort des Update-Servers ist kein ZIP-Archiv (vermutlich eine Fehlerseite). Die installierte Version bleibt unverändert.'); + } + + if ($headers['sha256'] && ! hash_equals(strtolower($headers['sha256']), hash_file('sha256', $file))) { + throw new RuntimeException('Das heruntergeladene Archiv ist beschädigt (Prüfsumme stimmt nicht). Bitte erneut versuchen.'); + } + } + + private function clearCaches(): void + { + foreach (['cache:clear', 'view:clear', 'config:clear', 'route:clear', 'event:clear'] as $command) { + try { + Artisan::call($command); + } catch (Throwable $e) { + Log::warning("{$command} fehlgeschlagen: ".$e->getMessage()); + } + } + + // Bytecode-Cache verwerfen – sonst läuft noch eine Weile der alte Code. + if (function_exists('opcache_reset')) { + @opcache_reset(); + } + } +} diff --git a/app/Support/Update/ZipExtractor.php b/app/Support/Update/ZipExtractor.php new file mode 100644 index 00000000..6b22294c --- /dev/null +++ b/app/Support/Update/ZipExtractor.php @@ -0,0 +1,146 @@ +/“). + * + * ZIP-Slip-Schutz in zwei Stufen: + * a) Eintragsnamen vorab ablehnen: absolute Pfade, Laufwerksbuchstaben, + * „..“-Segmente, Null-Bytes. + * b) Nach dem Schreiben den aufgelösten Pfad prüfen – liegt er wirklich im + * Staging? Sonst sofort wieder löschen. Fängt ab, was (a) übersieht. + */ +class ZipExtractor +{ + /** + * @return int Anzahl entpackter Dateien + */ + public function extract(string $zipFile, string $targetDir): int + { + $zip = new ZipArchive; + + if ($zip->open($zipFile) !== true) { + throw new RuntimeException('Das heruntergeladene Archiv kann nicht geöffnet werden.'); + } + + try { + $this->recreate($targetDir); + $root = realpath($targetDir); + $prefix = $this->commonPrefix($zip); + $count = 0; + + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = (string) $zip->getNameIndex($i); + + if (! self::isSafeEntryName($name)) { + throw new RuntimeException("Unsicherer Pfad im Archiv abgelehnt: {$name}"); + } + + $relative = substr($name, strlen($prefix)); + + if ($relative === '' || $relative === false) { + continue; + } + + $destination = $root.DIRECTORY_SEPARATOR.$relative; + + if (str_ends_with($name, '/')) { + $this->makeDirectory($destination); + + continue; + } + + $this->makeDirectory(dirname($destination)); + $stream = $zip->getStream($name); + + if ($stream === false || @file_put_contents($destination, $stream) === false) { + throw new RuntimeException("Datei {$relative} kann nicht entpackt werden. Bitte Schreibrechte für storage/ prüfen."); + } + + fclose($stream); + + // Stufe b: aufgelösten Pfad prüfen (Symlinks, ungewöhnliche Kodierungen). + $resolved = realpath($destination); + + if ($resolved === false || ! str_starts_with($resolved, $root.DIRECTORY_SEPARATOR)) { + @unlink($destination); + + throw new RuntimeException("Datei außerhalb des Entpackverzeichnisses abgelehnt: {$name}"); + } + + $count++; + } + + return $count; + } finally { + $zip->close(); + } + } + + /** + * Stufe a: Eintragsnamen vor dem Schreiben prüfen. + */ + public static function isSafeEntryName(string $name): bool + { + if ($name === '' || str_contains($name, "\0")) { + return false; + } + + $normalized = str_replace('\\', '/', $name); + + if (str_starts_with($normalized, '/') || preg_match('#^[a-zA-Z]:#', $normalized)) { + return false; + } + + foreach (explode('/', $normalized) as $segment) { + if ($segment === '..') { + return false; + } + } + + return true; + } + + /** + * GitHub-Stil: genau EIN gemeinsamer Top-Level-Ordner, der entfernt wird. + */ + private function commonPrefix(ZipArchive $zip): string + { + $prefix = null; + + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = str_replace('\\', '/', (string) $zip->getNameIndex($i)); + $first = explode('/', $name, 2)[0].'/'; + + if (! str_contains($name, '/')) { + return ''; + } + + if ($prefix === null) { + $prefix = $first; + } elseif ($prefix !== $first) { + return ''; + } + } + + return $prefix ?? ''; + } + + private function recreate(string $dir): void + { + Filesystem::deleteDirectory($dir); + $this->makeDirectory($dir); + } + + private function makeDirectory(string $dir): void + { + if (! is_dir($dir) && ! @mkdir($dir, 0775, true) && ! is_dir($dir)) { + throw new RuntimeException("Verzeichnis {$dir} kann nicht angelegt werden. Bitte Schreibrechte prüfen."); + } + } +} diff --git a/app/Version.php b/app/Version.php index 95cd8033..ac86a3fb 100644 --- a/app/Version.php +++ b/app/Version.php @@ -9,5 +9,5 @@ namespace App; */ final class Version { - public const VERSION = '0.1.0'; + public const VERSION = '0.2.0'; } diff --git a/bootstrap/app.php b/bootstrap/app.php index 8a497e80..836b7514 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,6 +1,8 @@ withMiddleware(function (Middleware $middleware): void { - $middleware->web(append: [ + $middleware->web(prepend: [ + EnsureNotInMaintenance::class, + ], append: [ + RunPendingMigrations::class, HandleInertiaRequests::class, ]); }) diff --git a/config/updater.php b/config/updater.php new file mode 100644 index 00000000..3d9d5b9b --- /dev/null +++ b/config/updater.php @@ -0,0 +1,61 @@ + 'mitarbeiterportal', + + // Update-Kanäle: jeweils eigene Proxy-Basis-URL. Standard ist „stable“. + 'channels' => [ + 'stable' => [ + 'label' => 'Stabil', + 'url' => 'https://update.loheide.cloud/mitarbeiterportal', + ], + 'development' => [ + 'label' => 'Entwicklung', + 'url' => 'https://update.loheide.cloud/mitarbeiterportal-development', + ], + ], + + 'default_channel' => 'stable', + + 'api_url' => 'https://api.loheide.cloud/v1', + + 'changelog_url' => 'https://update.loheide.cloud/mitarbeiterportal/changelog', + + 'timeouts' => [ + 'json' => 20, + 'zip' => 180, + ], + + 'max_redirects' => 3, + + // Werden beim Übernehmen eines Updates NIE überschrieben. + // Verzeichnisse mit Schrägstrich am Ende, Dateien exakt. + // Abweichung von der Vorgabe: vendor/ ist bewusst NICHT geschützt (docs/PLAN.md, 5.2). + 'protected_paths' => [ + '.env', + '.git/', + 'storage/', + 'bootstrap/cache/', + 'node_modules/', + 'vendor-dev/', + 'composer.lock', + 'package-lock.json', + 'plugins/', + 'public/storage/', + 'public/uploads/', + 'public/hot', + 'config/local.php', + '.htaccess', + 'database/database.sqlite', + ], + + // Wartungsmodus läuft spätestens nach dieser Zeit von allein aus. + 'maintenance_max_seconds' => 600, + +]; diff --git a/database/migrations/2026_09_26_000003_create_audit_logs_table.php b/database/migrations/2026_09_26_000003_create_audit_logs_table.php new file mode 100644 index 00000000..6fbf80aa --- /dev/null +++ b/database/migrations/2026_09_26_000003_create_audit_logs_table.php @@ -0,0 +1,26 @@ +id(); + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->string('action', 100); + $table->json('data')->nullable(); + $table->timestamp('created_at')->useCurrent(); + + $table->index(['action', 'created_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('audit_logs'); + } +}; diff --git a/resources/views/filament/pages/updates.blade.php b/resources/views/filament/pages/updates.blade.php new file mode 100644 index 00000000..54e9ce77 --- /dev/null +++ b/resources/views/filament/pages/updates.blade.php @@ -0,0 +1,360 @@ + + + + + +
+ {{-- Version und Kanal --}} + +
+
+
Installierte Version
+
{{ $release }} @if ($shortSha)({{ $shortSha }})@endif
+
+ +
+
+ + {{-- Suche und Installation --}} + +
+
+ + Nach Updates suchen + + +
+ + + + + + + + + + {{-- Datenschutzhinweis: dauerhaft sichtbar, Wortlaut nach Vorgabe (docs/specs/self-updater.md). --}} +
+

Bei der Suche nach Updates und beim Herunterladen einer neuen Fassung werden Daten an update.loheide.cloud übertragen. Übermittelt werden:

+
    +
  • die auf Ihrer Lizenz hinterlegte E-Mail-Adresse und der Lizenzschlüssel
  • +
  • eine Gerätekennung, die dieses Programm einmalig als Zufallszahl erzeugt hat (keine Hardwarekennung, keine Seriennummer) – damit wird gezählt, auf wie vielen Geräten die Lizenz genutzt wird
  • +
  • Rechnername, Betriebssystem und Programmversion, damit Sie Ihre Geräte im Kundenportal auseinanderhalten können
  • +
  • der bei Ihnen installierte Stand, damit die Gegenstelle weiß, was neu ist
  • +
  • technisch bedingt: Ihre IP-Adresse, Datum und Uhrzeit des Abrufs
  • +
+

Zweck: Bereitstellung der Aktualisierung und Prüfung der Lizenz.

+

Nicht übertragen werden Inhalte aus diesem Programm: keine Dokumente, keine Datenbank, keine Eingaben. Die Verbindung ist verschlüsselt.

+
+
+
+ + {{-- Lizenz --}} + +
+ @if ($licenseError || $licenseStatusError) + + @endif + + @if ($licenseSummary) + @if ($licenseSummary['expires_soon']) + + @endif + + + + + + +
Registriert auf{{ collect([$licenseSummary['registered_to']['company'] ?? null, $licenseSummary['registered_to']['contact_name'] ?? null])->filter()->implode(' · ') ?: '–' }}
Laufzeit + @if ($licenseSummary['unlimited']) + unbefristet + @elseif ($licenseSummary['expired']) + abgelaufen + @elseif ($licenseSummary['valid_until']) + bis {{ \Illuminate\Support\Carbon::parse($licenseSummary['valid_until'])->format('d.m.Y') }}@if ($licenseSummary['days_remaining'] !== null) (noch {{ $licenseSummary['days_remaining'] }} Tage)@endif + @else + – + @endif +
Geräteplätze{{ $licenseSummary['devices']['used'] ?? '?' }} von {{ $licenseSummary['devices']['max'] ?? '?' }} belegt
Diese Installation{{ $deviceLabel }}
+ @endif + +
+
+ + +
+

Die Lizenz-E-Mail ist die Adresse, auf die die Lizenz ausgestellt ist – nicht zwingend Ihre eigene.

+
+ Speichern und prüfen + @if ($hasLicense) + Lizenz prüfen + + Diese Installation abmelden + + @endif +
+
+
+
+ + {{-- Migrationen --}} + +
+
+ Migrationen ausführen + +
+ + @foreach ($migrations as $migration) + + + + + @endforeach +
{{ $migration['name'] }} + {{ $migration['ran'] ? 'angewendet' : 'offen' }} +
+
+
+ + {{-- Änderungsprotokoll --}} + + @forelse ($changelog as $section) +
+
Version {{ $section['heading'] }}
+
{!! $section['html'] !!}
+
+ @empty +

Kein Änderungsprotokoll vorhanden.

+ @endforelse +
+
+ +
diff --git a/resources/views/maintenance.blade.php b/resources/views/maintenance.blade.php new file mode 100644 index 00000000..51a2b223 --- /dev/null +++ b/resources/views/maintenance.blade.php @@ -0,0 +1,25 @@ + + + + + + + Wartung + + + +
+ +

Das Portal wird gerade aktualisiert

+

Das dauert meist nur wenige Minuten. Diese Seite lädt sich automatisch neu.

+
+ + diff --git a/routes/web.php b/routes/web.php index 14c44948..9ecfe000 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,5 +1,6 @@ group(function () { Route::delete('/profil/bild', [ProfileController::class, 'destroyAvatar'])->name('profile.avatar.destroy'); Route::put('/profil/darstellung', [ProfileController::class, 'updateTheme'])->name('profile.theme.update'); }); + +// Self-Updater (docs/specs/self-updater.md) – nur für Administratoren, CSRF über die web-Gruppe. +Route::middleware(['auth', 'can:admin'])->prefix('admin/update')->name('admin.update.')->group(function () { + Route::post('/check', [UpdateController::class, 'check'])->name('check'); + Route::post('/install', [UpdateController::class, 'install'])->name('install'); + Route::get('/progress', [UpdateController::class, 'progress'])->name('progress'); + Route::post('/channel', [UpdateController::class, 'channel'])->name('channel'); + Route::post('/migrations', [UpdateController::class, 'migrations'])->name('migrations'); +}); diff --git a/tests/Feature/Update/ArchiveTest.php b/tests/Feature/Update/ArchiveTest.php new file mode 100644 index 00000000..2a5a4f7f --- /dev/null +++ b/tests/Feature/Update/ArchiveTest.php @@ -0,0 +1,148 @@ +dir = sys_get_temp_dir().'/inhaus-zip-'.bin2hex(random_bytes(4)); + mkdir($this->dir); + } + + protected function tearDown(): void + { + Filesystem::deleteDirectory($this->dir); + + parent::tearDown(); + } + + /** + * @param array $files + */ + private function zip(array $files): string + { + $path = $this->dir.'/archiv.zip'; + $zip = new ZipArchive; + $zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE); + + foreach ($files as $name => $contents) { + $zip->addFromString($name, $contents); + } + + $zip->close(); + + return $path; + } + + public function test_common_top_level_folder_is_stripped(): void + { + $zip = $this->zip([ + 'repo-abc/app/Version.php' => ' 'Hallo', + ]); + + $count = (new ZipExtractor)->extract($zip, $this->dir.'/staging'); + + $this->assertSame(2, $count); + $this->assertFileExists($this->dir.'/staging/app/Version.php'); + $this->assertFileExists($this->dir.'/staging/README.md'); + } + + public function test_zip_slip_creates_nothing_outside_staging(): void + { + $zip = $this->zip([ + 'repo-abc/ok.txt' => 'ok', + 'repo-abc/../../evil.php' => 'extract($zip, $this->dir.'/staging'); + $this->fail('Das Archiv hätte abgelehnt werden müssen.'); + } catch (RuntimeException $e) { + $this->assertStringContainsString('Unsicherer Pfad', $e->getMessage()); + } + + $this->assertFileDoesNotExist($this->dir.'/evil.php'); + $this->assertFileDoesNotExist(dirname($this->dir).'/evil.php'); + $this->assertFileDoesNotExist($this->dir.'/staging/../evil.php'); + } + + public function test_dangerous_entry_names_are_rejected(): void + { + foreach (['../evil', 'a/../../evil', '/etc/passwd', 'C:\\Windows\\evil.dll', "a\0b", '..\\evil'] as $name) { + $this->assertFalse(ZipExtractor::isSafeEntryName($name), $name); + } + + foreach (['app/Version.php', 'repo-abc/public/.htaccess', 'a/..b/c'] as $name) { + $this->assertTrue(ZipExtractor::isSafeEntryName($name), $name); + } + } + + public function test_protected_paths_are_skipped_and_nothing_is_deleted(): void + { + $staging = $this->dir.'/staging'; + $target = $this->dir.'/target'; + + foreach ([ + 'app/Neu.php' => 'neu', + 'app/Version.php' => 'neue Version', + '.env' => 'APP_KEY=aus-dem-archiv', + 'storage/app/license.json' => '{}', + 'public/uploads/bild.jpg' => 'fremd', + 'plugins/kunde/plugin.json' => '{}', + 'vendor/autoload.php' => 'neu', + ] as $file => $contents) { + @mkdir(dirname("{$staging}/{$file}"), 0777, true); + file_put_contents("{$staging}/{$file}", $contents); + } + + foreach ([ + 'app/Version.php' => 'alte Version', + 'app/Alt.php' => 'bleibt', + '.env' => 'APP_KEY=geheim', + 'storage/app/license.json' => '{"email":"lizenz@example.com"}', + ] as $file => $contents) { + @mkdir(dirname("{$target}/{$file}"), 0777, true); + file_put_contents("{$target}/{$file}", $contents); + } + + $result = (new StagingApplier(new ProtectedPaths(config('updater.protected_paths'))))->apply($staging, $target); + + $this->assertSame(['copied' => 3, 'skipped' => 4], $result); + $this->assertSame('neue Version', file_get_contents("{$target}/app/Version.php")); + $this->assertSame('neu', file_get_contents("{$target}/app/Neu.php")); + $this->assertSame('neu', file_get_contents("{$target}/vendor/autoload.php")); + $this->assertSame('bleibt', file_get_contents("{$target}/app/Alt.php")); + $this->assertSame('APP_KEY=geheim', file_get_contents("{$target}/.env")); + $this->assertSame('{"email":"lizenz@example.com"}', file_get_contents("{$target}/storage/app/license.json")); + $this->assertFileDoesNotExist("{$target}/public/uploads/bild.jpg"); + $this->assertFileDoesNotExist("{$target}/plugins/kunde/plugin.json"); + $this->assertEmpty(glob("{$target}/app/*.update-*")); + } + + public function test_protected_path_matching(): void + { + $paths = new ProtectedPaths(['.env', 'storage/', 'config/local.php']); + + $this->assertTrue($paths->isProtected('.env')); + $this->assertTrue($paths->isProtected('storage')); + $this->assertTrue($paths->isProtected('storage/logs/x.log')); + $this->assertTrue($paths->isProtected('config/local.php')); + $this->assertFalse($paths->isProtected('.env.example')); + $this->assertFalse($paths->isProtected('storagebox/a')); + $this->assertFalse($paths->isProtected('config/app.php')); + } +} diff --git a/tests/Feature/Update/LicenseTest.php b/tests/Feature/Update/LicenseTest.php new file mode 100644 index 00000000..c31c6986 --- /dev/null +++ b/tests/Feature/Update/LicenseTest.php @@ -0,0 +1,193 @@ +dir = sys_get_temp_dir().'/inhaus-lic-'.bin2hex(random_bytes(4)); + mkdir($this->dir); + $this->app->instance(LicenseStore::class, new LicenseStore($this->dir.'/license.json')); + $this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version')); + } + + protected function tearDown(): void + { + Filesystem::deleteDirectory($this->dir); + + parent::tearDown(); + } + + private function store(): LicenseStore + { + return app(LicenseStore::class); + } + + public function test_device_id_is_created_once_and_kept(): void + { + $id = $this->store()->deviceId(); + + $this->assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $id); + $this->assertSame($id, (new LicenseStore($this->dir.'/license.json'))->deviceId()); + } + + public function test_license_headers_are_sent_with_device_data(): void + { + $this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL-123'); + $this->store()->saveDeviceToken('token-1'); + Http::fake(['*' => Http::response(['has_update' => false, 'latest_sha' => str_repeat('a', 40)])]); + + app(Channels::class)->client()->check(null); + + Http::assertSent(function (Request $request) { + parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query); + + return $request->hasHeader('X-License-Email', 'lizenz@firma.de') + && $request->hasHeader('Authorization', 'Bearer SCHLUESSEL-123') + && $request->hasHeader('X-Device-Id', $this->store()->deviceId()) + && $request->hasHeader('X-Device-Token', 'token-1') + && ($query['hostname'] ?? null) === gethostname() + && str_contains($query['device_label'] ?? '', base_path()) + && ($query['app_version'] ?? null) === Version::VERSION + && str_starts_with($request->url(), 'https://update.loheide.cloud/mitarbeiterportal/check'); + }); + } + + public function test_no_license_headers_without_license(): void + { + Http::fake(['*' => Http::response(['code' => 'license_required', 'error' => 'x'], 401)]); + + try { + app(Channels::class)->client()->version(); + } catch (ServerError) { + } + + Http::assertSent(fn (Request $request) => ! $request->hasHeader('X-License-Email') + && ! $request->hasHeader('Authorization') + && ! $request->hasHeader('X-Device-Id')); + } + + public function test_new_device_token_is_stored_even_on_error_responses(): void + { + $this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL'); + + Http::fake(['*' => Http::response(['code' => 'license_expired', 'error' => 'abgelaufen'], 403, ['X-Device-Token' => 'rotiert-im-fehler'])]); + + try { + app(Channels::class)->client()->check(null); + $this->fail('Fehler erwartet.'); + } catch (ServerError $e) { + $this->assertSame('license_expired', $e->errorCode); + } + + $this->assertSame('rotiert-im-fehler', (new LicenseStore($this->dir.'/license.json'))->deviceToken()); + } + + public function test_device_token_from_json_body_is_stored(): void + { + $this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL'); + Http::fake(['*' => Http::response(['sha' => str_repeat('b', 40), 'device_token' => 'aus-dem-json'])]); + + $data = app(Channels::class)->client()->version(); + + $this->assertSame(str_repeat('b', 40), $data['sha']); + $this->assertSame('aus-dem-json', $this->store()->deviceToken()); + } + + public function test_device_token_from_download_is_stored(): void + { + $this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL'); + Http::fake(['*' => Http::response('PK...', 200, ['X-Device-Token' => 'vom-download'])]); + + app(Channels::class)->client()->downloadZip(str_repeat('c', 40), $this->dir.'/x.zip'); + + $this->assertSame('vom-download', $this->store()->deviceToken()); + } + + public function test_license_errors_give_messages_and_never_block_the_portal(): void + { + $admin = User::factory()->admin()->create(); + $this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL'); + + $code = null; + Http::fake(function () use (&$code) { + return Http::response( + ['code' => $code, 'error' => 'egal', 'devices_used' => 3, 'devices_max' => 3], + $code === 'rate_limited' ? 429 : 403, + ); + }); + + foreach ([ + 'license_expired' => 'abgelaufen', + 'invalid_key' => 'Lizenzschlüssel ist unbekannt', + 'device_limit_reached' => '3 von 3', + 'license_revoked' => 'Support', + 'device_cloned' => 'kopierten Installation', + 'rate_limited' => 'erneut versuchen', + ] as $code => $expected) { + $response = $this->actingAs($admin) + ->postJson('/admin/update/check') + ->assertOk() + ->assertJson(['ok' => false, 'code' => $code]); + + $this->assertStringContainsString($expected, $response->json('message')); + + // Das Portal bleibt uneingeschränkt nutzbar. + $this->actingAs($admin)->get('/')->assertOk(); + $this->actingAs($admin)->get('/admin')->assertOk(); + $this->actingAs($admin)->get('/admin/aktualisierung')->assertOk(); + } + } + + public function test_unlimited_license_is_not_treated_as_expired(): void + { + $this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL'); + Http::fake(['*' => Http::response([ + 'licensing_required' => true, + 'license' => ['status' => 'active', 'valid_until' => null, 'unlimited' => true, 'days_remaining' => null, 'expired' => false], + 'registered_to' => ['license_email' => 'lizenz@firma.de', 'company' => 'Beispiel GmbH', 'contact_name' => 'Max Muster'], + 'devices' => ['used' => 1, 'max' => 2, 'policy' => 'enforce'], + ])]); + + app(LicenseService::class)->check(); + $summary = app(LicenseService::class)->summary(); + + $this->assertTrue($summary['unlimited']); + $this->assertFalse($summary['expired']); + $this->assertFalse($summary['expires_soon']); + + $this->actingAs(User::factory()->admin()->create()) + ->get('/admin/aktualisierung') + ->assertOk() + ->assertSee('unbefristet') + ->assertSee('Beispiel GmbH') + ->assertSee('1 von 2 belegt'); + } + + public function test_unknown_channel_is_rejected(): void + { + $this->expectException(\InvalidArgumentException::class); + + app(Channels::class)->client('nightly'); + } +} diff --git a/tests/Feature/Update/UpdateEndpointsTest.php b/tests/Feature/Update/UpdateEndpointsTest.php new file mode 100644 index 00000000..2987e3bd --- /dev/null +++ b/tests/Feature/Update/UpdateEndpointsTest.php @@ -0,0 +1,142 @@ +dir = sys_get_temp_dir().'/inhaus-ep-'.bin2hex(random_bytes(4)); + mkdir($this->dir); + $this->app->instance(MaintenanceFlag::class, new MaintenanceFlag($this->dir.'/.maintenance')); + $this->app->instance(UpdateProgress::class, new UpdateProgress($this->dir.'/.progress')); + $this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version')); + } + + protected function tearDown(): void + { + Filesystem::deleteDirectory($this->dir); + + parent::tearDown(); + } + + public function test_update_endpoints_are_admin_only(): void + { + $this->postJson('/admin/update/check')->assertUnauthorized(); + + $user = User::factory()->create(); + + foreach (['check', 'install', 'channel', 'migrations'] as $endpoint) { + $this->actingAs($user)->postJson("/admin/update/{$endpoint}")->assertForbidden(); + } + + $this->actingAs($user)->getJson('/admin/update/progress')->assertForbidden(); + $this->actingAs($user)->get('/admin/aktualisierung')->assertForbidden(); + } + + public function test_maintenance_mode_shows_503_but_keeps_update_pages_reachable(): void + { + $admin = User::factory()->admin()->create(); + app(MaintenanceFlag::class)->activate(300); + + $this->actingAs($admin)->get('/') + ->assertStatus(503) + ->assertHeader('Retry-After') + ->assertSee('Das Portal wird gerade aktualisiert'); + + $this->actingAs($admin)->getJson('/admin/update/progress')->assertOk()->assertJson(['step' => 'idle']); + $this->actingAs($admin)->get('/admin/aktualisierung')->assertOk(); + $this->get('/up')->assertOk(); + + app(MaintenanceFlag::class)->deactivate(); + $this->actingAs($admin)->get('/')->assertOk(); + } + + public function test_first_check_of_fresh_installation_remembers_latest_sha(): void + { + Http::fake(['*' => Http::response(['has_update' => false, 'latest_sha' => str_repeat('d', 40), 'version' => '0.2.0'])]); + + $this->actingAs(User::factory()->admin()->create()) + ->postJson('/admin/update/check') + ->assertOk() + ->assertJson(['ok' => true, 'result' => ['has_update' => false, 'changelog' => []]]); + + Http::assertSent(fn ($request) => ! str_contains($request->url(), 'current_sha')); + $this->assertSame(str_repeat('d', 40), app(InstalledVersion::class)->current()); + } + + public function test_check_shows_changelog_preview_without_commit_texts(): void + { + app(InstalledVersion::class)->save(str_repeat('a', 40)); + + Http::fake(['*' => Http::response([ + 'has_update' => true, + 'latest_sha' => str_repeat('b', 40), + 'version' => '0.3.0', + 'versions_behind' => 4, + 'changelog_preview' => [ + 'entries' => [['version' => '0.3.0', 'heading' => '0.3.0', 'text' => "- Neue **Umfragen**\n- "]], + 'complete' => false, + ], + ])]); + + $response = $this->actingAs(User::factory()->admin()->create()) + ->postJson('/admin/update/check') + ->assertOk() + ->assertJsonPath('result.has_update', true) + ->assertJsonPath('result.version', '0.3.0') + ->assertJsonPath('result.latest_short', 'bbbbbbb') + ->assertJsonPath('result.versions_behind', 4) + ->assertJsonPath('result.changelog_complete', false); + + Http::assertSent(fn ($request) => str_contains($request->url(), 'current_sha='.str_repeat('a', 40))); + $this->assertStringContainsString('Umfragen', $response->json('result.changelog.0.html')); + $this->assertStringNotContainsString(' + + ## 1.1.3 – Fehlerbehebung + + - Fix + MD); + + $this->assertCount(2, $sections); + $this->assertSame('1.2.0', $sections[0]['version']); + $this->assertSame('1.1.3', $sections[1]['version']); + $this->assertSame('1.1.3 – Fehlerbehebung', $sections[1]['heading']); + $this->assertStringContainsString('Funktion', $sections[0]['html']); + $this->assertStringNotContainsString('javascript:', $sections[0]['html']); + $this->assertStringNotContainsString('