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
30
app/Support/Audit.php
Normal file
30
app/Support/Audit.php
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Models\AuditLog;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Protokoll für Admin-Aktionen. Schreibt zusätzlich ins Log – falls die
|
||||
* Datenbank gerade nicht erreichbar ist (z. B. mitten in einem Update).
|
||||
*/
|
||||
class Audit
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $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());
|
||||
}
|
||||
}
|
||||
}
|
||||
20
app/Support/Installation.php
Normal file
20
app/Support/Installation.php
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
/**
|
||||
* Ob diese Installation eingerichtet ist. Der Web-Installer legt die Markierung
|
||||
* storage/.installed an; lokale Entwicklungsumgebungen gelten immer als eingerichtet.
|
||||
*/
|
||||
class Installation
|
||||
{
|
||||
public static function isInstalled(): bool
|
||||
{
|
||||
return is_file(storage_path('.installed')) || app()->environment('local');
|
||||
}
|
||||
|
||||
public static function markInstalled(): void
|
||||
{
|
||||
file_put_contents(storage_path('.installed'), date(DATE_ATOM));
|
||||
}
|
||||
}
|
||||
84
app/Support/License/LicenseService.php
Normal file
84
app/Support/License/LicenseService.php
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\License;
|
||||
|
||||
use App\Support\Update\Channels;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Lizenzauskunft und Geräte-Abmeldung. Ein Lizenzfehler sperrt nie das Programm –
|
||||
* er wird angezeigt und protokolliert, mehr nicht.
|
||||
*/
|
||||
class LicenseService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LicenseStore $store,
|
||||
private readonly Channels $channels,
|
||||
private readonly VendorHttp $http,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed> 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<string, mixed>|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'] ?? [],
|
||||
];
|
||||
}
|
||||
}
|
||||
161
app/Support/License/LicenseStore.php
Normal file
161
app/Support/License/LicenseStore.php
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\License;
|
||||
|
||||
use App\Support\Update\AtomicFile;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Lizenzdaten dieser Installation in storage/app/license.json – außerhalb der
|
||||
* Datenbank, damit Updater und Lizenzprüfung auch bei DB-Problemen funktionieren.
|
||||
*
|
||||
* Die Lizenz-E-Mail gehört zur Lizenz, nicht zu einem Benutzerkonto.
|
||||
* Die Geräte-ID ist eine einmalig erzeugte Zufallszahl (keine Hardwarekennung).
|
||||
* Ein „Gerät“ ist ein Installationsverzeichnis.
|
||||
*/
|
||||
class LicenseStore
|
||||
{
|
||||
/** @var array<string, mixed>|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<string, mixed>|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<string, mixed>|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<string, mixed>
|
||||
*/
|
||||
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<string, mixed> $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');
|
||||
}
|
||||
}
|
||||
38
app/Support/License/ServerError.php
Normal file
38
app/Support/License/ServerError.php
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\License;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Fehlerantwort eines Hersteller-Servers (Update-Proxy oder API) mit stabilem `code`.
|
||||
* Ausgewertet wird immer der Code, nie der Meldungstext.
|
||||
*/
|
||||
class ServerError extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $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);
|
||||
}
|
||||
}
|
||||
44
app/Support/License/ServerMessages.php
Normal file
44
app/Support/License/ServerMessages.php
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\License;
|
||||
|
||||
/**
|
||||
* Verständliche deutsche Meldungen zu den Fehlercodes der Hersteller-Server.
|
||||
* Lizenzfehler sperren nie das Programm – sie verhindern nur den Update-Bezug.
|
||||
*/
|
||||
final class ServerMessages
|
||||
{
|
||||
public static function for(ServerError $error): string
|
||||
{
|
||||
$wait = $error->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';
|
||||
}
|
||||
}
|
||||
136
app/Support/License/VendorHttp.php
Normal file
136
app/Support/License/VendorHttp.php
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\License;
|
||||
|
||||
use App\Support\Update\InstalledVersion;
|
||||
use App\Version;
|
||||
use GuzzleHttp\Exception\ConnectException;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* HTTP-Zugang zu den Hersteller-Servern (Update-Proxy und API) mit Lizenzdaten.
|
||||
*
|
||||
* Kernpunkt ist das rotierende Gerätetoken: JEDE Antwort kann ein neues liefern
|
||||
* (Kopfzeile X-Device-Token oder JSON-Feld device_token) – auch Fehlerantworten
|
||||
* und Datei-Downloads. Es wird in der Antwort-Middleware gespeichert, bevor
|
||||
* irgendetwas anderes mit der Antwort passiert.
|
||||
*/
|
||||
class VendorHttp
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LicenseStore $license,
|
||||
private readonly InstalledVersion $version,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param bool $identifyDevice Rechnername, Installationspfad, Betriebssystem und
|
||||
* Version mitsenden (Update-Endpunkte). Für Meldungen
|
||||
* nicht nötig – dort stehen die Angaben im Körper.
|
||||
*/
|
||||
public function request(int $timeout, bool $identifyDevice = true): PendingRequest
|
||||
{
|
||||
$request = Http::timeout($timeout)
|
||||
->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;
|
||||
}
|
||||
}
|
||||
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