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
|
|
@ -4,6 +4,14 @@ Neueste Version oben. Jeder Abschnitt beginnt mit `## MAJOR.MINOR.PATCH` und
|
|||
enthält kurze Stichpunkte für Anwenderinnen und Anwender – keine Commit-Texte.
|
||||
Der Self-Updater zeigt diese Abschnitte bei neuen Versionen an.
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Aktualisierung per Klick im Admin-Bereich – ohne Serverzugang, mit Wartungsseite und Fortschrittsanzeige
|
||||
- Lizenz hinterlegen und prüfen, Laufzeit und belegte Geräteplätze einsehen
|
||||
- Update-Kanäle „Stabil“ und „Entwicklung“
|
||||
- Datenbank wird nach einem Update automatisch auf den neuen Stand gebracht
|
||||
- Änderungsprotokoll im Admin-Bereich
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Erste Fassung des Mitarbeiterportals
|
||||
|
|
|
|||
131
app/Filament/Pages/Updates.php
Normal file
131
app/Filament/Pages/Updates.php
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Support\Audit;
|
||||
use App\Support\License\LicenseService;
|
||||
use App\Support\License\LicenseStore;
|
||||
use App\Support\License\ServerError;
|
||||
use App\Support\License\ServerMessages;
|
||||
use App\Support\Update\Changelog;
|
||||
use App\Support\Update\Channels;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
use App\Support\Update\Migrations;
|
||||
use App\Support\Update\UpdateProgress;
|
||||
use BackedEnum;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Throwable;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Seite „Aktualisierung“: Version, Kanal, Update-Suche und -Installation,
|
||||
* Migrationen, Änderungsprotokoll und Lizenz (docs/specs/self-updater.md).
|
||||
*/
|
||||
class Updates extends Page
|
||||
{
|
||||
protected string $view = 'filament.pages.updates';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedArrowPathRoundedSquare;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||||
|
||||
protected static ?int $navigationSort = 10;
|
||||
|
||||
protected static ?string $navigationLabel = 'Aktualisierung';
|
||||
|
||||
protected static ?string $title = 'Aktualisierung';
|
||||
|
||||
protected static ?string $slug = 'aktualisierung';
|
||||
|
||||
public string $licenseEmail = '';
|
||||
|
||||
public string $licenseKey = '';
|
||||
|
||||
public ?string $licenseError = null;
|
||||
|
||||
public function mount(LicenseStore $license): void
|
||||
{
|
||||
$this->licenseEmail = (string) $license->email();
|
||||
}
|
||||
|
||||
public function saveLicense(LicenseStore $license, LicenseService $service): void
|
||||
{
|
||||
$this->validate([
|
||||
'licenseEmail' => ['required', 'email', 'max:255'],
|
||||
'licenseKey' => [$license->hasLicense() ? 'nullable' : 'required', 'string', 'max:500'],
|
||||
], attributes: ['licenseEmail' => 'Lizenz-E-Mail', 'licenseKey' => 'Lizenzschlüssel']);
|
||||
|
||||
$license->setLicense($this->licenseEmail, filled($this->licenseKey) ? $this->licenseKey : (string) $license->key());
|
||||
$this->licenseKey = '';
|
||||
Audit::log('license.saved', ['email' => $this->licenseEmail]);
|
||||
|
||||
$this->checkLicense($service);
|
||||
}
|
||||
|
||||
public function checkLicense(LicenseService $service): void
|
||||
{
|
||||
$this->licenseError = null;
|
||||
|
||||
try {
|
||||
$service->check();
|
||||
|
||||
Notification::make()->success()->title('Lizenz geprüft')->send();
|
||||
} catch (ServerError $e) {
|
||||
$this->licenseError = ServerMessages::for($e);
|
||||
} catch (Throwable $e) {
|
||||
$this->licenseError = 'Die Lizenz konnte nicht geprüft werden: '.$e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
public function releaseDevice(LicenseService $service, LicenseStore $license): void
|
||||
{
|
||||
try {
|
||||
$service->releaseDevice();
|
||||
Audit::log('license.device_released', ['device_label' => $license->deviceLabel()]);
|
||||
|
||||
Notification::make()
|
||||
->success()
|
||||
->title('Installation abgemeldet')
|
||||
->body('Der Geräteplatz ist wieder frei. Updates sind erst nach erneuter Lizenzprüfung wieder möglich.')
|
||||
->send();
|
||||
} catch (ServerError $e) {
|
||||
Notification::make()->danger()->title('Abmelden fehlgeschlagen')->body(ServerMessages::for($e))->send();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getViewData(): array
|
||||
{
|
||||
$version = app(InstalledVersion::class);
|
||||
$license = app(LicenseStore::class);
|
||||
$channels = app(Channels::class);
|
||||
|
||||
try {
|
||||
$migrations = app(Migrations::class)->status();
|
||||
} catch (Throwable) {
|
||||
$migrations = [];
|
||||
}
|
||||
|
||||
return [
|
||||
'release' => $version->release(),
|
||||
'shortSha' => $version->short(),
|
||||
'channels' => $channels->all(),
|
||||
'activeChannel' => $channels->active(),
|
||||
'progress' => app(UpdateProgress::class)->get(),
|
||||
'migrations' => $migrations,
|
||||
'pendingMigrations' => count(array_filter($migrations, fn (array $m) => ! $m['ran'])),
|
||||
'changelog' => app(Changelog::class)->sections(),
|
||||
'hasLicense' => $license->hasLicense(),
|
||||
'maskedKey' => ($key = $license->key()) ? str_repeat('•', 8).substr($key, -4) : null,
|
||||
'licenseSummary' => app(LicenseService::class)->summary(),
|
||||
'licenseStatusError' => ($code = $license->lastStatus()['error_code'] ?? null)
|
||||
? ServerMessages::for(new ServerError($code, 0, $code))
|
||||
: null,
|
||||
'deviceLabel' => $license->deviceLabel(),
|
||||
];
|
||||
}
|
||||
}
|
||||
97
app/Http/Controllers/Admin/UpdateController.php
Normal file
97
app/Http/Controllers/Admin/UpdateController.php
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Support\Audit;
|
||||
use App\Support\License\ServerError;
|
||||
use App\Support\License\ServerMessages;
|
||||
use App\Support\Update\Channels;
|
||||
use App\Support\Update\Migrations;
|
||||
use App\Support\Update\UpdateCheck;
|
||||
use App\Support\Update\UpdateProgress;
|
||||
use App\Support\Update\Updater;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Endpunkte der Seite „Aktualisierung“ – nur für Administratoren, CSRF-geschützt.
|
||||
*/
|
||||
class UpdateController extends Controller
|
||||
{
|
||||
public function check(Request $request, UpdateCheck $check): JsonResponse
|
||||
{
|
||||
try {
|
||||
return response()->json(['ok' => true, 'result' => $check->run()]);
|
||||
} catch (ServerError $e) {
|
||||
return $this->serverError($e);
|
||||
}
|
||||
}
|
||||
|
||||
public function install(Request $request, Updater $updater, UpdateProgress $progress): JsonResponse
|
||||
{
|
||||
if ($progress->isRunning()) {
|
||||
return response()->json(['ok' => false, 'message' => 'Es läuft bereits eine Aktualisierung.'], 409);
|
||||
}
|
||||
|
||||
// Der Ablauf läuft serverseitig zu Ende, auch wenn der Browser die Verbindung trennt.
|
||||
@set_time_limit(0);
|
||||
@ignore_user_abort(true);
|
||||
|
||||
try {
|
||||
$result = $updater->installUpdate($request->user()?->id);
|
||||
|
||||
return response()->json(['ok' => true, 'result' => $result]);
|
||||
} catch (ServerError $e) {
|
||||
return $this->serverError($e);
|
||||
} catch (Throwable $e) {
|
||||
return response()->json(['ok' => false, 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function progress(UpdateProgress $progress): JsonResponse
|
||||
{
|
||||
return response()->json($progress->get());
|
||||
}
|
||||
|
||||
public function channel(Request $request, Channels $channels): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'channel' => ['required', 'string', Rule::in(array_keys($channels->all()))],
|
||||
]);
|
||||
|
||||
$channels->setActive($validated['channel']);
|
||||
Audit::log('update.channel_changed', ['channel' => $validated['channel']]);
|
||||
|
||||
return response()->json(['ok' => true, 'channel' => $validated['channel']]);
|
||||
}
|
||||
|
||||
public function migrations(Migrations $migrations): JsonResponse
|
||||
{
|
||||
@set_time_limit(0);
|
||||
|
||||
try {
|
||||
$count = $migrations->run();
|
||||
@file_put_contents(storage_path('.migrations-fingerprint'), $migrations->fingerprint());
|
||||
Audit::log('update.migrations', ['migrations' => $count]);
|
||||
|
||||
return response()->json(['ok' => true, 'count' => $count, 'status' => $migrations->status()]);
|
||||
} catch (Throwable $e) {
|
||||
Audit::log('update.migrations_failed', ['error' => $e->getMessage()]);
|
||||
|
||||
return response()->json(['ok' => false, 'message' => 'Migrationen fehlgeschlagen: '.$e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
|
||||
private function serverError(ServerError $e): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'ok' => false,
|
||||
'code' => $e->errorCode,
|
||||
'message' => ServerMessages::for($e),
|
||||
'license_input' => $e->needsLicenseInput(),
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
35
app/Http/Middleware/EnsureNotInMaintenance.php
Normal file
35
app/Http/Middleware/EnsureNotInMaintenance.php
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Support\Update\MaintenanceFlag;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Während eines Updates: 503 mit Wartungsseite. Ausgenommen sind die
|
||||
* Update-Endpunkte, die Seite „Aktualisierung“, die Anmeldung und der
|
||||
* Health-Check – sonst könnte niemand verfolgen, wie weit das Update ist.
|
||||
*/
|
||||
class EnsureNotInMaintenance
|
||||
{
|
||||
private const EXCEPT = ['admin/update/*', 'admin/aktualisierung', 'login', 'logout', 'up'];
|
||||
|
||||
public function __construct(private readonly MaintenanceFlag $maintenance) {}
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (! $this->maintenance->isActive() || $request->is(...self::EXCEPT)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$retryAfter = $this->maintenance->retryAfter();
|
||||
|
||||
if ($request->expectsJson() || $request->header('X-Inertia')) {
|
||||
return response()->json(['message' => 'Das Portal wird gerade aktualisiert.'], 503, ['Retry-After' => $retryAfter]);
|
||||
}
|
||||
|
||||
return response()->view('maintenance', ['retryAfter' => $retryAfter], 503, ['Retry-After' => $retryAfter]);
|
||||
}
|
||||
}
|
||||
72
app/Http/Middleware/RunPendingMigrations.php
Normal file
72
app/Http/Middleware/RunPendingMigrations.php
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Support\Installation;
|
||||
use App\Support\Update\Migrations;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Führt nach einem Update beim ersten Seitenaufruf ausstehende Migrationen aus –
|
||||
* ohne SSH der einzige verlässliche Zeitpunkt.
|
||||
*
|
||||
* Migriert wird nur, wenn sich der Fingerabdruck der Migrationsdateien geändert
|
||||
* hat (sonst liefe der Migrator bei jedem Request), mit einer Sperre gegen
|
||||
* Parallellauf. Fehler werden protokolliert, nie geworfen.
|
||||
*/
|
||||
class RunPendingMigrations
|
||||
{
|
||||
public function __construct(private readonly Migrations $migrations) {}
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (app()->runningUnitTests() || ! Installation::isInstalled()) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$stored = @file_get_contents(storage_path('.migrations-fingerprint'));
|
||||
|
||||
try {
|
||||
$current = $this->migrations->fingerprint();
|
||||
|
||||
if ($stored !== $current) {
|
||||
$this->migrateWithLock($current);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
Log::error('Automatische Migration fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
private function migrateWithLock(string $fingerprint): void
|
||||
{
|
||||
$lock = @fopen(storage_path('.migrate.lock'), 'c');
|
||||
|
||||
if ($lock === false || ! flock($lock, LOCK_EX | LOCK_NB)) {
|
||||
return; // Läuft gerade in einer anderen Anfrage.
|
||||
}
|
||||
|
||||
try {
|
||||
// Nach dem Warten auf die Sperre erneut prüfen – vielleicht war jemand schneller.
|
||||
if (@file_get_contents(storage_path('.migrations-fingerprint')) === $fingerprint) {
|
||||
return;
|
||||
}
|
||||
|
||||
@set_time_limit(300);
|
||||
$count = $this->migrations->run();
|
||||
file_put_contents(storage_path('.migrations-fingerprint'), $fingerprint);
|
||||
|
||||
if ($count > 0) {
|
||||
Log::info("Automatische Migration: {$count} Migration(en) ausgeführt.");
|
||||
}
|
||||
} finally {
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
}
|
||||
}
|
||||
}
|
||||
29
app/Models/AuditLog.php
Normal file
29
app/Models/AuditLog.php
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable(['user_id', 'action', 'data'])]
|
||||
class AuditLog extends Model
|
||||
{
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'data' => 'array',
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
||||
|
|
@ -2,12 +2,18 @@
|
|||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\Avatars;
|
||||
use App\Support\Branding;
|
||||
use App\Support\License\LicenseStore;
|
||||
use App\Support\Navigation;
|
||||
use App\Support\QuickLinks;
|
||||
use App\Support\Settings;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
use App\Support\Update\MaintenanceFlag;
|
||||
use App\Support\Update\UpdateProgress;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
|
|
@ -20,6 +26,10 @@ class AppServiceProvider extends ServiceProvider
|
|||
$this->app->singleton(Avatars::class);
|
||||
$this->app->singleton(Navigation::class);
|
||||
$this->app->singleton(QuickLinks::class);
|
||||
$this->app->singleton(LicenseStore::class);
|
||||
$this->app->singleton(InstalledVersion::class);
|
||||
$this->app->singleton(UpdateProgress::class);
|
||||
$this->app->singleton(MaintenanceFlag::class);
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
|
|
@ -27,6 +37,9 @@ class AppServiceProvider extends ServiceProvider
|
|||
// N+1-Abfragen in Entwicklung und Tests sofort sichtbar machen (docs/PLAN.md, Performance).
|
||||
Model::preventLazyLoading(! $this->app->isProduction());
|
||||
|
||||
// Vorläufig: Administratoren über is_admin – wird in Phase 2 durch Rollen ersetzt.
|
||||
Gate::define('admin', fn (User $user) => $user->is_admin && $user->is_active);
|
||||
|
||||
Password::defaults(fn () => Password::min(10)->letters()->numbers());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ class AdminPanelProvider extends PanelProvider
|
|||
->colors(fn () => [
|
||||
'primary' => app(Branding::class)->palette(),
|
||||
])
|
||||
->navigationGroups(['Inhalte', 'Portal'])
|
||||
->navigationGroups(['Inhalte', 'Portal', 'System'])
|
||||
->navigationItems([
|
||||
NavigationItem::make('Zum Portal')
|
||||
->url('/')
|
||||
|
|
|
|||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -9,5 +9,5 @@ namespace App;
|
|||
*/
|
||||
final class Version
|
||||
{
|
||||
public const VERSION = '0.1.0';
|
||||
public const VERSION = '0.2.0';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
<?php
|
||||
|
||||
use App\Http\Middleware\EnsureNotInMaintenance;
|
||||
use App\Http\Middleware\HandleInertiaRequests;
|
||||
use App\Http\Middleware\RunPendingMigrations;
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Foundation\Configuration\Exceptions;
|
||||
use Illuminate\Foundation\Configuration\Middleware;
|
||||
|
|
@ -13,7 +15,10 @@ return Application::configure(basePath: dirname(__DIR__))
|
|||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
$middleware->web(append: [
|
||||
$middleware->web(prepend: [
|
||||
EnsureNotInMaintenance::class,
|
||||
], append: [
|
||||
RunPendingMigrations::class,
|
||||
HandleInertiaRequests::class,
|
||||
]);
|
||||
})
|
||||
|
|
|
|||
61
config/updater.php
Normal file
61
config/updater.php
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
| Self-Updater und Lizenz – siehe docs/specs/self-updater.md und docs/PLAN.md (Abschnitt 5).
|
||||
| Der technische Schlüssel beim Hersteller ist „mitarbeiterportal“, unabhängig vom Produktnamen.
|
||||
*/
|
||||
|
||||
return [
|
||||
|
||||
'software' => 'mitarbeiterportal',
|
||||
|
||||
// Update-Kanäle: jeweils eigene Proxy-Basis-URL. Standard ist „stable“.
|
||||
'channels' => [
|
||||
'stable' => [
|
||||
'label' => 'Stabil',
|
||||
'url' => 'https://update.loheide.cloud/mitarbeiterportal',
|
||||
],
|
||||
'development' => [
|
||||
'label' => 'Entwicklung',
|
||||
'url' => 'https://update.loheide.cloud/mitarbeiterportal-development',
|
||||
],
|
||||
],
|
||||
|
||||
'default_channel' => 'stable',
|
||||
|
||||
'api_url' => 'https://api.loheide.cloud/v1',
|
||||
|
||||
'changelog_url' => 'https://update.loheide.cloud/mitarbeiterportal/changelog',
|
||||
|
||||
'timeouts' => [
|
||||
'json' => 20,
|
||||
'zip' => 180,
|
||||
],
|
||||
|
||||
'max_redirects' => 3,
|
||||
|
||||
// Werden beim Übernehmen eines Updates NIE überschrieben.
|
||||
// Verzeichnisse mit Schrägstrich am Ende, Dateien exakt.
|
||||
// Abweichung von der Vorgabe: vendor/ ist bewusst NICHT geschützt (docs/PLAN.md, 5.2).
|
||||
'protected_paths' => [
|
||||
'.env',
|
||||
'.git/',
|
||||
'storage/',
|
||||
'bootstrap/cache/',
|
||||
'node_modules/',
|
||||
'vendor-dev/',
|
||||
'composer.lock',
|
||||
'package-lock.json',
|
||||
'plugins/',
|
||||
'public/storage/',
|
||||
'public/uploads/',
|
||||
'public/hot',
|
||||
'config/local.php',
|
||||
'.htaccess',
|
||||
'database/database.sqlite',
|
||||
],
|
||||
|
||||
// Wartungsmodus läuft spätestens nach dieser Zeit von allein aus.
|
||||
'maintenance_max_seconds' => 600,
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('audit_logs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->string('action', 100);
|
||||
$table->json('data')->nullable();
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
|
||||
$table->index(['action', 'created_at']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('audit_logs');
|
||||
}
|
||||
};
|
||||
360
resources/views/filament/pages/updates.blade.php
Normal file
360
resources/views/filament/pages/updates.blade.php
Normal file
|
|
@ -0,0 +1,360 @@
|
|||
<x-filament-panels::page>
|
||||
<style>
|
||||
.ih-stack { display: grid; gap: 1.5rem; }
|
||||
.ih-row { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem 1.5rem; }
|
||||
.ih-muted { color: rgb(107 114 128); font-size: .875rem; }
|
||||
.ih-strong { font-weight: 600; }
|
||||
.ih-big { font-size: 1.5rem; font-weight: 600; letter-spacing: -.01em; }
|
||||
.ih-progress { height: .5rem; border-radius: 999px; background: rgb(229 231 235); overflow: hidden; }
|
||||
.ih-progress > div { height: 100%; background: var(--primary-600); transition: width .4s ease; }
|
||||
.ih-prose { font-size: .875rem; line-height: 1.6; }
|
||||
.ih-prose ul { list-style: disc; padding-left: 1.25rem; margin: .25rem 0; }
|
||||
.ih-prose p { margin: .25rem 0; }
|
||||
.ih-prose a { color: var(--primary-600); text-decoration: underline; }
|
||||
.ih-entry + .ih-entry { border-top: 1px solid rgb(229 231 235); padding-top: 1rem; margin-top: 1rem; }
|
||||
.ih-privacy { font-size: .8125rem; line-height: 1.55; color: rgb(75 85 99); border-left: 3px solid rgb(209 213 219); padding: .25rem 0 .25rem 1rem; }
|
||||
.ih-privacy ul { list-style: disc; padding-left: 1.25rem; margin: .5rem 0; }
|
||||
.ih-privacy p { margin: .5rem 0; }
|
||||
.ih-table { width: 100%; font-size: .875rem; border-collapse: collapse; }
|
||||
.ih-table td { padding: .375rem 0; border-bottom: 1px solid rgb(243 244 246); }
|
||||
.ih-grid2 { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); }
|
||||
.ih-select { border: 1px solid rgb(209 213 219); border-radius: .5rem; padding: .375rem 2rem .375rem .75rem; font-size: .875rem; background-color: transparent; }
|
||||
.dark .ih-muted, .dark .ih-privacy { color: rgb(156 163 175); }
|
||||
.dark .ih-progress { background: rgb(55 65 81); }
|
||||
.dark .ih-entry + .ih-entry, .dark .ih-table td { border-color: rgb(55 65 81); }
|
||||
</style>
|
||||
|
||||
<script>
|
||||
function updater({ csrf, progress, channel }) {
|
||||
return {
|
||||
csrf,
|
||||
progress,
|
||||
channel,
|
||||
result: null,
|
||||
error: null,
|
||||
checking: false,
|
||||
installing: false,
|
||||
migrationMessage: '',
|
||||
timer: null,
|
||||
|
||||
get busy() {
|
||||
return this.checking || this.installing;
|
||||
},
|
||||
|
||||
init() {
|
||||
// Seite während eines laufenden Updates neu geladen: weiter beobachten.
|
||||
if (!['idle', 'done', 'error'].includes(this.progress.step)) {
|
||||
this.installing = true;
|
||||
this.poll();
|
||||
}
|
||||
},
|
||||
|
||||
async post(url, body = {}) {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': this.csrf },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
return response.json().catch(() => ({ ok: false, message: `Unerwartete Antwort (HTTP ${response.status}).` }));
|
||||
},
|
||||
|
||||
async check() {
|
||||
this.checking = true;
|
||||
this.error = null;
|
||||
this.result = null;
|
||||
|
||||
try {
|
||||
const data = await this.post('/admin/update/check');
|
||||
data.ok ? (this.result = data.result) : (this.error = data.message);
|
||||
|
||||
if (data.license_input) {
|
||||
this.error += ' Die Lizenzdaten können unten eingegeben werden.';
|
||||
}
|
||||
} catch (e) {
|
||||
this.error = 'Die Update-Suche konnte nicht ausgeführt werden.';
|
||||
} finally {
|
||||
this.checking = false;
|
||||
}
|
||||
},
|
||||
|
||||
updateSummary() {
|
||||
const r = this.result;
|
||||
const parts = [];
|
||||
|
||||
parts.push(r.version ? `Version ${r.version} (${r.latest_short})` : `Stand ${r.latest_short}`);
|
||||
|
||||
if (r.released_at) {
|
||||
parts.push(`veröffentlicht am ${new Date(r.released_at).toLocaleDateString('de-DE')}`);
|
||||
}
|
||||
|
||||
if (r.versions_behind > 0) {
|
||||
parts.push(`${r.versions_behind} Version(en) zurück`);
|
||||
}
|
||||
|
||||
return parts.join(' · ');
|
||||
},
|
||||
|
||||
async install() {
|
||||
if (!confirm('Jetzt aktualisieren? Das Portal ist währenddessen kurz nicht erreichbar.')) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.installing = true;
|
||||
this.progress = { pct: 0, step: 'maintenance', text: 'Aktualisierung wird gestartet …' };
|
||||
this.poll();
|
||||
|
||||
// Der Server arbeitet weiter, auch wenn diese Anfrage abbricht – maßgeblich ist der Fortschritt.
|
||||
this.post('/admin/update/install').catch(() => {});
|
||||
},
|
||||
|
||||
poll() {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(async () => {
|
||||
try {
|
||||
const response = await fetch('/admin/update/progress', { headers: { Accept: 'application/json' } });
|
||||
this.progress = await response.json();
|
||||
} catch (e) {
|
||||
// Kurzzeitig nicht erreichbar (z. B. beim Austausch der Dateien) – weiter versuchen.
|
||||
}
|
||||
|
||||
if (this.progress.step === 'done') {
|
||||
this.installing = false;
|
||||
setTimeout(() => window.location.reload(), 1500);
|
||||
} else if (this.progress.step === 'error') {
|
||||
this.installing = false;
|
||||
} else {
|
||||
this.poll();
|
||||
}
|
||||
}, 2000);
|
||||
},
|
||||
|
||||
async changeChannel() {
|
||||
const data = await this.post('/admin/update/channel', { channel: this.channel });
|
||||
this.result = null;
|
||||
this.error = data.ok ? null : (data.message ?? 'Kanal konnte nicht gespeichert werden.');
|
||||
},
|
||||
|
||||
async runMigrations() {
|
||||
this.migrationMessage = 'Läuft …';
|
||||
const data = await this.post('/admin/update/migrations');
|
||||
this.migrationMessage = data.ok ? `${data.count} Migration(en) ausgeführt.` : data.message;
|
||||
|
||||
if (data.ok && data.count > 0) {
|
||||
setTimeout(() => window.location.reload(), 1200);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="ih-stack"
|
||||
x-data="updater({
|
||||
csrf: @js(csrf_token()),
|
||||
progress: @js($progress),
|
||||
channel: @js($activeChannel),
|
||||
})"
|
||||
x-init="init()"
|
||||
>
|
||||
{{-- Version und Kanal --}}
|
||||
<x-filament::section>
|
||||
<div class="ih-row" style="justify-content: space-between">
|
||||
<div>
|
||||
<div class="ih-muted">Installierte Version</div>
|
||||
<div class="ih-big">{{ $release }} @if ($shortSha)<span class="ih-muted" style="font-size: 1rem">({{ $shortSha }})</span>@endif</div>
|
||||
</div>
|
||||
<label class="ih-row" style="gap: .5rem">
|
||||
<span class="ih-muted">Update-Kanal</span>
|
||||
<select class="ih-select" x-model="channel" @change="changeChannel()" :disabled="busy">
|
||||
@foreach ($channels as $key => $label)
|
||||
<option value="{{ $key }}">{{ $label }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</x-filament::section>
|
||||
|
||||
{{-- Suche und Installation --}}
|
||||
<x-filament::section heading="Nach Updates suchen">
|
||||
<div class="ih-stack" style="gap: 1rem">
|
||||
<div class="ih-row">
|
||||
<x-filament::button icon="heroicon-o-magnifying-glass" x-on:click="check()" x-bind:disabled="busy">
|
||||
Nach Updates suchen
|
||||
</x-filament::button>
|
||||
<x-filament::loading-indicator class="h-5 w-5" x-show="checking" x-cloak />
|
||||
</div>
|
||||
|
||||
<template x-if="error">
|
||||
<x-filament::callout color="danger" icon="heroicon-o-exclamation-triangle">
|
||||
<x-slot name="description"><span x-text="error"></span></x-slot>
|
||||
</x-filament::callout>
|
||||
</template>
|
||||
|
||||
<template x-if="result && !result.has_update">
|
||||
<x-filament::callout color="success" icon="heroicon-o-check-circle" heading="Sie verwenden die neueste Version." />
|
||||
</template>
|
||||
|
||||
<template x-if="result && result.has_update">
|
||||
<div class="ih-stack" style="gap: 1rem">
|
||||
<x-filament::callout color="info" icon="heroicon-o-arrow-down-circle" heading="Neue Version verfügbar">
|
||||
<x-slot name="description">
|
||||
<span x-text="updateSummary()"></span>
|
||||
<template x-if="result.channel_switch && result.channel_switch.direction === 'back'">
|
||||
<span><br>Hinweis: Der Stand stammt aus einem anderen Kanal und ist älter als der installierte – das ist beim Zurückwechseln normal.</span>
|
||||
</template>
|
||||
</x-slot>
|
||||
</x-filament::callout>
|
||||
|
||||
<template x-if="result.changelog.length">
|
||||
<div>
|
||||
<div class="ih-strong" style="margin-bottom: .5rem">Was ist neu?</div>
|
||||
<template x-for="entry in result.changelog" :key="entry.heading">
|
||||
<div class="ih-entry">
|
||||
<div class="ih-strong" x-text="entry.heading"></div>
|
||||
<div class="ih-prose" x-html="entry.html"></div>
|
||||
</div>
|
||||
</template>
|
||||
<template x-if="!result.changelog_complete">
|
||||
<p class="ih-muted" style="margin-top: .75rem">
|
||||
Gekürzt – <a :href="result.changelog_url" target="_blank" rel="noopener" style="text-decoration: underline">vollständiges Änderungsprotokoll</a>
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="ih-row">
|
||||
<x-filament::button color="success" icon="heroicon-o-arrow-path" x-on:click="install()" x-bind:disabled="busy">
|
||||
Jetzt aktualisieren
|
||||
</x-filament::button>
|
||||
<span class="ih-muted">Das Portal zeigt währenddessen eine Wartungsseite.</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template x-if="progress.step !== 'idle' && (installing || progress.step === 'error' || progress.step === 'done')">
|
||||
<div class="ih-stack" style="gap: .5rem">
|
||||
<div class="ih-row" style="justify-content: space-between">
|
||||
<span x-text="progress.text"></span>
|
||||
<span class="ih-muted" x-show="progress.pct >= 0" x-text="progress.pct + ' %'"></span>
|
||||
</div>
|
||||
<div class="ih-progress" x-show="progress.pct >= 0"><div :style="`width: ${Math.max(progress.pct, 3)}%`"></div></div>
|
||||
<template x-if="progress.step === 'error'">
|
||||
<x-filament::callout color="danger" icon="heroicon-o-x-circle" heading="Aktualisierung fehlgeschlagen">
|
||||
<x-slot name="description"><span x-text="progress.text"></span> Die bisherige Version läuft weiter.</x-slot>
|
||||
</x-filament::callout>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
{{-- Datenschutzhinweis: dauerhaft sichtbar, Wortlaut nach Vorgabe (docs/specs/self-updater.md). --}}
|
||||
<div class="ih-privacy">
|
||||
<p>Bei der Suche nach Updates und beim Herunterladen einer neuen Fassung werden Daten an update.loheide.cloud übertragen. Übermittelt werden:</p>
|
||||
<ul>
|
||||
<li>die auf Ihrer Lizenz hinterlegte E-Mail-Adresse und der Lizenzschlüssel</li>
|
||||
<li>eine Gerätekennung, die dieses Programm einmalig als Zufallszahl erzeugt hat (keine Hardwarekennung, keine Seriennummer) – damit wird gezählt, auf wie vielen Geräten die Lizenz genutzt wird</li>
|
||||
<li>Rechnername, Betriebssystem und Programmversion, damit Sie Ihre Geräte im Kundenportal auseinanderhalten können</li>
|
||||
<li>der bei Ihnen installierte Stand, damit die Gegenstelle weiß, was neu ist</li>
|
||||
<li>technisch bedingt: Ihre IP-Adresse, Datum und Uhrzeit des Abrufs</li>
|
||||
</ul>
|
||||
<p>Zweck: Bereitstellung der Aktualisierung und Prüfung der Lizenz.</p>
|
||||
<p>Nicht übertragen werden Inhalte aus diesem Programm: keine Dokumente, keine Datenbank, keine Eingaben. Die Verbindung ist verschlüsselt.</p>
|
||||
</div>
|
||||
</div>
|
||||
</x-filament::section>
|
||||
|
||||
{{-- Lizenz --}}
|
||||
<x-filament::section heading="Lizenz" description="Die Lizenz wird nur für den Bezug von Updates benötigt. Ein Lizenzproblem schränkt die Nutzung des Portals nicht ein.">
|
||||
<div class="ih-stack" style="gap: 1.25rem">
|
||||
@if ($licenseError || $licenseStatusError)
|
||||
<x-filament::callout color="warning" icon="heroicon-o-exclamation-triangle" :description="$licenseError ?? $licenseStatusError" />
|
||||
@endif
|
||||
|
||||
@if ($licenseSummary)
|
||||
@if ($licenseSummary['expires_soon'])
|
||||
<x-filament::callout color="warning" icon="heroicon-o-clock" heading="Lizenz läuft bald ab" :description="'Noch '.$licenseSummary['days_remaining'].' Tage. Updates stehen danach erst nach einer Verlängerung wieder zur Verfügung.'" />
|
||||
@endif
|
||||
|
||||
<table class="ih-table">
|
||||
<tr><td class="ih-muted">Registriert auf</td><td>{{ collect([$licenseSummary['registered_to']['company'] ?? null, $licenseSummary['registered_to']['contact_name'] ?? null])->filter()->implode(' · ') ?: '–' }}</td></tr>
|
||||
<tr><td class="ih-muted">Laufzeit</td><td>
|
||||
@if ($licenseSummary['unlimited'])
|
||||
unbefristet
|
||||
@elseif ($licenseSummary['expired'])
|
||||
abgelaufen
|
||||
@elseif ($licenseSummary['valid_until'])
|
||||
bis {{ \Illuminate\Support\Carbon::parse($licenseSummary['valid_until'])->format('d.m.Y') }}@if ($licenseSummary['days_remaining'] !== null) (noch {{ $licenseSummary['days_remaining'] }} Tage)@endif
|
||||
@else
|
||||
–
|
||||
@endif
|
||||
</td></tr>
|
||||
<tr><td class="ih-muted">Geräteplätze</td><td>{{ $licenseSummary['devices']['used'] ?? '?' }} von {{ $licenseSummary['devices']['max'] ?? '?' }} belegt</td></tr>
|
||||
<tr><td class="ih-muted">Diese Installation</td><td>{{ $deviceLabel }}</td></tr>
|
||||
</table>
|
||||
@endif
|
||||
|
||||
<form wire:submit="saveLicense" class="ih-stack" style="gap: 1rem">
|
||||
<div class="ih-grid2">
|
||||
<label>
|
||||
<span class="ih-muted">Lizenz-E-Mail</span>
|
||||
<x-filament::input.wrapper :valid="! $errors->has('licenseEmail')">
|
||||
<x-filament::input type="email" wire:model="licenseEmail" autocomplete="off" />
|
||||
</x-filament::input.wrapper>
|
||||
@error('licenseEmail') <span class="ih-muted" style="color: rgb(220 38 38)">{{ $message }}</span> @enderror
|
||||
</label>
|
||||
<label>
|
||||
<span class="ih-muted">Lizenzschlüssel @if ($maskedKey)(hinterlegt: {{ $maskedKey }})@endif</span>
|
||||
<x-filament::input.wrapper :valid="! $errors->has('licenseKey')">
|
||||
<x-filament::input type="password" wire:model="licenseKey" autocomplete="off" :placeholder="$maskedKey ? 'Leer lassen, um ihn zu behalten' : ''" />
|
||||
</x-filament::input.wrapper>
|
||||
@error('licenseKey') <span class="ih-muted" style="color: rgb(220 38 38)">{{ $message }}</span> @enderror
|
||||
</label>
|
||||
</div>
|
||||
<p class="ih-muted">Die Lizenz-E-Mail ist die Adresse, auf die die Lizenz ausgestellt ist – nicht zwingend Ihre eigene.</p>
|
||||
<div class="ih-row">
|
||||
<x-filament::button type="submit">Speichern und prüfen</x-filament::button>
|
||||
@if ($hasLicense)
|
||||
<x-filament::button color="gray" wire:click="checkLicense">Lizenz prüfen</x-filament::button>
|
||||
<x-filament::button color="danger" outlined wire:click="releaseDevice" wire:confirm="Diese Installation bei der Lizenz abmelden? Der Geräteplatz wird frei, Updates sind danach erst nach erneuter Prüfung möglich.">
|
||||
Diese Installation abmelden
|
||||
</x-filament::button>
|
||||
@endif
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</x-filament::section>
|
||||
|
||||
{{-- Migrationen --}}
|
||||
<x-filament::section heading="Datenbank" :description="$pendingMigrations ? $pendingMigrations.' ausstehende Migration(en)' : 'Alle Migrationen sind angewendet.'" collapsible :collapsed="! $pendingMigrations">
|
||||
<div class="ih-stack" style="gap: 1rem">
|
||||
<div class="ih-row">
|
||||
<x-filament::button color="gray" icon="heroicon-o-circle-stack" x-on:click="runMigrations()" x-bind:disabled="busy">Migrationen ausführen</x-filament::button>
|
||||
<span class="ih-muted" x-text="migrationMessage"></span>
|
||||
</div>
|
||||
<table class="ih-table">
|
||||
@foreach ($migrations as $migration)
|
||||
<tr>
|
||||
<td style="font-family: ui-monospace, monospace; font-size: .8125rem">{{ $migration['name'] }}</td>
|
||||
<td style="text-align: right">
|
||||
<x-filament::badge :color="$migration['ran'] ? 'success' : 'warning'">{{ $migration['ran'] ? 'angewendet' : 'offen' }}</x-filament::badge>
|
||||
</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</table>
|
||||
</div>
|
||||
</x-filament::section>
|
||||
|
||||
{{-- Änderungsprotokoll --}}
|
||||
<x-filament::section heading="Änderungsprotokoll" collapsible>
|
||||
@forelse ($changelog as $section)
|
||||
<div class="ih-entry">
|
||||
<div class="ih-strong">Version {{ $section['heading'] }}</div>
|
||||
<div class="ih-prose">{!! $section['html'] !!}</div>
|
||||
</div>
|
||||
@empty
|
||||
<p class="ih-muted">Kein Änderungsprotokoll vorhanden.</p>
|
||||
@endforelse
|
||||
</x-filament::section>
|
||||
</div>
|
||||
|
||||
</x-filament-panels::page>
|
||||
25
resources/views/maintenance.blade.php
Normal file
25
resources/views/maintenance.blade.php
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="refresh" content="{{ $retryAfter }}">
|
||||
<title>Wartung</title>
|
||||
<style>
|
||||
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f4f5f7; color: #1a1d21; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; }
|
||||
main { max-width: 440px; padding: 40px 32px; background: #fff; border: 1px solid #e3e5e8; border-radius: 12px; text-align: center; }
|
||||
h1 { font-size: 20px; margin: 16px 0 8px; }
|
||||
p { color: #5f6670; line-height: 1.5; margin: 0; }
|
||||
.spinner { width: 32px; height: 32px; margin: 0 auto; border: 3px solid #e3e5e8; border-top-color: #5f6670; border-radius: 50%; animation: spin 1s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-color-scheme: dark) { body { background: #0f1114; color: #e8eaed; } main { background: #171a1e; border-color: #2a2e34; } p { color: #9aa1ab; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="spinner" aria-hidden="true"></div>
|
||||
<h1>Das Portal wird gerade aktualisiert</h1>
|
||||
<p>Das dauert meist nur wenige Minuten. Diese Seite lädt sich automatisch neu.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
<?php
|
||||
|
||||
use App\Http\Controllers\Admin\UpdateController;
|
||||
use App\Http\Controllers\DashboardController;
|
||||
use App\Http\Controllers\EventController;
|
||||
use App\Http\Controllers\NewsController;
|
||||
|
|
@ -29,3 +30,12 @@ Route::middleware('auth')->group(function () {
|
|||
Route::delete('/profil/bild', [ProfileController::class, 'destroyAvatar'])->name('profile.avatar.destroy');
|
||||
Route::put('/profil/darstellung', [ProfileController::class, 'updateTheme'])->name('profile.theme.update');
|
||||
});
|
||||
|
||||
// Self-Updater (docs/specs/self-updater.md) – nur für Administratoren, CSRF über die web-Gruppe.
|
||||
Route::middleware(['auth', 'can:admin'])->prefix('admin/update')->name('admin.update.')->group(function () {
|
||||
Route::post('/check', [UpdateController::class, 'check'])->name('check');
|
||||
Route::post('/install', [UpdateController::class, 'install'])->name('install');
|
||||
Route::get('/progress', [UpdateController::class, 'progress'])->name('progress');
|
||||
Route::post('/channel', [UpdateController::class, 'channel'])->name('channel');
|
||||
Route::post('/migrations', [UpdateController::class, 'migrations'])->name('migrations');
|
||||
});
|
||||
|
|
|
|||
148
tests/Feature/Update/ArchiveTest.php
Normal file
148
tests/Feature/Update/ArchiveTest.php
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Update;
|
||||
|
||||
use App\Support\Update\Filesystem;
|
||||
use App\Support\Update\ProtectedPaths;
|
||||
use App\Support\Update\StagingApplier;
|
||||
use App\Support\Update\ZipExtractor;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
use ZipArchive;
|
||||
|
||||
class ArchiveTest extends TestCase
|
||||
{
|
||||
private string $dir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->dir = sys_get_temp_dir().'/inhaus-zip-'.bin2hex(random_bytes(4));
|
||||
mkdir($this->dir);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Filesystem::deleteDirectory($this->dir);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $files
|
||||
*/
|
||||
private function zip(array $files): string
|
||||
{
|
||||
$path = $this->dir.'/archiv.zip';
|
||||
$zip = new ZipArchive;
|
||||
$zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE);
|
||||
|
||||
foreach ($files as $name => $contents) {
|
||||
$zip->addFromString($name, $contents);
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function test_common_top_level_folder_is_stripped(): void
|
||||
{
|
||||
$zip = $this->zip([
|
||||
'repo-abc/app/Version.php' => '<?php // neu',
|
||||
'repo-abc/README.md' => 'Hallo',
|
||||
]);
|
||||
|
||||
$count = (new ZipExtractor)->extract($zip, $this->dir.'/staging');
|
||||
|
||||
$this->assertSame(2, $count);
|
||||
$this->assertFileExists($this->dir.'/staging/app/Version.php');
|
||||
$this->assertFileExists($this->dir.'/staging/README.md');
|
||||
}
|
||||
|
||||
public function test_zip_slip_creates_nothing_outside_staging(): void
|
||||
{
|
||||
$zip = $this->zip([
|
||||
'repo-abc/ok.txt' => 'ok',
|
||||
'repo-abc/../../evil.php' => '<?php echo "böse";',
|
||||
]);
|
||||
|
||||
try {
|
||||
(new ZipExtractor)->extract($zip, $this->dir.'/staging');
|
||||
$this->fail('Das Archiv hätte abgelehnt werden müssen.');
|
||||
} catch (RuntimeException $e) {
|
||||
$this->assertStringContainsString('Unsicherer Pfad', $e->getMessage());
|
||||
}
|
||||
|
||||
$this->assertFileDoesNotExist($this->dir.'/evil.php');
|
||||
$this->assertFileDoesNotExist(dirname($this->dir).'/evil.php');
|
||||
$this->assertFileDoesNotExist($this->dir.'/staging/../evil.php');
|
||||
}
|
||||
|
||||
public function test_dangerous_entry_names_are_rejected(): void
|
||||
{
|
||||
foreach (['../evil', 'a/../../evil', '/etc/passwd', 'C:\\Windows\\evil.dll', "a\0b", '..\\evil'] as $name) {
|
||||
$this->assertFalse(ZipExtractor::isSafeEntryName($name), $name);
|
||||
}
|
||||
|
||||
foreach (['app/Version.php', 'repo-abc/public/.htaccess', 'a/..b/c'] as $name) {
|
||||
$this->assertTrue(ZipExtractor::isSafeEntryName($name), $name);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_protected_paths_are_skipped_and_nothing_is_deleted(): void
|
||||
{
|
||||
$staging = $this->dir.'/staging';
|
||||
$target = $this->dir.'/target';
|
||||
|
||||
foreach ([
|
||||
'app/Neu.php' => 'neu',
|
||||
'app/Version.php' => 'neue Version',
|
||||
'.env' => 'APP_KEY=aus-dem-archiv',
|
||||
'storage/app/license.json' => '{}',
|
||||
'public/uploads/bild.jpg' => 'fremd',
|
||||
'plugins/kunde/plugin.json' => '{}',
|
||||
'vendor/autoload.php' => 'neu',
|
||||
] as $file => $contents) {
|
||||
@mkdir(dirname("{$staging}/{$file}"), 0777, true);
|
||||
file_put_contents("{$staging}/{$file}", $contents);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'app/Version.php' => 'alte Version',
|
||||
'app/Alt.php' => 'bleibt',
|
||||
'.env' => 'APP_KEY=geheim',
|
||||
'storage/app/license.json' => '{"email":"lizenz@example.com"}',
|
||||
] as $file => $contents) {
|
||||
@mkdir(dirname("{$target}/{$file}"), 0777, true);
|
||||
file_put_contents("{$target}/{$file}", $contents);
|
||||
}
|
||||
|
||||
$result = (new StagingApplier(new ProtectedPaths(config('updater.protected_paths'))))->apply($staging, $target);
|
||||
|
||||
$this->assertSame(['copied' => 3, 'skipped' => 4], $result);
|
||||
$this->assertSame('neue Version', file_get_contents("{$target}/app/Version.php"));
|
||||
$this->assertSame('neu', file_get_contents("{$target}/app/Neu.php"));
|
||||
$this->assertSame('neu', file_get_contents("{$target}/vendor/autoload.php"));
|
||||
$this->assertSame('bleibt', file_get_contents("{$target}/app/Alt.php"));
|
||||
$this->assertSame('APP_KEY=geheim', file_get_contents("{$target}/.env"));
|
||||
$this->assertSame('{"email":"lizenz@example.com"}', file_get_contents("{$target}/storage/app/license.json"));
|
||||
$this->assertFileDoesNotExist("{$target}/public/uploads/bild.jpg");
|
||||
$this->assertFileDoesNotExist("{$target}/plugins/kunde/plugin.json");
|
||||
$this->assertEmpty(glob("{$target}/app/*.update-*"));
|
||||
}
|
||||
|
||||
public function test_protected_path_matching(): void
|
||||
{
|
||||
$paths = new ProtectedPaths(['.env', 'storage/', 'config/local.php']);
|
||||
|
||||
$this->assertTrue($paths->isProtected('.env'));
|
||||
$this->assertTrue($paths->isProtected('storage'));
|
||||
$this->assertTrue($paths->isProtected('storage/logs/x.log'));
|
||||
$this->assertTrue($paths->isProtected('config/local.php'));
|
||||
$this->assertFalse($paths->isProtected('.env.example'));
|
||||
$this->assertFalse($paths->isProtected('storagebox/a'));
|
||||
$this->assertFalse($paths->isProtected('config/app.php'));
|
||||
}
|
||||
}
|
||||
193
tests/Feature/Update/LicenseTest.php
Normal file
193
tests/Feature/Update/LicenseTest.php
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Update;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\License\LicenseService;
|
||||
use App\Support\License\LicenseStore;
|
||||
use App\Support\License\ServerError;
|
||||
use App\Support\Update\Channels;
|
||||
use App\Support\Update\Filesystem;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
use App\Version;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Client\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Tests\TestCase;
|
||||
|
||||
class LicenseTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private string $dir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->dir = sys_get_temp_dir().'/inhaus-lic-'.bin2hex(random_bytes(4));
|
||||
mkdir($this->dir);
|
||||
$this->app->instance(LicenseStore::class, new LicenseStore($this->dir.'/license.json'));
|
||||
$this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version'));
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Filesystem::deleteDirectory($this->dir);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function store(): LicenseStore
|
||||
{
|
||||
return app(LicenseStore::class);
|
||||
}
|
||||
|
||||
public function test_device_id_is_created_once_and_kept(): void
|
||||
{
|
||||
$id = $this->store()->deviceId();
|
||||
|
||||
$this->assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $id);
|
||||
$this->assertSame($id, (new LicenseStore($this->dir.'/license.json'))->deviceId());
|
||||
}
|
||||
|
||||
public function test_license_headers_are_sent_with_device_data(): void
|
||||
{
|
||||
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL-123');
|
||||
$this->store()->saveDeviceToken('token-1');
|
||||
Http::fake(['*' => Http::response(['has_update' => false, 'latest_sha' => str_repeat('a', 40)])]);
|
||||
|
||||
app(Channels::class)->client()->check(null);
|
||||
|
||||
Http::assertSent(function (Request $request) {
|
||||
parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);
|
||||
|
||||
return $request->hasHeader('X-License-Email', 'lizenz@firma.de')
|
||||
&& $request->hasHeader('Authorization', 'Bearer SCHLUESSEL-123')
|
||||
&& $request->hasHeader('X-Device-Id', $this->store()->deviceId())
|
||||
&& $request->hasHeader('X-Device-Token', 'token-1')
|
||||
&& ($query['hostname'] ?? null) === gethostname()
|
||||
&& str_contains($query['device_label'] ?? '', base_path())
|
||||
&& ($query['app_version'] ?? null) === Version::VERSION
|
||||
&& str_starts_with($request->url(), 'https://update.loheide.cloud/mitarbeiterportal/check');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_no_license_headers_without_license(): void
|
||||
{
|
||||
Http::fake(['*' => Http::response(['code' => 'license_required', 'error' => 'x'], 401)]);
|
||||
|
||||
try {
|
||||
app(Channels::class)->client()->version();
|
||||
} catch (ServerError) {
|
||||
}
|
||||
|
||||
Http::assertSent(fn (Request $request) => ! $request->hasHeader('X-License-Email')
|
||||
&& ! $request->hasHeader('Authorization')
|
||||
&& ! $request->hasHeader('X-Device-Id'));
|
||||
}
|
||||
|
||||
public function test_new_device_token_is_stored_even_on_error_responses(): void
|
||||
{
|
||||
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
|
||||
|
||||
Http::fake(['*' => Http::response(['code' => 'license_expired', 'error' => 'abgelaufen'], 403, ['X-Device-Token' => 'rotiert-im-fehler'])]);
|
||||
|
||||
try {
|
||||
app(Channels::class)->client()->check(null);
|
||||
$this->fail('Fehler erwartet.');
|
||||
} catch (ServerError $e) {
|
||||
$this->assertSame('license_expired', $e->errorCode);
|
||||
}
|
||||
|
||||
$this->assertSame('rotiert-im-fehler', (new LicenseStore($this->dir.'/license.json'))->deviceToken());
|
||||
}
|
||||
|
||||
public function test_device_token_from_json_body_is_stored(): void
|
||||
{
|
||||
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
|
||||
Http::fake(['*' => Http::response(['sha' => str_repeat('b', 40), 'device_token' => 'aus-dem-json'])]);
|
||||
|
||||
$data = app(Channels::class)->client()->version();
|
||||
|
||||
$this->assertSame(str_repeat('b', 40), $data['sha']);
|
||||
$this->assertSame('aus-dem-json', $this->store()->deviceToken());
|
||||
}
|
||||
|
||||
public function test_device_token_from_download_is_stored(): void
|
||||
{
|
||||
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
|
||||
Http::fake(['*' => Http::response('PK...', 200, ['X-Device-Token' => 'vom-download'])]);
|
||||
|
||||
app(Channels::class)->client()->downloadZip(str_repeat('c', 40), $this->dir.'/x.zip');
|
||||
|
||||
$this->assertSame('vom-download', $this->store()->deviceToken());
|
||||
}
|
||||
|
||||
public function test_license_errors_give_messages_and_never_block_the_portal(): void
|
||||
{
|
||||
$admin = User::factory()->admin()->create();
|
||||
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
|
||||
|
||||
$code = null;
|
||||
Http::fake(function () use (&$code) {
|
||||
return Http::response(
|
||||
['code' => $code, 'error' => 'egal', 'devices_used' => 3, 'devices_max' => 3],
|
||||
$code === 'rate_limited' ? 429 : 403,
|
||||
);
|
||||
});
|
||||
|
||||
foreach ([
|
||||
'license_expired' => 'abgelaufen',
|
||||
'invalid_key' => 'Lizenzschlüssel ist unbekannt',
|
||||
'device_limit_reached' => '3 von 3',
|
||||
'license_revoked' => 'Support',
|
||||
'device_cloned' => 'kopierten Installation',
|
||||
'rate_limited' => 'erneut versuchen',
|
||||
] as $code => $expected) {
|
||||
$response = $this->actingAs($admin)
|
||||
->postJson('/admin/update/check')
|
||||
->assertOk()
|
||||
->assertJson(['ok' => false, 'code' => $code]);
|
||||
|
||||
$this->assertStringContainsString($expected, $response->json('message'));
|
||||
|
||||
// Das Portal bleibt uneingeschränkt nutzbar.
|
||||
$this->actingAs($admin)->get('/')->assertOk();
|
||||
$this->actingAs($admin)->get('/admin')->assertOk();
|
||||
$this->actingAs($admin)->get('/admin/aktualisierung')->assertOk();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_unlimited_license_is_not_treated_as_expired(): void
|
||||
{
|
||||
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
|
||||
Http::fake(['*' => Http::response([
|
||||
'licensing_required' => true,
|
||||
'license' => ['status' => 'active', 'valid_until' => null, 'unlimited' => true, 'days_remaining' => null, 'expired' => false],
|
||||
'registered_to' => ['license_email' => 'lizenz@firma.de', 'company' => 'Beispiel GmbH', 'contact_name' => 'Max Muster'],
|
||||
'devices' => ['used' => 1, 'max' => 2, 'policy' => 'enforce'],
|
||||
])]);
|
||||
|
||||
app(LicenseService::class)->check();
|
||||
$summary = app(LicenseService::class)->summary();
|
||||
|
||||
$this->assertTrue($summary['unlimited']);
|
||||
$this->assertFalse($summary['expired']);
|
||||
$this->assertFalse($summary['expires_soon']);
|
||||
|
||||
$this->actingAs(User::factory()->admin()->create())
|
||||
->get('/admin/aktualisierung')
|
||||
->assertOk()
|
||||
->assertSee('unbefristet')
|
||||
->assertSee('Beispiel GmbH')
|
||||
->assertSee('1 von 2 belegt');
|
||||
}
|
||||
|
||||
public function test_unknown_channel_is_rejected(): void
|
||||
{
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
|
||||
app(Channels::class)->client('nightly');
|
||||
}
|
||||
}
|
||||
142
tests/Feature/Update/UpdateEndpointsTest.php
Normal file
142
tests/Feature/Update/UpdateEndpointsTest.php
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Update;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\Update\Channels;
|
||||
use App\Support\Update\Filesystem;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
use App\Support\Update\MaintenanceFlag;
|
||||
use App\Support\Update\UpdateProgress;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Tests\TestCase;
|
||||
|
||||
class UpdateEndpointsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private string $dir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->dir = sys_get_temp_dir().'/inhaus-ep-'.bin2hex(random_bytes(4));
|
||||
mkdir($this->dir);
|
||||
$this->app->instance(MaintenanceFlag::class, new MaintenanceFlag($this->dir.'/.maintenance'));
|
||||
$this->app->instance(UpdateProgress::class, new UpdateProgress($this->dir.'/.progress'));
|
||||
$this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version'));
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Filesystem::deleteDirectory($this->dir);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_update_endpoints_are_admin_only(): void
|
||||
{
|
||||
$this->postJson('/admin/update/check')->assertUnauthorized();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
foreach (['check', 'install', 'channel', 'migrations'] as $endpoint) {
|
||||
$this->actingAs($user)->postJson("/admin/update/{$endpoint}")->assertForbidden();
|
||||
}
|
||||
|
||||
$this->actingAs($user)->getJson('/admin/update/progress')->assertForbidden();
|
||||
$this->actingAs($user)->get('/admin/aktualisierung')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_maintenance_mode_shows_503_but_keeps_update_pages_reachable(): void
|
||||
{
|
||||
$admin = User::factory()->admin()->create();
|
||||
app(MaintenanceFlag::class)->activate(300);
|
||||
|
||||
$this->actingAs($admin)->get('/')
|
||||
->assertStatus(503)
|
||||
->assertHeader('Retry-After')
|
||||
->assertSee('Das Portal wird gerade aktualisiert');
|
||||
|
||||
$this->actingAs($admin)->getJson('/admin/update/progress')->assertOk()->assertJson(['step' => 'idle']);
|
||||
$this->actingAs($admin)->get('/admin/aktualisierung')->assertOk();
|
||||
$this->get('/up')->assertOk();
|
||||
|
||||
app(MaintenanceFlag::class)->deactivate();
|
||||
$this->actingAs($admin)->get('/')->assertOk();
|
||||
}
|
||||
|
||||
public function test_first_check_of_fresh_installation_remembers_latest_sha(): void
|
||||
{
|
||||
Http::fake(['*' => Http::response(['has_update' => false, 'latest_sha' => str_repeat('d', 40), 'version' => '0.2.0'])]);
|
||||
|
||||
$this->actingAs(User::factory()->admin()->create())
|
||||
->postJson('/admin/update/check')
|
||||
->assertOk()
|
||||
->assertJson(['ok' => true, 'result' => ['has_update' => false, 'changelog' => []]]);
|
||||
|
||||
Http::assertSent(fn ($request) => ! str_contains($request->url(), 'current_sha'));
|
||||
$this->assertSame(str_repeat('d', 40), app(InstalledVersion::class)->current());
|
||||
}
|
||||
|
||||
public function test_check_shows_changelog_preview_without_commit_texts(): void
|
||||
{
|
||||
app(InstalledVersion::class)->save(str_repeat('a', 40));
|
||||
|
||||
Http::fake(['*' => Http::response([
|
||||
'has_update' => true,
|
||||
'latest_sha' => str_repeat('b', 40),
|
||||
'version' => '0.3.0',
|
||||
'versions_behind' => 4,
|
||||
'changelog_preview' => [
|
||||
'entries' => [['version' => '0.3.0', 'heading' => '0.3.0', 'text' => "- Neue **Umfragen**\n- <script>x</script>"]],
|
||||
'complete' => false,
|
||||
],
|
||||
])]);
|
||||
|
||||
$response = $this->actingAs(User::factory()->admin()->create())
|
||||
->postJson('/admin/update/check')
|
||||
->assertOk()
|
||||
->assertJsonPath('result.has_update', true)
|
||||
->assertJsonPath('result.version', '0.3.0')
|
||||
->assertJsonPath('result.latest_short', 'bbbbbbb')
|
||||
->assertJsonPath('result.versions_behind', 4)
|
||||
->assertJsonPath('result.changelog_complete', false);
|
||||
|
||||
Http::assertSent(fn ($request) => str_contains($request->url(), 'current_sha='.str_repeat('a', 40)));
|
||||
$this->assertStringContainsString('<strong>Umfragen</strong>', $response->json('result.changelog.0.html'));
|
||||
$this->assertStringNotContainsString('<script>', $response->json('result.changelog.0.html'));
|
||||
}
|
||||
|
||||
public function test_channel_can_be_changed_and_unknown_channels_are_rejected(): void
|
||||
{
|
||||
$admin = User::factory()->admin()->create();
|
||||
|
||||
$this->actingAs($admin)->postJson('/admin/update/channel', ['channel' => 'development'])->assertOk();
|
||||
$this->assertSame('development', app(Channels::class)->active());
|
||||
|
||||
$this->actingAs($admin)->postJson('/admin/update/channel', ['channel' => 'nightly'])->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_unconfigured_channel_gives_clear_message(): void
|
||||
{
|
||||
Http::fake(['*' => Http::response(['code' => 'unknown_tool', 'error' => 'nicht konfiguriert'], 404)]);
|
||||
|
||||
$this->actingAs(User::factory()->admin()->create())
|
||||
->postJson('/admin/update/check')
|
||||
->assertOk()
|
||||
->assertJsonPath('code', 'unknown_tool')
|
||||
->assertJsonPath('message', 'Dieser Update-Kanal ist beim Hersteller noch nicht eingerichtet. Bitte den Kanal „Stabil“ verwenden.');
|
||||
}
|
||||
|
||||
public function test_install_is_refused_while_another_run_is_active(): void
|
||||
{
|
||||
app(UpdateProgress::class)->set(50, 'extract', 'läuft');
|
||||
|
||||
$this->actingAs(User::factory()->admin()->create())
|
||||
->postJson('/admin/update/install')
|
||||
->assertStatus(409);
|
||||
}
|
||||
}
|
||||
113
tests/Feature/Update/UpdateStateTest.php
Normal file
113
tests/Feature/Update/UpdateStateTest.php
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Update;
|
||||
|
||||
use App\Support\Update\Filesystem;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
use App\Support\Update\MaintenanceFlag;
|
||||
use App\Support\Update\UpdateProgress;
|
||||
use InvalidArgumentException;
|
||||
use Tests\TestCase;
|
||||
|
||||
class UpdateStateTest extends TestCase
|
||||
{
|
||||
private string $dir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->dir = sys_get_temp_dir().'/inhaus-state-'.bin2hex(random_bytes(4));
|
||||
mkdir($this->dir);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Filesystem::deleteDirectory($this->dir);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_sha_is_read_and_written(): void
|
||||
{
|
||||
$version = new InstalledVersion($this->dir.'/.version');
|
||||
|
||||
$this->assertNull($version->current());
|
||||
$this->assertSame('0.2.0', $version->release());
|
||||
$this->assertSame('0.2.0', $version->full());
|
||||
|
||||
$version->save('A1B2C3D4E5F60718293a4b5c6d7e8f9012345678');
|
||||
|
||||
$this->assertSame('a1b2c3d4e5f60718293a4b5c6d7e8f9012345678', $version->current());
|
||||
$this->assertSame('a1b2c3d', $version->short());
|
||||
$this->assertSame('0.2.0 (a1b2c3d)', $version->full());
|
||||
}
|
||||
|
||||
public function test_invalid_sha_is_rejected(): void
|
||||
{
|
||||
$version = new InstalledVersion($this->dir.'/.version');
|
||||
|
||||
foreach (['', 'main', 'a1b2c3d', str_repeat('g', 40), str_repeat('a', 41)] as $invalid) {
|
||||
try {
|
||||
$version->save($invalid);
|
||||
$this->fail("„{$invalid}“ hätte abgelehnt werden müssen.");
|
||||
} catch (InvalidArgumentException) {
|
||||
$this->assertNull($version->current());
|
||||
}
|
||||
}
|
||||
|
||||
file_put_contents($this->dir.'/.version', "kaputt\n");
|
||||
$this->assertNull($version->current());
|
||||
}
|
||||
|
||||
public function test_maintenance_mode_heals_itself_after_expiry(): void
|
||||
{
|
||||
$flag = new MaintenanceFlag($this->dir.'/.maintenance');
|
||||
|
||||
$this->assertFalse($flag->isActive());
|
||||
|
||||
$flag->activate(600);
|
||||
$this->assertTrue($flag->isActive());
|
||||
|
||||
$flag->deactivate();
|
||||
$this->assertFalse($flag->isActive());
|
||||
|
||||
// Absturz mitten im Update: Flag bleibt liegen, ist aber abgelaufen.
|
||||
file_put_contents($this->dir.'/.maintenance', json_encode(['since' => time() - 700, 'until' => time() - 100]));
|
||||
$this->assertFalse($flag->isActive());
|
||||
$this->assertFileDoesNotExist($this->dir.'/.maintenance');
|
||||
|
||||
// Kaputte Datei sperrt ebenfalls nicht.
|
||||
file_put_contents($this->dir.'/.maintenance', 'Müll');
|
||||
$this->assertFalse($flag->isActive());
|
||||
}
|
||||
|
||||
public function test_progress_file_including_error_state(): void
|
||||
{
|
||||
$progress = new UpdateProgress($this->dir.'/.update-progress');
|
||||
|
||||
$this->assertSame(['pct' => 0, 'step' => 'idle', 'text' => '', 'ts' => 0], $progress->get());
|
||||
$this->assertFalse($progress->isRunning());
|
||||
|
||||
$progress->set(20, 'download', 'Lädt …');
|
||||
$this->assertSame(20, $progress->get()['pct']);
|
||||
$this->assertSame('Lädt …', $progress->get()['text']);
|
||||
$this->assertTrue($progress->isRunning());
|
||||
|
||||
$progress->fail('Kaputt');
|
||||
$this->assertSame(-1, $progress->get()['pct']);
|
||||
$this->assertSame('error', $progress->get()['step']);
|
||||
$this->assertFalse($progress->isRunning());
|
||||
}
|
||||
|
||||
public function test_stale_run_does_not_block_forever(): void
|
||||
{
|
||||
$progress = new UpdateProgress($this->dir.'/.update-progress');
|
||||
|
||||
file_put_contents($this->dir.'/.update-progress', json_encode([
|
||||
'pct' => 50, 'step' => 'extract', 'text' => '', 'ts' => time() - UpdateProgress::STALE_AFTER_SECONDS - 1,
|
||||
]));
|
||||
|
||||
$this->assertFalse($progress->isRunning());
|
||||
}
|
||||
}
|
||||
193
tests/Feature/Update/UpdaterTest.php
Normal file
193
tests/Feature/Update/UpdaterTest.php
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Update;
|
||||
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\User;
|
||||
use App\Support\License\LicenseStore;
|
||||
use App\Support\Update\Changelog;
|
||||
use App\Support\Update\Channels;
|
||||
use App\Support\Update\Filesystem;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
use App\Support\Update\MaintenanceFlag;
|
||||
use App\Support\Update\Migrations;
|
||||
use App\Support\Update\UpdateProgress;
|
||||
use App\Support\Update\Updater;
|
||||
use App\Support\Update\ZipExtractor;
|
||||
use App\Version;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
use ZipArchive;
|
||||
|
||||
class UpdaterTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private const SHA = '1111111111111111111111111111111111111111';
|
||||
|
||||
private string $dir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->dir = sys_get_temp_dir().'/inhaus-upd-'.bin2hex(random_bytes(4));
|
||||
mkdir($this->dir.'/storage', 0777, true);
|
||||
$this->app->useStoragePath($this->dir.'/storage');
|
||||
$this->app->instance(LicenseStore::class, new LicenseStore($this->dir.'/license.json'));
|
||||
$this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version'));
|
||||
$this->app->instance(UpdateProgress::class, new UpdateProgress($this->dir.'/.progress'));
|
||||
$this->app->instance(MaintenanceFlag::class, new MaintenanceFlag($this->dir.'/.maintenance'));
|
||||
mkdir($this->dir.'/storage/app', 0777, true);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Filesystem::deleteDirectory($this->dir);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function zipContents(): string
|
||||
{
|
||||
$path = $this->dir.'/build.zip';
|
||||
$zip = new ZipArchive;
|
||||
$zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE);
|
||||
$zip->addFromString('repo-1111111/app/Neu.php', '<?php // neu');
|
||||
$zip->addFromString('repo-1111111/.env', 'APP_KEY=aus-dem-archiv');
|
||||
$zip->close();
|
||||
|
||||
return file_get_contents($path);
|
||||
}
|
||||
|
||||
private function updater(string $target): Updater
|
||||
{
|
||||
return new Updater(
|
||||
app(Channels::class),
|
||||
app(InstalledVersion::class),
|
||||
app(UpdateProgress::class),
|
||||
app(MaintenanceFlag::class),
|
||||
new ZipExtractor,
|
||||
app(Migrations::class),
|
||||
$target,
|
||||
);
|
||||
}
|
||||
|
||||
public function test_full_update_run(): void
|
||||
{
|
||||
$zip = $this->zipContents();
|
||||
|
||||
Http::fake([
|
||||
'update.loheide.cloud/mitarbeiterportal/version*' => Http::response(['sha' => self::SHA, 'version' => '0.3.0']),
|
||||
'update.loheide.cloud/mitarbeiterportal/zip*' => Http::response($zip, 200, [
|
||||
'Content-Type' => 'application/zip',
|
||||
'X-Commit-Sha' => self::SHA,
|
||||
'X-Content-Sha256' => hash('sha256', $zip),
|
||||
]),
|
||||
]);
|
||||
|
||||
$target = $this->dir.'/app-root';
|
||||
mkdir($target);
|
||||
file_put_contents($target.'/.env', 'APP_KEY=geheim');
|
||||
$admin = User::factory()->admin()->create();
|
||||
|
||||
$result = $this->updater($target)->installUpdate($admin->id);
|
||||
|
||||
$this->assertSame(self::SHA, $result['sha']);
|
||||
$this->assertSame(0, $result['migrations']);
|
||||
$this->assertFileExists($target.'/app/Neu.php');
|
||||
$this->assertSame('APP_KEY=geheim', file_get_contents($target.'/.env'));
|
||||
$this->assertSame(self::SHA, app(InstalledVersion::class)->current());
|
||||
$this->assertSame('done', app(UpdateProgress::class)->get()['step']);
|
||||
$this->assertSame(100, app(UpdateProgress::class)->get()['pct']);
|
||||
$this->assertFalse(app(MaintenanceFlag::class)->isActive());
|
||||
$this->assertDirectoryDoesNotExist($this->dir.'/storage/.update-staging');
|
||||
|
||||
$audit = AuditLog::query()->where('action', 'update.installed')->firstOrFail();
|
||||
$this->assertSame($admin->id, $audit->user_id);
|
||||
$this->assertSame(['channel' => 'stable', 'sha' => self::SHA, 'migrations' => 0, 'files' => 1], $audit->data);
|
||||
}
|
||||
|
||||
public function test_error_page_instead_of_zip_is_rejected(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*/version*' => Http::response(['sha' => self::SHA]),
|
||||
'*/zip*' => Http::response('<html>Proxy-Fehler</html>', 200, ['Content-Type' => 'text/html']),
|
||||
]);
|
||||
|
||||
$target = $this->dir.'/app-root';
|
||||
mkdir($target);
|
||||
|
||||
try {
|
||||
$this->updater($target)->installUpdate();
|
||||
$this->fail('Das Update hätte abbrechen müssen.');
|
||||
} catch (RuntimeException $e) {
|
||||
$this->assertStringContainsString('kein ZIP-Archiv', $e->getMessage());
|
||||
}
|
||||
|
||||
$progress = app(UpdateProgress::class)->get();
|
||||
$this->assertSame('error', $progress['step']);
|
||||
$this->assertSame(-1, $progress['pct']);
|
||||
$this->assertFalse(app(MaintenanceFlag::class)->isActive(), 'Wartungsmodus muss auch im Fehlerfall enden.');
|
||||
$this->assertNull(app(InstalledVersion::class)->current());
|
||||
$this->assertSame(1, AuditLog::query()->where('action', 'update.failed')->count());
|
||||
}
|
||||
|
||||
public function test_checksum_mismatch_is_rejected(): void
|
||||
{
|
||||
$zip = $this->zipContents();
|
||||
|
||||
Http::fake([
|
||||
'*/version*' => Http::response(['sha' => self::SHA]),
|
||||
'*/zip*' => Http::response($zip, 200, ['X-Content-Sha256' => str_repeat('0', 64)]),
|
||||
]);
|
||||
|
||||
$target = $this->dir.'/app-root';
|
||||
mkdir($target);
|
||||
|
||||
$this->expectExceptionMessage('Prüfsumme');
|
||||
|
||||
$this->updater($target)->installUpdate();
|
||||
}
|
||||
|
||||
public function test_migration_counter(): void
|
||||
{
|
||||
$migrations = app(Migrations::class);
|
||||
|
||||
$this->assertSame([], $migrations->pending());
|
||||
$this->assertSame(0, $migrations->run());
|
||||
$this->assertNotEmpty($migrations->status());
|
||||
$this->assertTrue(collect($migrations->status())->every(fn (array $m) => $m['ran']));
|
||||
$this->assertSame(40, strlen($migrations->fingerprint()));
|
||||
}
|
||||
|
||||
public function test_changelog_is_parsed_and_rendered_safely(): void
|
||||
{
|
||||
$sections = app(Changelog::class)->sections(<<<'MD'
|
||||
# Änderungsprotokoll
|
||||
|
||||
Einleitung
|
||||
|
||||
## 1.2.0
|
||||
|
||||
- Neue **Funktion**
|
||||
- [Link](javascript:alert(1)) und <script>alert(1)</script>
|
||||
|
||||
## 1.1.3 – Fehlerbehebung
|
||||
|
||||
- Fix
|
||||
MD);
|
||||
|
||||
$this->assertCount(2, $sections);
|
||||
$this->assertSame('1.2.0', $sections[0]['version']);
|
||||
$this->assertSame('1.1.3', $sections[1]['version']);
|
||||
$this->assertSame('1.1.3 – Fehlerbehebung', $sections[1]['heading']);
|
||||
$this->assertStringContainsString('<strong>Funktion</strong>', $sections[0]['html']);
|
||||
$this->assertStringNotContainsString('javascript:', $sections[0]['html']);
|
||||
$this->assertStringNotContainsString('<script>', $sections[0]['html']);
|
||||
|
||||
$this->assertSame(Version::VERSION, app(Changelog::class)->sections()[0]['version']);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue