Loheide-eu-mitarbeiterplatt.../app/Support/Update/Updater.php
Friederich Loheide b2f5d95d39
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 7m2s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 7m21s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 7m32s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 7m47s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 10m53s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 10m36s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 8m59s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 49s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 9m13s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m13s
App-Anmeldung reparieren, Titelbilder erneut verkleinern (0.47.1)
- Updater baut die Paketliste neu (package:discover); Migration einmalig – auf
  älteren Installationen fehlte Sanctum (API 500)
- UploadController: ohne Sanctum-Guard sauber 404 statt 500
- Systemzustand prüft die Anmeldung der App
- Titelbild-Verkleinerung erneut (lief beim Update auf 0.47.0 mit der alten
  Theme-Klasse im Speicher ins Leere)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 17:48:49 +00:00

141 lines
5.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Support\Update;
use App\Support\Audit;
use App\Support\License\ServerError;
use App\Support\License\ServerMessages;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use RuntimeException;
use Throwable;
/**
* Self-Updater: holt den Stand des aktiven Kanals als ZIP, legt ihn über die
* Produktion (mit geschützten Pfaden), migriert, leert Caches und merkt sich
* den neuen Commit-SHA. Ablauf und Prozentwerte nach docs/specs/self-updater.md.
*/
class Updater
{
public function __construct(
private readonly Channels $channels,
private readonly InstalledVersion $version,
private readonly UpdateProgress $progress,
private readonly MaintenanceFlag $maintenance,
private readonly ZipExtractor $extractor,
private readonly Migrations $migrations,
private readonly ?string $basePath = null,
) {}
/**
* @return array{sha: string, migrations: int, files: int}
*/
public function installUpdate(?int $userId = null, ?string $channel = null): array
{
$channel ??= $this->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
{
// Paketliste neu aufbauen – bootstrap/cache ist vor dem Updater geschützt, neue Pakete
// (z. B. Sanctum für die App) würden sonst nie geladen
foreach (['package:discover', '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();
}
}
}