Add one-click git-based auto-update (manual trigger only)

Phase 6 of the dashboard roadmap - the largest and riskiest item, since
it overwrites live production code. Pulls the current main branch from
the public Gitea repo over plain HTTPS (archive zip download + REST API
for commit info) and applies it to the live hifi/ tree - no SSH,
git binary, exec(), or shell_exec() anywhere, so it works on plain
shared PHP hosting with no CI/deploy pipeline (exactly the hosting this
site actually runs on, per DEPLOY.md's manual-FTP fallback).

Six independent endpoints (status/check/download/extract/backup/apply)
instead of one big request, mirroring the existing multi-step
SetupController pattern - this app has no job-queue infrastructure, and
a single ~127MB download+extract+backup+copy is the most likely way to
hit an unknown host's max_execution_time or reverse-proxy timeout.
GitUpdateService.php does the actual work; UpdateController.php is a
thin adapter that marks each step in-progress/failed in a new gitignored
update-state.php (same convention as db.php) so a crashed step shows as
failed rather than stuck, and a retry starts clean.

Security-critical bits:
- The backup zip necessarily contains db.php (must be fully restorable),
  so it lives under hifi/_update/ behind a "Require all denied" .htaccess
  written the instant the directory is created, and hifi/_update/ was
  added to .gitignore in this same commit, before any code that could
  write into it - both needed since a physically-existing file bypasses
  this app's SPA-fallback/API rewrite rules entirely.
- Only hifi/'s own subtree is extracted from the archive (hifi-src/ and
  everything else ignored) via a wrapper-folder-prefix detected at
  runtime, not hardcoded.
- Copy-then-prune (not copy-only) across the whole hifi/ tree, since
  Vite renames JS/CSS chunks on every build and a copy-only updater
  would let stale chunks accumulate forever - guarded by a denylist
  (db.php, setup.php, ga-service-account.json, update-state.php,
  api/uploads/, plus local Claude-tooling dirs) that must never be
  touched in either direction.
- index.html is swapped in last via copy+rename (near-atomic), after
  the new hashed assets it references are already fully in place.
- Reuses SchemaController's existing migration logic as the last apply
  step (extracted into a new runMigration() so it's callable without
  Http::send()/exit ending the response early) and app_settings'
  existing maintenance-mode column to show visitors a maintenance page
  during the brief apply window, restoring whatever maintenance state
  existed before the update ran (not just forcing it off).

Gated behind a new, narrower system.update permission (not the broader
settings.manage), with its own settings tab hidden from anyone lacking
it - unlike this app's usual "everyone with settings.manage sees every
tab" pattern, since this one can overwrite the whole site.

Verified in isolation (synthetic zip + fixture directories in a scratch
folder, not the real hifi/ tree): wrapper-folder detection and
selective hifi/-subtree extraction, and copy+prune with denylist
enforcement. Not yet verified: behavior on an actual shared-hosting
target (max_execution_time, ZipArchive availability, outbound HTTPS
egress, disk quota vs disk_free_space()) - per the plan, validate
against the Plesk test server from DEPLOY.md before ever running this
against a real client site. Also enabled the php_zip extension in the
local XAMPP php.ini, since it was disabled and this feature needs it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Maaxxs 2026-09-09 02:16:41 +02:00
parent 5f1d4e1092
commit 3ea5bd4201
11 changed files with 981 additions and 55 deletions

9
.gitignore vendored
View file

@ -31,6 +31,15 @@
# (wird vom Admin-Panel automatisch neu geschrieben, enthält einen privaten Schlüssel) # (wird vom Admin-Panel automatisch neu geschrieben, enthält einen privaten Schlüssel)
/hifi/api/config/ga-service-account.json /hifi/api/config/ga-service-account.json
# Merkt sich den aktuell installierten Git-Commit fürs Auto-Update-Feature
# (GitUpdateService) - pro Umgebung unterschiedlich, wird automatisch geschrieben.
/hifi/api/config/update-state.php
# Arbeits-/Backup-Verzeichnis des Auto-Update-Features. Die Backup-ZIPs darin enthalten
# zwangsläufig db.php (siehe oben) - darf NIE ins Repo gelangen, sonst landen
# Datenbank-Zugangsdaten im (öffentlichen!) Git-Repo.
/hifi/_update/
# Claude-Code-Tooling (Skills/lokale Einstellungen) - gehört nicht zum Website-Projekt # Claude-Code-Tooling (Skills/lokale Einstellungen) - gehört nicht zum Website-Projekt
/hifi/.claude/ /hifi/.claude/
/hifi/.agents/ /hifi/.agents/

View file

