Self-Updater und Lizenzprüfung
Umsetzung von docs/specs/self-updater.md für Laravel: - Installierter Stand als SHA in storage/.version, Fortschritt in storage/.update-progress, selbstheilender Wartungsmodus in storage/.maintenance - Update-Client je Kanal (stable/development), nur HTTPS, begrenzte Redirects, ZIP-Download per Stream mit PK- und SHA-256-Prüfung - Entpacken mit zweistufigem ZIP-Slip-Schutz, Übernahme mit geschützten Pfaden (atomar je Datei, nie löschen), Migrationen, Cache- und OPcache-Reset - Lizenzspeicher außerhalb der DB, Geräte-ID als Zufallszahl, rotierendes Gerätetoken wird bei jeder Antwort (auch Fehler und Downloads) sofort gespeichert - Lizenzfehler mit verständlichen Meldungen – sie sperren nie das Portal - Seite „Aktualisierung“ mit Kanal, Suche, Changelog-Vorschau, Fortschritt, Migrationen, Änderungsprotokoll, Lizenz und Datenschutzhinweis - Wartungs-Middleware (503 + Retry-After) und Auto-Migration per Fingerabdruck - Audit-Log für Updates, Kanalwechsel und Lizenzänderungen - Version 0.2.0 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
a36752e09a
commit
43244d751a
41 changed files with 3184 additions and 3 deletions
33
app/Support/Update/AtomicFile.php
Normal file
33
app/Support/Update/AtomicFile.php
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Schreibt Dateien erst daneben und benennt sie dann um – ein Abbruch mittendrin
|
||||
* hinterlässt so nie eine halbe Datei.
|
||||
*/
|
||||
final class AtomicFile
|
||||
{
|
||||
public static function write(string $path, string $contents): void
|
||||
{
|
||||
$directory = dirname($path);
|
||||
|
||||
if (! is_dir($directory) && ! @mkdir($directory, 0775, true) && ! is_dir($directory)) {
|
||||
throw new RuntimeException("Verzeichnis {$directory} kann nicht angelegt werden. Bitte Schreibrechte prüfen.");
|
||||
}
|
||||
|
||||
$temporary = $path.'.tmp-'.bin2hex(random_bytes(4));
|
||||
|
||||
if (@file_put_contents($temporary, $contents, LOCK_EX) === false) {
|
||||
throw new RuntimeException("Datei {$path} ist nicht schreibbar. Bitte Schreibrechte für {$directory} prüfen.");
|
||||
}
|
||||
|
||||
if (! @rename($temporary, $path)) {
|
||||
@unlink($temporary);
|
||||
|
||||
throw new RuntimeException("Datei {$path} kann nicht ersetzt werden. Bitte Schreibrechte prüfen.");
|
||||
}
|
||||
}
|
||||
}
|
||||
45
app/Support/Update/Changelog.php
Normal file
45
app/Support/Update/Changelog.php
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
use League\CommonMark\GithubFlavoredMarkdownConverter;
|
||||
|
||||
/**
|
||||
* Zerlegt CHANGELOG.md an „## <version>“-Abschnitten und rendert Markdown
|
||||
* sicher (kein Roh-HTML, keine unsicheren Links).
|
||||
*/
|
||||
class Changelog
|
||||
{
|
||||
/**
|
||||
* @return list<array{version: string, heading: string, html: string}>
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
65
app/Support/Update/Channels.php
Normal file
65
app/Support/Update/Channels.php
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
use App\Support\License\VendorHttp;
|
||||
use App\Support\Settings;
|
||||
use InvalidArgumentException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Update-Kanäle: Auswahl persistiert in den Einstellungen (Standard „stable“),
|
||||
* Factory für den Client des aktiven oder eines übergebenen Kanals.
|
||||
*/
|
||||
class Channels
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Settings $settings,
|
||||
private readonly VendorHttp $http,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, string> 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
28
app/Support/Update/Filesystem.php
Normal file
28
app/Support/Update/Filesystem.php
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
use FilesystemIterator;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
|
||||
final class Filesystem
|
||||
{
|
||||
public static function deleteDirectory(string $dir): void
|
||||
{
|
||||
if (! is_dir($dir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$items = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::CHILD_FIRST,
|
||||
);
|
||||
|
||||
foreach ($items as $item) {
|
||||
$item->isDir() && ! $item->isLink() ? @rmdir($item->getPathname()) : @unlink($item->getPathname());
|
||||
}
|
||||
|
||||
@rmdir($dir);
|
||||
}
|
||||
}
|
||||
60
app/Support/Update/InstalledVersion.php
Normal file
60
app/Support/Update/InstalledVersion.php
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
use App\Version;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Installierter Stand als Git-Commit-SHA – bewusst in einer Datei, nicht in der
|
||||
* Datenbank, damit der Updater ihn auch lesen kann, wenn die DB hängt.
|
||||
* storage/ ist ein geschützter Pfad: ein Update überschreibt die Datei nie.
|
||||
*/
|
||||
class InstalledVersion
|
||||
{
|
||||
public function __construct(private readonly ?string $file = null) {}
|
||||
|
||||
public function current(): ?string
|
||||
{
|
||||
$sha = @file_get_contents($this->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');
|
||||
}
|
||||
}
|
||||
59
app/Support/Update/MaintenanceFlag.php
Normal file
59
app/Support/Update/MaintenanceFlag.php
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
/**
|
||||
* Wartungsmodus während eines Updates als Flag-Datei storage/.maintenance.
|
||||
*
|
||||
* Selbstheilend: Ein abgelaufenes „until“ wird beim Prüfen entfernt. Ohne das
|
||||
* würde ein Absturz mitten im Update die Installation dauerhaft sperren – und
|
||||
* niemand käme mehr an die Oberfläche, um den Modus abzuschalten.
|
||||
*/
|
||||
class MaintenanceFlag
|
||||
{
|
||||
public function __construct(private readonly ?string $file = null) {}
|
||||
|
||||
public function activate(int $maxSeconds = 600): void
|
||||
{
|
||||
AtomicFile::write($this->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');
|
||||
}
|
||||
}
|
||||
81
app/Support/Update/Migrations.php
Normal file
81
app/Support/Update/Migrations.php
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
use Illuminate\Database\Migrations\Migrator;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
|
||||
/**
|
||||
* Migrationen ohne Shell: Status, Ausführen und Fingerabdruck über die Dateien.
|
||||
*/
|
||||
class Migrations
|
||||
{
|
||||
public function __construct(private readonly Migrator $migrator) {}
|
||||
|
||||
/**
|
||||
* @return list<array{name: string, ran: bool}>
|
||||
*/
|
||||
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<string>
|
||||
*/
|
||||
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<string, string> Name => Pfad
|
||||
*/
|
||||
private function files(): array
|
||||
{
|
||||
$files = $this->migrator->getMigrationFiles(array_merge(
|
||||
[database_path('migrations')],
|
||||
$this->migrator->paths(),
|
||||
));
|
||||
|
||||
ksort($files);
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function ran(): array
|
||||
{
|
||||
$repository = $this->migrator->getRepository();
|
||||
|
||||
return $repository->repositoryExists() ? $repository->getRan() : [];
|
||||
}
|
||||
}
|
||||
37
app/Support/Update/ProtectedPaths.php
Normal file
37
app/Support/Update/ProtectedPaths.php
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
/**
|
||||
* Pfade, die ein Update nie überschreibt. Verzeichnisse enden mit „/“ und
|
||||
* schützen alles darunter; Dateien werden exakt verglichen.
|
||||
*/
|
||||
class ProtectedPaths
|
||||
{
|
||||
/**
|
||||
* @param list<string> $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;
|
||||
}
|
||||
}
|
||||
77
app/Support/Update/StagingApplier.php
Normal file
77
app/Support/Update/StagingApplier.php
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
use FilesystemIterator;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Legt den entpackten Stand über die Produktion.
|
||||
*
|
||||
* - Geschützte Pfade werden übersprungen.
|
||||
* - Jede Datei wird erst daneben geschrieben und dann umbenannt – ein Abbruch
|
||||
* hinterlässt keine halbe PHP-Datei, die den nächsten Aufruf abwürgt.
|
||||
* - Nur überschreiben und ergänzen, NIE löschen: Ein Fehler in der
|
||||
* Pfadberechnung nimmt so keine Nutzdaten mit.
|
||||
*/
|
||||
class StagingApplier
|
||||
{
|
||||
public function __construct(private readonly ProtectedPaths $protected) {}
|
||||
|
||||
/**
|
||||
* @return array{copied: int, skipped: int}
|
||||
*/
|
||||
public function apply(string $stagingDir, string $targetDir): array
|
||||
{
|
||||
$copied = 0;
|
||||
$skipped = 0;
|
||||
$stagingDir = rtrim((string) realpath($stagingDir), DIRECTORY_SEPARATOR);
|
||||
|
||||
$files = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($stagingDir, FilesystemIterator::SKIP_DOTS),
|
||||
);
|
||||
|
||||
foreach ($files as $file) {
|
||||
if ($file->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];
|
||||
}
|
||||
}
|
||||
53
app/Support/Update/UpdateCheck.php
Normal file
53
app/Support/Update/UpdateCheck.php
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
/**
|
||||
* „Nach Updates suchen“: fragt /check und bereitet das Ergebnis für die Anzeige auf.
|
||||
* Zeigt bewusst keine Commit-Texte – nur ob es Neues gibt und was laut
|
||||
* Änderungsprotokoll neu ist.
|
||||
*/
|
||||
class UpdateCheck
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Channels $channels,
|
||||
private readonly InstalledVersion $version,
|
||||
private readonly Changelog $changelog,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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'),
|
||||
];
|
||||
}
|
||||
}
|
||||
114
app/Support/Update/UpdateClient.php
Normal file
114
app/Support/Update/UpdateClient.php
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
use App\Support\License\ServerError;
|
||||
use App\Support\License\VendorHttp;
|
||||
use Illuminate\Http\Client\Response;
|
||||
|
||||
/**
|
||||
* Zugriff auf den Update-Proxy eines Kanals. Kennt keine Tags und keine Releases:
|
||||
* Es zählt der Stand des Branches, identifiziert über den Commit-SHA.
|
||||
*/
|
||||
class UpdateClient
|
||||
{
|
||||
public function __construct(
|
||||
private readonly VendorHttp $http,
|
||||
private readonly string $baseUrl,
|
||||
) {
|
||||
if (! str_starts_with($baseUrl, 'https://')) {
|
||||
throw new \InvalidArgumentException('Update-Server müssen per HTTPS angesprochen werden.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function version(): array
|
||||
{
|
||||
return $this->json('version');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function check(?string $currentSha): array
|
||||
{
|
||||
return $this->json('check', $currentSha ? ['current_sha' => $currentSha] : []);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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<string, string> $query
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
70
app/Support/Update/UpdateProgress.php
Normal file
70
app/Support/Update/UpdateProgress.php
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
/**
|
||||
* Fortschritt eines laufenden Updates in storage/.update-progress – das Frontend
|
||||
* fragt ihn alle ~2 Sekunden ab.
|
||||
*/
|
||||
class UpdateProgress
|
||||
{
|
||||
/** Ohne Lebenszeichen gilt ein Lauf nach dieser Zeit als abgestürzt. */
|
||||
public const STALE_AFTER_SECONDS = 600;
|
||||
|
||||
public function __construct(private readonly ?string $file = null) {}
|
||||
|
||||
public function set(int $pct, string $step, string $text = ''): void
|
||||
{
|
||||
AtomicFile::write($this->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');
|
||||
}
|
||||
}
|
||||
139
app/Support/Update/Updater.php
Normal file
139
app/Support/Update/Updater.php
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
<?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
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
146
app/Support/Update/ZipExtractor.php
Normal file
146
app/Support/Update/ZipExtractor.php
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Update;
|
||||
|
||||
use RuntimeException;
|
||||
use ZipArchive;
|
||||
|
||||
/**
|
||||
* Entpackt ein Update-Archiv ins Staging und entfernt dabei den gemeinsamen
|
||||
* Top-Level-Ordner („repo-<sha>/“).
|
||||
*
|
||||
* 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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue