Loheide-eu-mitarbeiterplatt.../app/Support/License/VendorHttp.php
Friederich Loheide 43244d751a 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>
2026-09-26 06:02:19 +00:00

136 lines
4.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

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

<?php
namespace App\Support\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;
}
}