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
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;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue