Backoffice: PHP admin web UI for licenses, versions, audit

Self-contained admin under /PS_Launcher/admin/ on the same OVH host. No
JS framework, no Composer deps — just PHP 8.3 + sessions + a small CSS.

Auth & infrastructure
---------------------
- admin/lib/Auth.php: session + CSRF helper. Login via password_hash /
  password_verify. session_regenerate_id on successful login.
  config.example.php gains admin_password_hash, generated by:
  php -r "echo password_hash('PWD', PASSWORD_DEFAULT);"
- admin/lib/Layout.php: shared header/footer/nav, formatBytes,
  csrfField helpers.
- admin/.htaccess: noindex / X-Frame-Options DENY / X-Content-Type
  nosniff / blocks lib/*.php from web access.
- admin/assets/style.css: matches launcher's dark theme — same
  Brush.* palette mapped to CSS vars, vivid green/blue/amber status
  pills consistent with the WPF UI.

Pages
-----
- index.php (Dashboard): KPIs (active/expired/revoked licenses, machines
  seen 30d, validations 24h), manifest signature status, last 10
  audit_log entries.
- licenses.php: full CRUD.
  * Émettre: owner, expiration date, max machines, internal notes →
    generates a PRSRV-XXXX-XXXX-XXXX-XXXX key, displays it ONCE in a
    green callout (DB stores the key; the message stays only on this
    request, never shown again).
  * Prolonger (per-row, expandable form), Revoke / Unrevoke,
    Reset machines (frees all slots for that license).
  * Status badge: active / expired / revoked.
- versions.php: edit the manifest from the web.
  * Add a version: number + release date + minLicenseDate + release
    notes Markdown (creates releasenotes/{version}.md). Sets default
    download URL to {base_url}/builds/proserve-{version}.zip.
  * Per-row Méta (edit minLicenseDate / releasedAt), Notes (edit md
    inline), toggle availableForDownload, Delete entry.
  * 🔁 Sync (sign-manifest) button: shells out to
    `php tools/sign-manifest.php` and shows its stdout — recomputes
    sha256/sizeBytes for every uploaded ZIP, bumps `latest`, signs
    Ed25519. Visual indicators on each row: zip presence, hash
    computed yes/no, signature status.
  * Lists orphan ZIPs in builds/ that no manifest entry references.
- audit.php: paginated audit_log viewer (100/page) with event-type
  filter dropdown. JOINs licenses to show owner_name. Color-codes
  events (validate_ok green, expired amber, invalid/revoked red).

Server README rewritten to document the full setup flow:
1. Create MySQL DB, run migrations/001_init.sql
2. Copy config.example.php → config.php, fill db credentials
3. php tools/generate-keypair.php → paste into config.php and into the
   client's Resources/server-pubkey.txt
4. Set admin_password_hash in config.php
5. Login at /PS_Launcher/admin/

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-01 10:21:52 +02:00
parent 7a29dbb049
commit 92f4fd16e8
12 changed files with 1250 additions and 43 deletions

213
server/admin/licenses.php Normal file
View File

@@ -0,0 +1,213 @@
<?php
declare(strict_types=1);
require __DIR__ . '/lib/Auth.php';
require __DIR__ . '/lib/Layout.php';
require __DIR__ . '/../api/lib/Db.php';
use PSLauncher\Admin\Auth;
use PSLauncher\Admin\Layout;
use PSLauncher\Db;
Auth::requireLogin();
$config = require __DIR__ . '/../api/config.php';
$db = Db::get($config);
$message = null; $messageType = 'success';
$newKey = null;
function generateLicenseKey(): string
{
$alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$groups = [];
for ($g = 0; $g < 4; $g++) {
$s = '';
for ($i = 0; $i < 4; $i++) $s .= $alphabet[random_int(0, strlen($alphabet) - 1)];
$groups[] = $s;
}
return 'PRSRV-' . implode('-', $groups);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
Auth::checkCsrf();
$action = $_POST['action'] ?? '';
try {
if ($action === 'create') {
$owner = trim($_POST['owner'] ?? '');
$until = trim($_POST['until'] ?? '');
$maxMachines = max(1, (int)($_POST['max_machines'] ?? 1));
$notes = trim($_POST['notes'] ?? '') ?: null;
if ($owner === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $until)) {
throw new Exception('Nom du client et date d\'expiration sont requis (date au format YYYY-MM-DD).');
}
for ($attempts = 0; $attempts < 5; $attempts++) {
$newKey = generateLicenseKey();
try {
$db->prepare('INSERT INTO licenses (license_key, owner_name, issued_at, download_entitlement_until, max_machines, notes) VALUES (?, ?, NOW(), ?, ?, ?)')
->execute([$newKey, $owner, $until . ' 23:59:59', $maxMachines, $notes]);
$message = "License émise avec succès. Note la clé maintenant — elle ne sera plus jamais affichée.";
break;
} catch (PDOException $e) {
if (str_contains($e->getMessage(), 'Duplicate')) { continue; }
throw $e;
}
}
}
elseif ($action === 'revoke') {
$id = (int)($_POST['id'] ?? 0);
$db->prepare('UPDATE licenses SET revoked_at = NOW() WHERE id = ?')->execute([$id]);
$message = "License #{$id} révoquée.";
}
elseif ($action === 'unrevoke') {
$id = (int)($_POST['id'] ?? 0);
$db->prepare('UPDATE licenses SET revoked_at = NULL WHERE id = ?')->execute([$id]);
$message = "License #{$id} réactivée.";
}
elseif ($action === 'extend') {
$id = (int)($_POST['id'] ?? 0);
$newUntil = trim($_POST['new_until'] ?? '');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $newUntil)) {
throw new Exception('Date invalide.');
}
$db->prepare('UPDATE licenses SET download_entitlement_until = ? WHERE id = ?')
->execute([$newUntil . ' 23:59:59', $id]);
$message = "License #{$id} prolongée jusqu'au {$newUntil}.";
}
elseif ($action === 'reset_machines') {
$id = (int)($_POST['id'] ?? 0);
$db->prepare('DELETE FROM license_machines WHERE license_id = ?')->execute([$id]);
$message = "Machines libérées pour la license #{$id}.";
}
} catch (Exception $e) {
$message = $e->getMessage();
$messageType = 'error';
}
}
$licenses = $db->query(
'SELECT l.*,
(SELECT COUNT(*) FROM license_machines m WHERE m.license_id = l.id) AS machines_count
FROM licenses l
ORDER BY l.id DESC'
)->fetchAll();
Layout::header('Licenses', 'licenses');
?>
<h1>Licenses</h1>
<?php Layout::flash($message, $messageType); ?>
<?php if ($newKey): ?>
<div class="card" style="border-color: var(--installed); background: var(--installed-bg);">
<h2 style="color: #6EE7B7; margin-top:0">⚡ Nouvelle clé — copie-la dès maintenant</h2>
<pre style="font-size: 18px; font-weight: bold; color: white; background: rgba(0,0,0,0.3); margin: 0;"><?= htmlspecialchars($newKey) ?></pre>
<p class="muted" style="margin-bottom: 0; margin-top: 12px;">Elle est stockée hashée — la prochaine fois que tu rechargeras cette page elle ne sera plus visible.</p>
</div>
<?php endif; ?>
<div class="card">
<h2>Émettre une license</h2>
<form method="post">
<?= Layout::csrfField() ?>
<input type="hidden" name="action" value="create">
<div class="row">
<div class="col field">
<label>Nom du client</label>
<input type="text" name="owner" required placeholder="ACME Corp">
</div>
<div class="col field">
<label>Date d'expiration des téléchargements</label>
<input type="date" name="until" required>
</div>
<div class="col field" style="flex: 0 0 140px">
<label>Max machines</label>
<input type="number" name="max_machines" value="1" min="1" max="100">
</div>
</div>
<div class="field">
<label>Notes internes (optionnel)</label>
<input type="text" name="notes" placeholder="Contact : jean@acme.com">
</div>
<button class="btn btn-success" type="submit">Émettre la license</button>
</form>
</div>
<div class="card">
<table>
<thead>
<tr>
<th>ID</th>
<th>Client</th>
<th>Émise</th>
<th>Expire</th>
<th>Machines</th>
<th>Statut</th>
<th style="text-align:right">Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($licenses as $l):
$isExpired = strtotime($l['download_entitlement_until']) < time();
$isRevoked = $l['revoked_at'] !== null;
if ($isRevoked) { $status = 'révoquée'; $cls = 'badge-danger'; }
elseif ($isExpired) { $status = 'expirée'; $cls = 'badge-warning'; }
else { $status = 'active'; $cls = 'badge-success'; }
?>
<tr>
<td>#<?= $l['id'] ?></td>
<td>
<strong><?= htmlspecialchars($l['owner_name']) ?></strong>
<?php if (!empty($l['notes'])): ?>
<div class="muted" style="font-size: 11px;"><?= htmlspecialchars($l['notes']) ?></div>
<?php endif; ?>
</td>
<td class="muted"><?= date('d/m/Y', strtotime($l['issued_at'])) ?></td>
<td><?= date('d/m/Y', strtotime($l['download_entitlement_until'])) ?></td>
<td><?= $l['machines_count'] ?> / <?= $l['max_machines'] ?></td>
<td><span class="badge <?= $cls ?>"><?= $status ?></span></td>
<td style="text-align:right; white-space: nowrap;">
<details style="display: inline-block; margin: 0 4px;">
<summary class="btn btn-secondary">Prolonger</summary>
<form method="post" style="margin-top: 8px; display: flex; gap: 4px; align-items: center;">
<?= Layout::csrfField() ?>
<input type="hidden" name="action" value="extend">
<input type="hidden" name="id" value="<?= $l['id'] ?>">
<input type="date" name="new_until" required style="width: 150px;">
<button class="btn btn-primary" type="submit">OK</button>
</form>
</details>
<?php if ($l['machines_count'] > 0): ?>
<form method="post" style="display:inline" onsubmit="return confirm('Libérer toutes les machines de cette license ?')">
<?= Layout::csrfField() ?>
<input type="hidden" name="action" value="reset_machines">
<input type="hidden" name="id" value="<?= $l['id'] ?>">
<button class="btn btn-secondary" type="submit" title="Libère les slots machines occupés">Libérer machines</button>
</form>
<?php endif; ?>
<?php if (!$isRevoked): ?>
<form method="post" style="display:inline" onsubmit="return confirm('Révoquer définitivement cette license ?')">
<?= Layout::csrfField() ?>
<input type="hidden" name="action" value="revoke">
<input type="hidden" name="id" value="<?= $l['id'] ?>">
<button class="btn btn-danger" type="submit">Révoquer</button>
</form>
<?php else: ?>
<form method="post" style="display:inline">
<?= Layout::csrfField() ?>
<input type="hidden" name="action" value="unrevoke">
<input type="hidden" name="id" value="<?= $l['id'] ?>">
<button class="btn btn-secondary" type="submit">Réactiver</button>
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
<?php if (empty($licenses)): ?>
<tr><td colspan="7" class="muted" style="text-align:center; padding: 32px;">Aucune license émise.</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
<?php Layout::footer();