@ -40,6 +40,7 @@ import PermissionGroups from './pages/admin/PermissionGroups.jsx';
import SettingsLayout from './pages/admin/settings/SettingsLayout.jsx'; import SettingsLayout from './pages/admin/settings/SettingsLayout.jsx';
import WebsiteSettings from './pages/admin/settings/WebsiteSettings.jsx'; import WebsiteSettings from './pages/admin/settings/WebsiteSettings.jsx';
import LegalSettings from './pages/admin/settings/LegalSettings.jsx'; import LegalSettings from './pages/admin/settings/LegalSettings.jsx';
import UpdateSettings from './pages/admin/settings/UpdateSettings.jsx';
import EmailSettings from './pages/admin/settings/EmailSettings.jsx'; import EmailSettings from './pages/admin/settings/EmailSettings.jsx';
import DatabaseSettings from './pages/admin/settings/DatabaseSettings.jsx'; import DatabaseSettings from './pages/admin/settings/DatabaseSettings.jsx';
import ExportImportSettings from './pages/admin/settings/ExportImportSettings.jsx'; import ExportImportSettings from './pages/admin/settings/ExportImportSettings.jsx';
@ -100,6 +101,10 @@ export default function App() {
<Route path="database" element={<DatabaseSettings />} /> <Route path="database" element={<DatabaseSettings />} />
<Route path="export-import" element={<ExportImportSettings />} /> <Route path="export-import" element={<ExportImportSettings />} />
<Route path="maintenance" element={<MaintenanceSettings />} /> <Route path="maintenance" element={<MaintenanceSettings />} />
<Route
path="update"
element={<RequirePermission permission="system.update"><UpdateSettings /></RequirePermission>}
/>
<Route path="reset" element={<ResetSettings />} /> <Route path="reset" element={<ResetSettings />} />
</Route> </Route>
</Route> </Route>

View file

@ -1,4 +1,5 @@
import { NavLink, Outlet } from 'react-router-dom'; import { NavLink, Outlet } from 'react-router-dom';
import { useAuth } from '../../../context/AuthContext.jsx';
const tabs = [ const tabs = [
{ to: '/admin/settings/website', label: 'Website' }, { to: '/admin/settings/website', label: 'Website' },
@ -7,10 +8,17 @@ const tabs = [
{ to: '/admin/settings/database', label: 'Datenbank' }, { to: '/admin/settings/database', label: 'Datenbank' },
{ to: '/admin/settings/export-import', label: 'Export & Import' }, { to: '/admin/settings/export-import', label: 'Export & Import' },
{ to: '/admin/settings/maintenance', label: 'Wartungsmodus' }, { to: '/admin/settings/maintenance', label: 'Wartungsmodus' },
// Eigene, engere Berechtigung (ueberschreibt Live-Code) statt nur der allgemeinen
// settings.manage-Sperre um den ganzen Bereich - anders als die restlichen Tabs hier
// gefiltert, nicht jeder mit Zugriff auf "Einstellungen" soll das automatisch sehen.
{ to: '/admin/settings/update', label: 'Updates', permission: 'system.update' },
{ to: '/admin/settings/reset', label: 'Zurücksetzen' }, { to: '/admin/settings/reset', label: 'Zurücksetzen' },
]; ];
export default function SettingsLayout() { export default function SettingsLayout() {
const { hasPermission } = useAuth();
const visibleTabs = tabs.filter((tab) => !tab.permission || hasPermission(tab.permission));
const tabClass = ({ isActive }) => const tabClass = ({ isActive }) =>
`rounded-md px-4 py-2 text-sm font-medium transition ${ `rounded-md px-4 py-2 text-sm font-medium transition ${
isActive isActive
@ -25,7 +33,7 @@ export default function SettingsLayout() {
Werkzeuge rund um Datenbank, Server-Umzug und Zurücksetzen dieser Seite. Werkzeuge rund um Datenbank, Server-Umzug und Zurücksetzen dieser Seite.
</p> </p>
<nav className="mb-6 flex flex-wrap gap-2"> <nav className="mb-6 flex flex-wrap gap-2">
{tabs.map((tab) => ( {visibleTabs.map((tab) => (
<NavLink key={tab.to} to={tab.to} className={tabClass}> <NavLink key={tab.to} to={tab.to} className={tabClass}>
{tab.label} {tab.label}
</NavLink> </NavLink>

View file

@ -0,0 +1,197 @@
import { useEffect, useState } from 'react';
import { api } from '../../../api/client.js';
const STEP_LABELS = {
download: 'Herunterladen',
extract: 'Entpacken',
backup: 'Sichern',
apply: 'Installieren',
};
function shortSha(sha) {
return sha ? sha.slice(0, 7) : '–';
}
function formatDate(value) {
if (!value) return '–';
return new Date(value).toLocaleString('de-DE');
}
export default function UpdateSettings() {
const [status, setStatus] = useState(null);
const [check, setCheck] = useState(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [running, setRunning] = useState(false);
const [steps, setSteps] = useState({ download: null, extract: null, backup: null, apply: null }); // null | 'busy' | 'done' | 'error'
const [error, setError] = useState('');
const [applyLog, setApplyLog] = useState(null);
const load = () => {
setLoading(true);
setLoadError('');
Promise.all([api.get('/settings/update-status'), api.get('/settings/update-check')])
.then(([statusRes, checkRes]) => {
setStatus(statusRes);
setCheck(checkRes);
})
.catch((err) => setLoadError(err.message))
.finally(() => setLoading(false));
};
useEffect(load, []);
const handleInstall = async () => {
setRunning(true);
setError('');
setApplyLog(null);
setSteps({ download: 'busy', extract: null, backup: null, apply: null });
try {
const downloadRes = await api.post('/settings/update-download', {});
const runId = downloadRes.run_id;
setSteps((s) => ({ ...s, download: 'done', extract: 'busy' }));
await api.post('/settings/update-extract', { run_id: runId });
setSteps((s) => ({ ...s, extract: 'done', backup: 'busy' }));
await api.post('/settings/update-backup', {});
setSteps((s) => ({ ...s, backup: 'done', apply: 'busy' }));
const applyRes = await api.post('/settings/update-apply', { run_id: runId });
setSteps((s) => ({ ...s, apply: 'done' }));
setApplyLog(applyRes.log || []);
load();
} catch (err) {
setSteps((s) => {
const failedStep = Object.keys(s).find((key) => s[key] === 'busy');
return failedStep ? { ...s, [failedStep]: 'error' } : s;
});
setError(err.message);
} finally {
setRunning(false);
}
};
if (loading) {
return <p className="text-sm text-neutral-400">Lädt…</p>;
}
const caps = status?.capabilities || {};
const missingCapability = !caps.zip
? 'Diese Funktion benötigt die PHP-Erweiterung "zip", die auf diesem Server aktuell nicht aktiviert ist. Bitte beim Hoster aktivieren lassen.'
: !caps.http_client
? 'Diese Funktion benötigt ausgehende HTTPS-Verbindungen (curl oder allow_url_fopen), die auf diesem Server aktuell nicht verfügbar sind.'
: !caps.writable
? 'Das Website-Verzeichnis ist für PHP nicht beschreibbar - bitte Dateiberechtigungen prüfen.'
: null;
const updateAvailable = check?.update_available;
return (
<div className="max-w-2xl space-y-6">
<section className="rounded-xl border border-neutral-200 bg-white p-6 dark:border-neutral-800 dark:bg-neutral-900">
<h2 className="mb-1 font-semibold text-neutral-900 dark:text-white">Updates aus Git</h2>
<p className="mb-4 text-sm text-neutral-500 dark:text-neutral-400">
Zieht den aktuellen Stand direkt vom Code-Repository und installiert ihn hier - ohne manuellen
FTP-Upload. Passiert nur, wenn du unten aktiv auf "Update installieren" klickst, nie automatisch im
Hintergrund.
</p>
{loadError && <p className="mb-3 text-sm text-red-600">{loadError}</p>}
{missingCapability ? (
<p className="rounded-md bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-900/20 dark:text-amber-300">
{missingCapability}
</p>
) : (
<>
<div className="mb-4 grid grid-cols-2 gap-3 text-sm">
<div className="rounded-md bg-neutral-50 p-3 dark:bg-neutral-800/50">
<p className="text-xs uppercase tracking-wide text-neutral-400">Installiert</p>
<p className="font-mono text-neutral-800 dark:text-neutral-100">{shortSha(status?.deployed_sha)}</p>
<p className="text-xs text-neutral-400">{formatDate(status?.deployed_at)}</p>
</div>
<div className="rounded-md bg-neutral-50 p-3 dark:bg-neutral-800/50">
<p className="text-xs uppercase tracking-wide text-neutral-400">Neuester Stand</p>
<p className="font-mono text-neutral-800 dark:text-neutral-100">{shortSha(check?.latest_sha)}</p>
{check?.latest_message && (
<p className="truncate text-xs text-neutral-400" title={check.latest_message}>
{check.latest_message}
</p>
)}
</div>
</div>
{updateAvailable ? (
<p className="mb-3 text-sm font-medium text-brand-600 dark:text-brand-400">Update verfügbar.</p>
) : (
<p className="mb-3 text-sm text-neutral-500 dark:text-neutral-400">Bereits auf dem neuesten Stand.</p>
)}
<div className="mb-3 flex gap-2">
<button
type="button"
onClick={load}
disabled={running}
className="rounded-md border border-neutral-300 px-4 py-2 text-sm font-medium hover:bg-neutral-50 disabled:opacity-50 dark:border-neutral-700 dark:hover:bg-neutral-800"
>
Nach Updates suchen
</button>
<button
type="button"
onClick={handleInstall}
disabled={running || !updateAvailable}
className="rounded-md bg-brand-500 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-600 disabled:opacity-50"
>
{running ? 'Installiere…' : 'Update installieren'}
</button>
</div>
{(running || error) && (
<ul className="mb-3 space-y-1 text-sm">
{Object.entries(STEP_LABELS).map(([key, label]) => (
<li key={key} className="flex items-center gap-2">
<span
className={
steps[key] === 'done'
? 'text-green-600 dark:text-green-400'
: steps[key] === 'error'
? 'text-red-600'
: steps[key] === 'busy'
? 'text-brand-600 dark:text-brand-400'
: 'text-neutral-300 dark:text-neutral-600'
}
>
{steps[key] === 'done' ? '✓' : steps[key] === 'error' ? '✕' : steps[key] === 'busy' ? '…' : '○'}
</span>
{label}
</li>
))}
</ul>
)}
{error && <p className="text-sm text-red-600">{error}</p>}
{applyLog && (
<div className="mt-3 rounded-md bg-green-50 p-3 text-sm text-green-800 dark:bg-green-900/20 dark:text-green-300">
<p className="mb-1 font-semibold">Update installiert.</p>
{applyLog.length > 0 && (
<details>
<summary className="cursor-pointer text-xs">Details anzeigen</summary>
<ul className="mt-2 list-disc pl-5 text-xs">
{applyLog.map((line, i) => (
<li key={i}>{line}</li>
))}
</ul>
</details>
)}
</div>
)}
</>
)}
</section>
</div>
);
}

View file

@ -34,6 +34,7 @@ use App\Controllers\SettingsController;
use App\Controllers\SetupController; use App\Controllers\SetupController;
use App\Controllers\SiteSettingsController; use App\Controllers\SiteSettingsController;
use App\Controllers\TwoFactorController; use App\Controllers\TwoFactorController;
use App\Controllers\UpdateController;
use App\Controllers\UploadController; use App\Controllers\UploadController;
use App\Middleware\AuthMiddleware; use App\Middleware\AuthMiddleware;
use App\Router; use App\Router;
@ -188,6 +189,15 @@ $router->post('/settings/reset-all', $perm('settings.manage', fn($p) => Settings
$router->get('/settings/schema-check', $perm('settings.manage', fn($p) => SchemaController::check())); $router->get('/settings/schema-check', $perm('settings.manage', fn($p) => SchemaController::check()));
$router->post('/settings/schema-migrate', $perm('settings.manage', fn($p) => SchemaController::migrate())); $router->post('/settings/schema-migrate', $perm('settings.manage', fn($p) => SchemaController::migrate()));
// Git-Auto-Update: eigene, engere Berechtigung (ueberschreibt Live-Code) statt des
// breiteren settings.manage - siehe Kommentar bei Permissions::CATALOG['system.update'].
$router->get('/settings/update-status', $perm('system.update', fn($p) => UpdateController::status()));
$router->get('/settings/update-check', $perm('system.update', fn($p) => UpdateController::check()));
$router->post('/settings/update-download', $perm('system.update', fn($p) => UpdateController::download()));
$router->post('/settings/update-extract', $perm('system.update', fn($p) => UpdateController::extract()));
$router->post('/settings/update-backup', $perm('system.update', fn($p) => UpdateController::backup()));
$router->post('/settings/update-apply', $perm('system.update', fn($p) => UpdateController::apply()));
$router->get('/settings/database', $perm('settings.manage', fn($p) => DatabaseConfigController::show())); $router->get('/settings/database', $perm('settings.manage', fn($p) => DatabaseConfigController::show()));
$router->post('/settings/database', $perm('settings.manage', fn($p) => DatabaseConfigController::update())); $router->post('/settings/database', $perm('settings.manage', fn($p) => DatabaseConfigController::update()));

View file

@ -14,6 +14,20 @@ class SchemaController
} }
public static function migrate(): void public static function migrate(): void
{
$actions = self::runMigration();
Http::send(['ok' => true, 'actions' => $actions, 'report' => self::buildReport()]);
}
/**
* Der eigentliche additive Migrations-Lauf, losgeloest von Http::send()/exit - damit
* z.B. GitUpdateService das nach einem Auto-Update genauso aufrufen kann wie der
* "Datenbankstruktur aktualisieren"-Button, ohne die laufende Response zu beenden.
* Verhalten unveraendert gegenueber vorher, nur aus migrate() herausgezogen.
*
* @return string[]
*/
public static function runMigration(): array
{ {
$db = Database::connection(); $db = Database::connection();
$existingTables = self::existingTables($db); $existingTables = self::existingTables($db);
@ -44,7 +58,7 @@ class SchemaController
} }
} }
Http::send(['ok' => true, 'actions' => $actions, 'report' => self::buildReport()]); return $actions;
} }
private static function buildReport(): array private static function buildReport(): array

View file

@ -0,0 +1,95 @@
<?php
namespace App\Controllers;
use App\Services\GitUpdateService;
use App\Support\Http;
/**
* Dünner HTTP-Adapter über GitUpdateService - sechs unabhängige Schritte statt eines
* grossen Requests (siehe Kommentar in GitUpdateService.php). Berechtigungsprüfung
* passiert wie ueberall in diesem Projekt am Router ($perm(...) in index.php), nicht hier.
* Jeder schreibende Schritt laeuft ueber runStep(), das vor dem eigentlichen Aufruf "in
* Bearbeitung" vermerkt und einen Absturz mitten im Schritt (Server-Timeout o.ae.) als
* "fehlgeschlagen" statt "haengend" markiert, damit ein erneuter Klick sauber nachholt.
*/
class UpdateController
{
public static function status(): void
{
Http::send(GitUpdateService::status());
}
public static function check(): void
{
self::runStep('check', fn() => GitUpdateService::check());
}
public static function download(): void
{
$runId = self::newRunId();
self::runStep('download', fn() => array_merge(['run_id' => $runId], GitUpdateService::download($runId)));
}
public static function extract(): void
{
$runId = self::requireRunId();
self::runStep('extract', fn() => GitUpdateService::extract($runId));
}
public static function backup(): void
{
self::runStep('backup', fn() => GitUpdateService::backup());
}
public static function apply(): void
{
$runId = self::requireRunId();
self::runStep('apply', fn() => GitUpdateService::apply($runId));
}
private static function newRunId(): string
{
return date('Ymd_His') . '_' . bin2hex(random_bytes(4));
}
/** run_id kommt vom Client zurueck und landet in Dateipfaden - streng auf ein sicheres Format pruefen. */
private static function requireRunId(): string
{
$body = Http::jsonBody();
$runId = (string) ($body['run_id'] ?? '');
if ($runId === '' || !preg_match('/^[a-zA-Z0-9_]+$/', $runId)) {
Http::error('Ungültige oder fehlende run_id - bitte von vorn beginnen (Herunterladen).', 422);
}
return $runId;
}
private static function runStep(string $step, callable $fn): void
{
GitUpdateService::markStepInProgress($step);
register_shutdown_function(function () use ($step) {
$error = error_get_last();
if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
GitUpdateService::markStepFailed($step, $error['message'] ?? 'Unbekannter Fehler');
}
});
try {
$result = $fn();
} catch (\Throwable $e) {
GitUpdateService::markStepFailed($step, $e->getMessage());
Http::error('Schritt "' . $step . '" fehlgeschlagen: ' . $e->getMessage(), 500);
return;
}
if (($result['ok'] ?? true) === false) {
$message = (string) ($result['error'] ?? 'Unbekannter Fehler');
GitUpdateService::markStepFailed($step, $message);
Http::error($message, 500);
return;
}
Http::send($result);
}
}

View file

@ -0,0 +1,587 @@
<?php
namespace App\Services;
use App\Config\Database;
use App\Controllers\SchemaController;
/**
* Zieht den aktuellen Stand von main aus dem oeffentlichen Gitea-Repo per HTTPS-ZIP-Archiv
* (kein Git-Binary/exec()/shell_exec() noetig - funktioniert auch auf reinem Shared-PHP-
* Hosting ohne SSH) und spielt ihn ueber den Live-Baum. Bewusst als sechs unabhaengige,
* synchron aufgerufene Schritte (status/check/download/extract/backup/apply) statt eines
* grossen Requests oder eines echten Hintergrund-Jobs - dieses Projekt hat keine
* Job-Queue-Infrastruktur, und ein einzelner ~127-MB-Download+Entpacken+Sichern+Kopieren
* waere der wahrscheinlichste Weg, ein unbekanntes max_execution_time/Proxy-Timeout zu
* reissen. Jeder Schritt ist fuer sich wiederholbar (siehe UpdateController).
*
* Sicherheitskritisch: das Backup-ZIP enthaelt zwangslaeufig db.php (Datenbank-Zugangsdaten),
* liegt deshalb unter hifi/_update/ mit sofort geschriebener "alles verbieten"-.htaccess
* (siehe ensureProtectedDir()) UND hifi/_update/ ist in .gitignore, seit BEVOR dieser Code
* je eine erste Sicherung anlegen kann - beides zusammen verhindert, dass Zugangsdaten
* ueber die Weboberflaeche oder ins (oeffentliche!) Git-Repo gelangen.
*/
class GitUpdateService
{
private const GIT_HOST = 'git.maaxxs-coding.de';
private const REPO_OWNER = 'max.olchov';
private const REPO_NAME = 'HifiPlanet-Website';
private const BRANCH = 'main';
// Harte Obergrenze fuer den Archiv-Download, unabhaengig von einer Vorab-Schaetzung -
// zweite Verteidigungslinie, falls disk_free_space() aus irgendeinem Grund optimistisch war.
private const MAX_ARCHIVE_BYTES = 300 * 1024 * 1024;
private const KEEP_BACKUPS = 3;
// Darf beim Kopieren/Loeschen des Live-Baums NIE angefasst werden - Zugangsdaten,
// Kunden-Uploads, der eigene Zustand, sowie lokales Claude-Tooling/VCS-Metadaten.
// Haelt sich bewusst nicht automatisch mit .gitignore synchron (kein generischer
// Parser fuer eine so kurze, stabile Liste) - bei einem neuen gitignorten Pfad unter
// hifi/ auch hier ergaenzen.
private const APPLY_DENYLIST_FILES = [
'api/config/db.php',
'api/config/setup.php',
'api/config/ga-service-account.json',
'api/config/update-state.php',
'skills-lock.json',
];
private const APPLY_DENYLIST_PREFIXES = ['api/uploads/', '_update/', '.claude/', '.agents/', '.git/'];
// Das Backup ist ein Code-Rollback, keine allgemeine Datensicherung - Kunden-Uploads
// aendern sich nicht durch ein Code-Update und muessten sonst bei jedem Update erneut
// mitkopiert werden (unnoetig gross/langsam).
private const BACKUP_EXCLUDE_FILES = ['skills-lock.json'];
private const BACKUP_EXCLUDE_PREFIXES = ['_update/', '.claude/', '.agents/', 'api/uploads/', '.git/'];
private const STATE_FILE = __DIR__ . '/../../config/update-state.php';
public static function status(): array
{
$state = self::readState();
$liveRoot = self::liveRoot();
$free = @disk_free_space($liveRoot);
return [
'ok' => true,
'deployed_sha' => $state['deployed_sha'],
'deployed_at' => $state['deployed_at'],
'last_check' => $state['last_check'],
'latest_known_sha' => $state['latest_known_sha'],
'in_progress' => !empty($state['in_progress_since']),
'current_step' => $state['current_step'],
'last_error' => $state['last_error'],
'capabilities' => [
'zip' => class_exists('ZipArchive'),
'http_client' => function_exists('curl_init') || (bool) ini_get('allow_url_fopen'),
'writable' => is_writable($liveRoot),
'disk_free_mb' => $free !== false ? (int) round($free / 1024 / 1024) : null,
],
];
}
public static function check(): array
{
$url = 'https://' . self::GIT_HOST . '/api/v1/repos/' . self::REPO_OWNER . '/' . self::REPO_NAME . '/branches/' . self::BRANCH;
$json = self::httpGetJson($url);
if ($json === null || !isset($json['commit']['id'])) {
return ['ok' => false, 'error' => 'Update-Server nicht erreichbar oder unerwartete Antwort - konnte nicht prüfen, ob ein Update verfügbar ist.'];
}
$state = self::readState();
$latestSha = $json['commit']['id'];
$rawMessage = (string) ($json['commit']['message'] ?? '');
$latestMessage = trim(strtok($rawMessage, "\n")) ?: null;
$state['last_check'] = date('c');
$state['latest_known_sha'] = $latestSha;
self::writeState($state);
return [
'ok' => true,
'deployed_sha' => $state['deployed_sha'],
'latest_sha' => $latestSha,
'latest_message' => $latestMessage,
'latest_date' => $json['commit']['timestamp'] ?? null,
'update_available' => $state['deployed_sha'] !== $latestSha,
];
}
public static function download(string $runId): array
{
self::ensureProtectedDir(self::updateDir());
$stagingDir = self::updateDir() . '/staging/' . $runId;
self::deleteTree($stagingDir);
@mkdir($stagingDir, 0755, true);
$archivePath = $stagingDir . '/archive.zip';
$url = 'https://' . self::GIT_HOST . '/' . self::REPO_OWNER . '/' . self::REPO_NAME . '/archive/' . self::BRANCH . '.zip';
$fh = @fopen($archivePath, 'wb');
if (!$fh) {
return ['ok' => false, 'error' => 'Zieldatei für den Download konnte nicht angelegt werden (Schreibrechte prüfen).'];
}
$ceilingHit = false;
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 280);
curl_setopt($ch, CURLOPT_USERAGENT, 'HifiPlanet-AutoUpdate/1');
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function ($res, $expectedDown, $down) use (&$ceilingHit) {
if ($down > self::MAX_ARCHIVE_BYTES) {
$ceilingHit = true;
return 1; // ungleich 0 bricht den laufenden Transfer ab
}
return 0;
});
$ok = curl_exec($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fh);
if ($ceilingHit) {
@unlink($archivePath);
return ['ok' => false, 'error' => 'Download abgebrochen: Archiv überschreitet das Sicherheitslimit von ' . (int) (self::MAX_ARCHIVE_BYTES / 1024 / 1024) . ' MB.'];
}
if (!$ok || $httpCode !== 200) {
@unlink($archivePath);
return ['ok' => false, 'error' => "Download fehlgeschlagen (HTTP $httpCode)" . ($error ? ": $error" : '.')];
}
} elseif (ini_get('allow_url_fopen')) {
$context = stream_context_create(['http' => ['timeout' => 280, 'header' => "User-Agent: HifiPlanet-AutoUpdate/1\r\n"]]);
$in = @fopen($url, 'rb', false, $context);
if (!$in) {
fclose($fh);
return ['ok' => false, 'error' => 'Download fehlgeschlagen (Server nicht erreichbar).'];
}
$bytesWritten = 0;
while (!feof($in)) {
$chunk = fread($in, 256 * 1024);
if ($chunk === false) {
break;
}
fwrite($fh, $chunk);
$bytesWritten += strlen($chunk);
if ($bytesWritten > self::MAX_ARCHIVE_BYTES) {
$ceilingHit = true;
break;
}
}
fclose($in);
fclose($fh);
if ($ceilingHit) {
@unlink($archivePath);
return ['ok' => false, 'error' => 'Download abgebrochen: Archiv überschreitet das Sicherheitslimit von ' . (int) (self::MAX_ARCHIVE_BYTES / 1024 / 1024) . ' MB.'];
}
} else {
fclose($fh);
return ['ok' => false, 'error' => 'Weder curl noch allow_url_fopen verfügbar - Download nicht möglich.'];
}
if (!is_file($archivePath) || filesize($archivePath) === 0) {
return ['ok' => false, 'error' => 'Download lieferte eine leere Datei.'];
}
return ['ok' => true, 'bytes' => filesize($archivePath)];
}
public static function extract(string $runId): array
{
if (!class_exists('ZipArchive')) {
return ['ok' => false, 'error' => 'PHP-Erweiterung "zip" ist auf diesem Server nicht verfügbar.'];
}
$stagingDir = self::updateDir() . '/staging/' . $runId;
$archivePath = $stagingDir . '/archive.zip';
if (!is_file($archivePath)) {
return ['ok' => false, 'error' => 'Kein Download für diesen Lauf gefunden - bitte erneut herunterladen.'];
}
$extractedDir = $stagingDir . '/extracted';
self::deleteTree($extractedDir);
@mkdir($extractedDir, 0755, true);
$zip = new \ZipArchive();
if ($zip->open($archivePath) !== true) {
return ['ok' => false, 'error' => 'Archiv konnte nicht geöffnet werden (unvollständiger/beschädigter Download?).'];
}
// Gitea packt das Archiv mit einem Wrapper-Ordner (z.B. "HifiPlanet-Website-main/"),
// dessen genauer Name bewusst nicht angenommen wird, sondern aus dem ersten
// Eintrag abgeleitet wird.
$wrapperPrefix = null;
$extractedCount = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if ($name === false) {
continue;
}
if ($wrapperPrefix === null) {
$slash = strpos($name, '/');
$wrapperPrefix = $slash !== false ? substr($name, 0, $slash + 1) : '';
}
$needle = $wrapperPrefix . 'hifi/';
if (!str_starts_with($name, $needle)) {
continue; // hifi-src/, Doku etc. - fuer eine deployte Seite irrelevant
}
$relative = substr($name, strlen($needle));
if ($relative === '') {
continue; // der "hifi/"-Ordnereintrag selbst
}
$destPath = $extractedDir . '/' . $relative;
if (substr($name, -1) === '/') {
@mkdir($destPath, 0755, true);
continue;
}
@mkdir(dirname($destPath), 0755, true);
$stream = $zip->getStream($name);
if ($stream === false) {
continue;
}
$out = @fopen($destPath, 'wb');
if ($out) {
stream_copy_to_stream($stream, $out);
fclose($out);
$extractedCount++;
}
fclose($stream);
}
$zip->close();
if ($extractedCount === 0) {
return ['ok' => false, 'error' => 'Archiv enthielt keinen "hifi/"-Ordner - unerwartetes Format oder falscher Branch.'];
}
return ['ok' => true, 'files' => $extractedCount];
}
public static function backup(): array
{
$liveRoot = self::liveRoot();
self::ensureProtectedDir(self::updateDir());
$backupsDir = self::updateDir() . '/backups';
@mkdir($backupsDir, 0755, true);
if (!class_exists('ZipArchive')) {
return ['ok' => false, 'error' => 'PHP-Erweiterung "zip" ist auf diesem Server nicht verfügbar.'];
}
$filename = 'backup-' . date('Y-m-d_His') . '.zip';
$path = $backupsDir . '/' . $filename;
$zip = new \ZipArchive();
if ($zip->open($path, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
return ['ok' => false, 'error' => 'Backup-ZIP konnte nicht angelegt werden (Schreibrechte prüfen).'];
}
$noCompressExt = ['mp4', 'webm', 'png', 'jpg', 'jpeg', 'webp', 'zip', 'gz'];
$count = 0;
foreach (self::listFilesRelative($liveRoot) as $rel) {
if (self::isDenylisted($rel, self::BACKUP_EXCLUDE_FILES, self::BACKUP_EXCLUDE_PREFIXES)) {
continue;
}
$zip->addFile($liveRoot . '/' . $rel, $rel);
$ext = strtolower((string) pathinfo($rel, PATHINFO_EXTENSION));
if (in_array($ext, $noCompressExt, true)) {
$zip->setCompressionName($rel, \ZipArchive::CM_STORE);
}
$count++;
}
$zip->close();
self::pruneOldBackups($backupsDir);
return [
'ok' => true,
'filename' => $filename,
'size' => is_file($path) ? filesize($path) : 0,
'files' => $count,
];
}
public static function apply(string $runId): array
{
$extractedDir = self::updateDir() . '/staging/' . $runId . '/extracted';
if (!is_dir($extractedDir)) {
return ['ok' => false, 'error' => 'Kein entpacktes Update für diesen Lauf gefunden - bitte von vorn beginnen.'];
}
$liveRoot = self::liveRoot();
$log = [];
$previousMaintenance = null;
self::setMaintenanceMode(true, $previousMaintenance);
try {
// index.html wird bewusst von der allgemeinen Kopier-Runde ausgenommen und danach
// als letztes atomar getauscht (copy + rename) - so verweist es erst dann auf die
// neuen, gehashten JS/CSS-Dateinamen, wenn diese schon vollstaendig kopiert sind.
$denylistFiles = array_merge(self::APPLY_DENYLIST_FILES, ['index.html']);
$log = array_merge($log, self::copyAndPrune($extractedDir, $liveRoot, $denylistFiles, self::APPLY_DENYLIST_PREFIXES));
$newIndexHtml = $extractedDir . '/index.html';
if (is_file($newIndexHtml)) {
$tmp = $liveRoot . '/index.html.new';
if (@copy($newIndexHtml, $tmp) && @rename($tmp, $liveRoot . '/index.html')) {
$log[] = 'index.html aktualisiert';
} else {
$log[] = 'FEHLER beim Aktualisieren von index.html';
}
}
$log = array_merge($log, SchemaController::runMigration());
} finally {
self::setMaintenanceMode(false, $previousMaintenance);
}
self::deleteTree(self::updateDir() . '/staging/' . $runId);
$state = self::readState();
$state['deployed_sha'] = $state['latest_known_sha'] ?? $state['deployed_sha'];
$state['deployed_at'] = date('c');
$state['in_progress_since'] = null;
$state['current_step'] = null;
$state['last_error'] = null;
self::writeState($state);
return ['ok' => true, 'log' => $log];
}
// ---- Zustand (hifi/api/config/update-state.php, gitignored) ----
public static function readState(): array
{
$state = is_file(self::STATE_FILE) ? require self::STATE_FILE : [];
return array_merge(self::defaultState(), is_array($state) ? $state : []);
}
public static function writeState(array $state): void
{
@mkdir(dirname(self::STATE_FILE), 0755, true);
$content = "<?php\n\n// Wird vom Auto-Update-Feature automatisch geschrieben (siehe GitUpdateService).\nreturn "
. var_export($state, true) . ";\n";
file_put_contents(self::STATE_FILE, $content);
}
public static function markStepInProgress(string $step): void
{
$state = self::readState();
$state['in_progress_since'] = $state['in_progress_since'] ?: date('c');
$state['current_step'] = $step;
$state['last_error'] = null;
self::writeState($state);
}
public static function markStepFailed(string $step, string $message): void
{
$state = self::readState();
$state['current_step'] = $step . ' (fehlgeschlagen)';
$state['last_error'] = $message;
self::writeState($state);
}
private static function defaultState(): array
{
return [
'deployed_sha' => null,
'deployed_at' => null,
'last_check' => null,
'latest_known_sha' => null,
'in_progress_since' => null,
'current_step' => null,
'last_error' => null,
];
}
// ---- HTTP ----
private static function httpGetJson(string $url): ?array
{
$body = self::httpGet($url);
if ($body === null) {
return null;
}
$json = json_decode($body, true);
return is_array($json) ? $json : null;
}
private static function httpGet(string $url): ?string
{
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'HifiPlanet-AutoUpdate/1');
$body = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($body !== false && $httpCode === 200) ? $body : null;
}
if (ini_get('allow_url_fopen')) {
$context = stream_context_create(['http' => ['timeout' => 15, 'header' => "User-Agent: HifiPlanet-AutoUpdate/1\r\n"]]);
$body = @file_get_contents($url, false, $context);
return $body !== false ? $body : null;
}
return null;
}
// ---- Dateisystem-Hilfsfunktionen ----
private static function liveRoot(): string
{
// hifi/api/src/Services -> hifi/
return rtrim((string) realpath(__DIR__ . '/../../..'), '/\\');
}
private static function updateDir(): string
{
return self::liveRoot() . '/_update';
}
/** Legt $dir an (falls noetig) und schreibt sofort eine "alles verbieten"-.htaccess hinein. */
private static function ensureProtectedDir(string $dir): void
{
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}
$htaccess = $dir . '/.htaccess';
if (!is_file($htaccess)) {
@file_put_contents($htaccess, "Require all denied\n");
}
}
private static function setMaintenanceMode(bool $enabled, ?array &$previous): void
{
try {
$db = Database::connection();
$db->exec('INSERT IGNORE INTO app_settings (id) VALUES (1)');
if ($enabled) {
$stmt = $db->query('SELECT maintenance_global, maintenance_global_message FROM app_settings WHERE id = 1');
$previous = $stmt->fetch() ?: ['maintenance_global' => 0, 'maintenance_global_message' => null];
$upd = $db->prepare('UPDATE app_settings SET maintenance_global = 1, maintenance_global_message = ? WHERE id = 1');
$upd->execute(['Wir aktualisieren die Seite gerade und sind gleich zurück.']);
} else {
$restore = $previous ?: ['maintenance_global' => 0, 'maintenance_global_message' => null];
$upd = $db->prepare('UPDATE app_settings SET maintenance_global = ?, maintenance_global_message = ? WHERE id = 1');
$upd->execute([(int) $restore['maintenance_global'], $restore['maintenance_global_message']]);
}
} catch (\Throwable $e) {
// Wartungsmodus ist ein Komfort-Feature fuer die Dauer des Updates - ein Fehler
// hier (z.B. DB kurz nicht erreichbar) soll das eigentliche Update nicht verhindern.
}
}
/**
* Kopiert alles aus $srcDir nach $destDir und loescht danach in $destDir alles, was in
* $srcDir kein Gegenstueck (mehr) hat - noetig, weil Vite bei jedem Build neue Hash-
* Dateinamen vergibt (siehe hifi-src/package.json prebuild-Skript, das lokal genau
* deshalb hifi/assets/ vorher leert), sonst sammeln sich alte JS/CSS-Chunks im
* Live-Baum an. $denylistFiles/$denylistPrefixes (relativ zu $destDir) werden in
* beiden Richtungen ausgenommen - kann strukturell eigentlich nie greifen, da diese
* Pfade nie im Git-Archiv liegen, bleibt aber als billige Absicherung im Code stehen.
*
* @return string[]
*/
private static function copyAndPrune(string $srcDir, string $destDir, array $denylistFiles, array $denylistPrefixes): array
{
$log = [];
@mkdir($destDir, 0755, true);
$srcFiles = self::listFilesRelative($srcDir);
foreach ($srcFiles as $rel) {
if (self::isDenylisted($rel, $denylistFiles, $denylistPrefixes)) {
continue;
}
$destPath = $destDir . '/' . $rel;
@mkdir(dirname($destPath), 0755, true);
if (!@copy($srcDir . '/' . $rel, $destPath)) {
$log[] = "FEHLER beim Kopieren von $rel";
}
}
$destFiles = self::listFilesRelative($destDir);
$srcFileSet = array_flip($srcFiles);
foreach ($destFiles as $rel) {
if (self::isDenylisted($rel, $denylistFiles, $denylistPrefixes)) {
continue;
}
if (!isset($srcFileSet[$rel])) {
@unlink($destDir . '/' . $rel);
$log[] = "Entfernt (nicht mehr im Update enthalten): $rel";
}
}
return $log;
}
private static function isDenylisted(string $rel, array $files, array $prefixes): bool
{
if (in_array($rel, $files, true)) {
return true;
}
foreach ($prefixes as $prefix) {
if (str_starts_with($rel, $prefix)) {
return true;
}
}
return false;
}
/** @return string[] Relative Pfade (immer mit "/"), nur Dateien, keine Verzeichnisse. */
private static function listFilesRelative(string $root): array
{
$root = rtrim($root, '/\\');
if (!is_dir($root)) {
return [];
}
$files = [];
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $fileInfo) {
if ($fileInfo->isFile()) {
$rel = substr($fileInfo->getPathname(), strlen($root) + 1);
$files[] = str_replace('\\', '/', $rel);
}
}
return $files;
}
private static function deleteTree(string $dir): void
{
if (!is_dir($dir)) {
return;
}
$items = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($items as $item) {
if ($item->isDir()) {
@rmdir($item->getPathname());
} else {
@unlink($item->getPathname());
}
}
@rmdir($dir);
}
private static function pruneOldBackups(string $backupsDir): void
{
$files = glob($backupsDir . '/backup-*.zip') ?: [];
usort($files, fn($a, $b) => filemtime($b) <=> filemtime($a));
foreach (array_slice($files, self::KEEP_BACKUPS) as $old) {
@unlink($old);
}
}
}

View file

@ -17,6 +17,7 @@ class Permissions
'permission_groups.manage' => 'Berechtigungsgruppen verwalten', 'permission_groups.manage' => 'Berechtigungsgruppen verwalten',
'settings.manage' => 'Systemeinstellungen (Export/Import/Zurücksetzen) verwalten', 'settings.manage' => 'Systemeinstellungen (Export/Import/Zurücksetzen) verwalten',
'maintenance.bypass' => 'Wartungsmodus umgehen (Inhalte trotzdem sehen)', 'maintenance.bypass' => 'Wartungsmodus umgehen (Inhalte trotzdem sehen)',
'system.update' => 'Updates aus Git prüfen & installieren (überschreibt Live-Code)',
]; ];
public static function isValid(string $permission): bool public static function isValid(string $permission): bool

File diff suppressed because one or more lines are too long

View file

@ -43,7 +43,7 @@
"sameAs": ["https://www.youtube.com/@hifiplanet2812"] "sameAs": ["https://www.youtube.com/@hifiplanet2812"]
} }
</script> </script>
<script type="module" crossorigin src="/assets/index-C8YANYNU.js"></script> <script type="module" crossorigin src="/assets/index-DMjv3wnD.js"></script>
<link rel="modulepreload" crossorigin href="/assets/lucide-icons-Cg2IxtAO.js"> <link rel="modulepreload" crossorigin href="/assets/lucide-icons-Cg2IxtAO.js">
<link rel="stylesheet" crossorigin href="/assets/index-DHi-eHhm.css"> <link rel="stylesheet" crossorigin href="/assets/index-DHi-eHhm.css">
</head> </head>