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:
132
server/README.md
132
server/README.md
@@ -8,59 +8,111 @@ Contenu de ce dossier à uploader **sous `www/PS_Launcher/`** sur le mutualisé
|
||||
www/
|
||||
└── PS_Launcher/
|
||||
├── .htaccess
|
||||
├── api/
|
||||
│ ├── config.php ← À ÉDITER avec tes vraies valeurs (DB, secrets)
|
||||
├── api/ ← API consommée par le launcher
|
||||
│ ├── config.php ← À CRÉER (copie de config.example.php)
|
||||
│ ├── index.php
|
||||
│ ├── lib/Response.php
|
||||
│ └── routes/
|
||||
│ ├── Manifest.php
|
||||
│ └── Releasenotes.php
|
||||
├── manifest/
|
||||
│ └── versions.json ← Régénéré par tools/sign-manifest.php
|
||||
├── releasenotes/
|
||||
│ ├── 1.4.5.md
|
||||
│ └── 1.4.6.md
|
||||
├── builds/ ← Tu uploades ici les ZIPs en SFTP
|
||||
│ └── proserve-1.4.6.zip
|
||||
│ ├── lib/{Response,Db,Crypto}.php
|
||||
│ └── routes/{Manifest,Releasenotes,ValidateLicense}.php
|
||||
├── admin/ ← Backoffice web (auth par mot de passe)
|
||||
│ ├── .htaccess
|
||||
│ ├── index.php (dashboard)
|
||||
│ ├── login.php / logout.php
|
||||
│ ├── licenses.php / versions.php / audit.php
|
||||
│ ├── lib/{Auth,Layout}.php
|
||||
│ └── assets/style.css
|
||||
├── manifest/versions.json
|
||||
├── releasenotes/1.4.X.md
|
||||
├── builds/ ← ZIPs uploadés en SFTP
|
||||
├── migrations/001_init.sql ← Schéma MySQL initial
|
||||
└── tools/
|
||||
└── sign-manifest.php ← Lance après chaque upload de ZIP
|
||||
├── generate-keypair.php
|
||||
├── issue-license.php
|
||||
└── sign-manifest.php
|
||||
```
|
||||
|
||||
## Workflow de release
|
||||
## Setup initial (à faire une fois)
|
||||
|
||||
1. Packager Unreal → produit le dossier `Proserve v1.4.6/`.
|
||||
2. Le zipper localement : le contenu du ZIP doit reproduire ce qui est attendu côté client (le client extrait dans `Proserve v1.4.6/`, donc le ZIP peut soit contenir un dossier racine `Proserve v1.4.6/`, soit son contenu directement — voir ci-dessous).
|
||||
3. Uploader le ZIP via SFTP dans `www/PS_Launcher/builds/proserve-1.4.6.zip`.
|
||||
4. Éditer `manifest/versions.json` pour ajouter (ou modifier) l'entrée `1.4.6` et le champ `latest`.
|
||||
5. Ajouter `releasenotes/1.4.6.md`.
|
||||
6. Se connecter en SSH OVH et lancer :
|
||||
### 1. Crée la base MySQL
|
||||
Manager OVH → Hébergements → Bases de données → Créer. Note le DSN, user, password.
|
||||
|
||||
### 2. Joue le schéma
|
||||
PhpMyAdmin (manager OVH) ou en SSH :
|
||||
```bash
|
||||
mysql -h <host> -u <user> -p <db> < www/PS_Launcher/migrations/001_init.sql
|
||||
```
|
||||
cd www/PS_Launcher
|
||||
|
||||
### 3. Configure le serveur
|
||||
- Copie `api/config.example.php` → `api/config.php`
|
||||
- Remplis la section `db`, `base_url`
|
||||
- Génère les clés Ed25519 :
|
||||
```bash
|
||||
cd ~/www/PS_Launcher
|
||||
php tools/generate-keypair.php
|
||||
```
|
||||
Recopie `private_key_hex` et `public_key_hex` dans `api/config.php` section `ed25519`.
|
||||
Recopie aussi `public_key_hex` dans `src/PSLauncher.Core/Resources/server-pubkey.txt` côté projet C# et recompile le launcher.
|
||||
|
||||
### 4. Configure le mot de passe admin
|
||||
```bash
|
||||
php -r "echo password_hash('TonMotDePasseFort', PASSWORD_DEFAULT);"
|
||||
```
|
||||
Recopie le hash dans `api/config.php` → `admin_password_hash`.
|
||||
|
||||
### 5. Test la chaîne
|
||||
```
|
||||
https://tondomaine.com/PS_Launcher/api/health → JSON status: ok
|
||||
https://tondomaine.com/PS_Launcher/admin/login.php → page de connexion admin
|
||||
```
|
||||
|
||||
## Workflow de release (via le backoffice)
|
||||
|
||||
1. Connecte-toi sur `https://tondomaine.com/PS_Launcher/admin/`.
|
||||
2. Onglet **Versions** → formulaire « Ajouter une version » : numéro, date min de license, release notes Markdown.
|
||||
3. Upload le ZIP correspondant via SFTP dans `www/PS_Launcher/builds/proserve-{version}.zip`.
|
||||
4. Bouton **🔁 Sync (sign-manifest)** : calcule SHA-256, met à jour `latest`, signe le manifest avec Ed25519.
|
||||
5. Au prochain « Vérifier les MAJ » côté launcher, la nouvelle version apparaît.
|
||||
|
||||
## Workflow de release (alternative manuelle SSH)
|
||||
|
||||
```bash
|
||||
# 1. Édite manifest/versions.json (ou utilise le backoffice)
|
||||
# 2. Upload le ZIP en SFTP dans builds/
|
||||
# 3. Resigne :
|
||||
cd ~/www/PS_Launcher
|
||||
php tools/sign-manifest.php
|
||||
```
|
||||
Cela calcule automatiquement `sizeBytes` et `sha256` à partir du ZIP.
|
||||
|
||||
## Émettre une license
|
||||
|
||||
**Via le backoffice** (recommandé) : onglet **Licenses** → formulaire « Émettre ». La clé apparaît une seule fois — copie-la pour le client.
|
||||
|
||||
**Via SSH** :
|
||||
```bash
|
||||
php tools/issue-license.php "ACME Corp" 2027-12-31 1
|
||||
```
|
||||
|
||||
## Convention du contenu du ZIP
|
||||
|
||||
Le client extrait le ZIP dans `installRoot/Proserve v{version}/`. Donc le ZIP doit contenir **directement** les fichiers `PROSERVE_UE_5_5.exe`, `Engine/`, `PROSERVE_UE_5_5/`, etc. à sa racine (pas de dossier englobant).
|
||||
Le client extrait le ZIP dans `installRoot/Proserve v{version}/`. Le ZIP peut soit contenir
|
||||
un dossier racine `Proserve v{version}/`, soit le contenu directement — le launcher détecte
|
||||
automatiquement le préfixe commun et le strippe.
|
||||
|
||||
Test rapide en ligne de commande :
|
||||
```
|
||||
unzip -l proserve-1.4.6.zip | head -10
|
||||
```
|
||||
Doit lister `PROSERVE_UE_5_5.exe` à la racine, pas `Proserve v1.4.6/PROSERVE_UE_5_5.exe`.
|
||||
## Test API depuis ton poste
|
||||
|
||||
## Test de l'API depuis ton poste
|
||||
|
||||
Une fois uploadé, vérifier :
|
||||
|
||||
```
|
||||
curl https://www.tondomaine.com/PS_Launcher/api/health
|
||||
curl https://www.tondomaine.com/PS_Launcher/api/manifest
|
||||
curl https://www.tondomaine.com/PS_Launcher/api/releasenotes/1.4.6
|
||||
```powershell
|
||||
curl.exe https://tondomaine.com/PS_Launcher/api/health
|
||||
curl.exe https://tondomaine.com/PS_Launcher/api/manifest
|
||||
curl.exe https://tondomaine.com/PS_Launcher/api/releasenotes/1.4.6
|
||||
```
|
||||
|
||||
## À mettre à jour avant prod
|
||||
## Sécurité
|
||||
|
||||
- `api/config.php` : tous les `replace_me` / `replace_with_*`. Ce fichier ne doit JAMAIS être commit dans un repo public.
|
||||
- Dans `manifest/versions.json`, remplace `www.exemple-asterion.com` par ton vrai domaine.
|
||||
- `api/config.php` est gitignored. Ne jamais le commit.
|
||||
- Toutes les URLs `/api/*` forcent HTTPS via `.htaccess`.
|
||||
- Les routes /api/* renvoient toujours du JSON (pas de page Apache 500 HTML).
|
||||
- L'admin est protégé par session + CSRF + mot de passe bcrypt.
|
||||
- Les licenses sont stockées via UNIQUE en clair (pour la lookup constant-time côté serveur),
|
||||
mais ne sont jamais loguées en clair côté audit.
|
||||
- Côté client : la clé license est chiffrée DPAPI scope CurrentUser dans `%LocalAppData%`.
|
||||
- Les réponses serveur (manifest, validation license) sont signées Ed25519 — le launcher
|
||||
embarque la clé publique et refuse toute réponse mal signée.
|
||||
|
||||
12
server/admin/.htaccess
Normal file
12
server/admin/.htaccess
Normal file
@@ -0,0 +1,12 @@
|
||||
# Pas indexé par les moteurs
|
||||
<IfModule mod_headers.c>
|
||||
Header set X-Robots-Tag "noindex, nofollow, noarchive"
|
||||
Header set X-Frame-Options "DENY"
|
||||
Header set X-Content-Type-Options "nosniff"
|
||||
Header set Referrer-Policy "no-referrer"
|
||||
</IfModule>
|
||||
|
||||
# Bloquer l'accès direct aux libs
|
||||
<FilesMatch "^lib/.*\.php$">
|
||||
Require all denied
|
||||
</FilesMatch>
|
||||
132
server/admin/assets/style.css
Normal file
132
server/admin/assets/style.css
Normal file
@@ -0,0 +1,132 @@
|
||||
:root {
|
||||
--bg: #1B1B1F;
|
||||
--bg-card: #26262B;
|
||||
--bg-elevated: #2C2C32;
|
||||
--bg-input: #1A1A20;
|
||||
--border: #37373D;
|
||||
--text: #F2F2F2;
|
||||
--text-secondary: #A0A0A8;
|
||||
--accent: #3B82F6;
|
||||
--accent-hover: #2563EB;
|
||||
--installed: #16A34A;
|
||||
--installed-bg: #0E2A1B;
|
||||
--busy: #F59E0B;
|
||||
--busy-bg: #3A2A0E;
|
||||
--danger: #EF4444;
|
||||
--danger-bg: #2A1414;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
background: var(--bg); color: var(--text);
|
||||
font-family: 'Segoe UI', Roboto, system-ui, sans-serif;
|
||||
font-size: 14px; line-height: 1.5;
|
||||
margin: 0;
|
||||
}
|
||||
nav {
|
||||
background: #202024; border-bottom: 1px solid var(--border);
|
||||
padding: 12px 24px; display: flex; gap: 8px; align-items: center;
|
||||
}
|
||||
nav .brand { color: #fff; font-weight: 700; margin-right: 16px; }
|
||||
nav a {
|
||||
color: var(--text-secondary); text-decoration: none;
|
||||
padding: 6px 14px; border-radius: 4px; font-size: 13px;
|
||||
}
|
||||
nav a:hover { background: var(--bg-elevated); color: var(--text); }
|
||||
nav a.active { background: var(--bg-elevated); color: var(--text); }
|
||||
nav .spacer { flex: 1; }
|
||||
nav a.logout { color: var(--text-secondary); }
|
||||
|
||||
main { padding: 24px; max-width: 1200px; margin: 0 auto; }
|
||||
|
||||
h1 { margin: 0 0 24px 0; font-size: 26px; font-weight: 600; }
|
||||
h2 {
|
||||
margin: 0 0 12px 0; font-size: 12px; font-weight: 700;
|
||||
color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--bg-card); border: 1px solid var(--border);
|
||||
border-radius: 6px; padding: 20px; margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.row { display: flex; gap: 16px; flex-wrap: wrap; }
|
||||
.row .col { flex: 1; min-width: 200px; }
|
||||
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th {
|
||||
text-align: left; color: var(--text-secondary); font-size: 11px;
|
||||
text-transform: uppercase; letter-spacing: 0.5px;
|
||||
padding: 10px 8px; border-bottom: 1px solid var(--border);
|
||||
font-weight: 600;
|
||||
}
|
||||
td { padding: 12px 8px; border-bottom: 1px solid var(--border); vertical-align: middle; }
|
||||
tr:last-child td { border-bottom: none; }
|
||||
tr:hover td { background: var(--bg-elevated); }
|
||||
|
||||
.btn {
|
||||
display: inline-block; padding: 8px 16px;
|
||||
border-radius: 4px; border: none; cursor: pointer;
|
||||
font-size: 13px; font-family: inherit; text-decoration: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
.btn-primary { background: var(--accent); color: white; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-success { background: var(--installed); color: white; }
|
||||
.btn-danger { background: var(--danger); color: white; }
|
||||
.btn-secondary { background: var(--bg-elevated); color: var(--text); }
|
||||
.btn-secondary:hover { background: #3A3A40; }
|
||||
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
input[type=text], input[type=password], input[type=date], input[type=datetime-local],
|
||||
input[type=number], select, textarea {
|
||||
background: var(--bg-input); color: var(--text);
|
||||
border: 1px solid var(--border); padding: 8px 10px;
|
||||
border-radius: 4px; font-family: inherit; font-size: 13px;
|
||||
width: 100%;
|
||||
}
|
||||
input:focus, textarea:focus, select:focus {
|
||||
outline: none; border-color: var(--accent);
|
||||
}
|
||||
label { display: block; margin-bottom: 4px; font-size: 12px; color: var(--text-secondary); font-weight: 500; }
|
||||
.field { margin-bottom: 16px; }
|
||||
.field input[type=checkbox] { width: auto; margin-right: 8px; }
|
||||
|
||||
.flash { padding: 12px 16px; border-radius: 4px; margin-bottom: 16px; }
|
||||
.flash.error { background: var(--danger-bg); color: #FCA5A5; border: 1px solid var(--danger); }
|
||||
.flash.success { background: var(--installed-bg); color: #6EE7B7; border: 1px solid var(--installed); }
|
||||
|
||||
.badge {
|
||||
display: inline-block; padding: 2px 8px; border-radius: 10px;
|
||||
font-size: 11px; font-weight: 600; color: white; line-height: 1.5;
|
||||
}
|
||||
.badge-success { background: var(--installed); }
|
||||
.badge-danger { background: var(--danger); }
|
||||
.badge-warning { background: var(--busy); }
|
||||
.badge-secondary { background: var(--bg-elevated); color: var(--text-secondary); }
|
||||
|
||||
.muted { color: var(--text-secondary); }
|
||||
|
||||
.toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 16px; flex-wrap: wrap; }
|
||||
|
||||
code {
|
||||
background: var(--bg-input); padding: 2px 6px; border-radius: 3px;
|
||||
font-family: 'Cascadia Code', 'Consolas', monospace; font-size: 12px;
|
||||
color: #C5E1A5;
|
||||
}
|
||||
pre {
|
||||
background: var(--bg-input); padding: 12px; border-radius: 4px;
|
||||
font-family: 'Cascadia Code', 'Consolas', monospace; font-size: 12px;
|
||||
overflow: auto; white-space: pre-wrap; word-break: break-all;
|
||||
}
|
||||
|
||||
.kpi { font-size: 36px; font-weight: 700; line-height: 1; }
|
||||
.kpi-label { font-size: 11px; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; font-weight: 600; }
|
||||
|
||||
ol, ul { margin: 0; padding-left: 20px; }
|
||||
li { margin-bottom: 4px; }
|
||||
|
||||
details summary { cursor: pointer; padding: 4px 0; }
|
||||
details[open] { background: var(--bg-elevated); padding: 8px; border-radius: 4px; margin: 4px 0; }
|
||||
|
||||
a { color: var(--accent); }
|
||||
a:hover { text-decoration: underline; }
|
||||
121
server/admin/audit.php
Normal file
121
server/admin/audit.php
Normal file
@@ -0,0 +1,121 @@
|
||||
<?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);
|
||||
|
||||
$page = max(1, (int)($_GET['page'] ?? 1));
|
||||
$pageSize = 100;
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$filter = trim((string)($_GET['event'] ?? ''));
|
||||
|
||||
$where = '';
|
||||
$params = [];
|
||||
if ($filter !== '') {
|
||||
$where = 'WHERE event = ?';
|
||||
$params[] = $filter;
|
||||
}
|
||||
|
||||
$total = (int)$db->prepare("SELECT COUNT(*) FROM audit_log $where")->execute($params) ?? 0;
|
||||
$totalStmt = $db->prepare("SELECT COUNT(*) FROM audit_log $where");
|
||||
$totalStmt->execute($params);
|
||||
$total = (int)$totalStmt->fetchColumn();
|
||||
$totalPages = max(1, (int)ceil($total / $pageSize));
|
||||
|
||||
$listStmt = $db->prepare("SELECT a.*, l.owner_name FROM audit_log a LEFT JOIN licenses l ON l.id = a.license_id $where ORDER BY a.id DESC LIMIT $pageSize OFFSET $offset");
|
||||
$listStmt->execute($params);
|
||||
$rows = $listStmt->fetchAll();
|
||||
|
||||
$eventTypes = $db->query('SELECT DISTINCT event FROM audit_log ORDER BY event')->fetchAll(\PDO::FETCH_COLUMN);
|
||||
|
||||
Layout::header('Audit', 'audit');
|
||||
?>
|
||||
<h1>Audit log</h1>
|
||||
|
||||
<div class="card">
|
||||
<form method="get" class="toolbar">
|
||||
<label style="margin: 0;">Filtrer par événement :</label>
|
||||
<select name="event" onchange="this.form.submit()">
|
||||
<option value="">Tous (<?= number_format($total) ?>)</option>
|
||||
<?php foreach ($eventTypes as $ev): ?>
|
||||
<option value="<?= htmlspecialchars($ev) ?>" <?= $ev === $filter ? 'selected' : '' ?>>
|
||||
<?= htmlspecialchars($ev) ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<?php if ($filter !== ''): ?>
|
||||
<a href="audit.php" class="btn btn-secondary">Réinitialiser</a>
|
||||
<?php endif; ?>
|
||||
<span class="muted" style="margin-left: auto;">page <?= $page ?> / <?= $totalPages ?> • <?= number_format($total) ?> entrée(s)</span>
|
||||
</form>
|
||||
|
||||
<?php if (empty($rows)): ?>
|
||||
<p class="muted">Aucune entrée d'audit.</p>
|
||||
<?php else: ?>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Date</th>
|
||||
<th>Événement</th>
|
||||
<th>License</th>
|
||||
<th>IP</th>
|
||||
<th>Détail</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($rows as $r):
|
||||
$cls = match($r['event']) {
|
||||
'validate_ok' => 'badge-success',
|
||||
'validate_invalid', 'validate_revoked', 'machine_limit' => 'badge-danger',
|
||||
'validate_expired' => 'badge-warning',
|
||||
default => 'badge-secondary',
|
||||
};
|
||||
$detail = $r['detail'] ? json_decode($r['detail'], true) : null;
|
||||
?>
|
||||
<tr>
|
||||
<td class="muted" style="white-space: nowrap;"><?= htmlspecialchars($r['ts']) ?></td>
|
||||
<td><span class="badge <?= $cls ?>"><?= htmlspecialchars($r['event']) ?></span></td>
|
||||
<td>
|
||||
<?php if ($r['license_id']): ?>
|
||||
#<?= htmlspecialchars((string)$r['license_id']) ?>
|
||||
<?php if ($r['owner_name']): ?>
|
||||
<span class="muted">(<?= htmlspecialchars($r['owner_name']) ?>)</span>
|
||||
<?php endif; ?>
|
||||
<?php else: ?>
|
||||
<span class="muted">—</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td class="muted"><?= htmlspecialchars($r['ip'] ?? '—') ?></td>
|
||||
<td class="muted">
|
||||
<?php if ($detail): ?>
|
||||
<code style="font-size: 11px;"><?= htmlspecialchars(json_encode($detail, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?></code>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="toolbar" style="margin-top:16px; justify-content: space-between;">
|
||||
<div>
|
||||
<?php if ($page > 1): ?>
|
||||
<a href="?<?= http_build_query(['event' => $filter, 'page' => $page - 1]) ?>" class="btn btn-secondary">← Précédent</a>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div>
|
||||
<?php if ($page < $totalPages): ?>
|
||||
<a href="?<?= http_build_query(['event' => $filter, 'page' => $page + 1]) ?>" class="btn btn-secondary">Suivant →</a>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php Layout::footer();
|
||||
103
server/admin/index.php
Normal file
103
server/admin/index.php
Normal file
@@ -0,0 +1,103 @@
|
||||
<?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);
|
||||
|
||||
$stats = [
|
||||
'licenses_total' => (int)$db->query('SELECT COUNT(*) FROM licenses')->fetchColumn(),
|
||||
'licenses_active' => (int)$db->query('SELECT COUNT(*) FROM licenses WHERE revoked_at IS NULL AND download_entitlement_until >= NOW()')->fetchColumn(),
|
||||
'licenses_expired' => (int)$db->query('SELECT COUNT(*) FROM licenses WHERE revoked_at IS NULL AND download_entitlement_until < NOW()')->fetchColumn(),
|
||||
'licenses_revoked' => (int)$db->query('SELECT COUNT(*) FROM licenses WHERE revoked_at IS NOT NULL')->fetchColumn(),
|
||||
'machines_30d' => (int)$db->query('SELECT COUNT(*) FROM license_machines WHERE last_seen >= DATE_SUB(NOW(), INTERVAL 30 DAY)')->fetchColumn(),
|
||||
'audit_24h' => (int)$db->query('SELECT COUNT(*) FROM audit_log WHERE ts >= DATE_SUB(NOW(), INTERVAL 24 HOUR)')->fetchColumn(),
|
||||
];
|
||||
|
||||
$manifestPath = dirname(__DIR__) . '/manifest/versions.json';
|
||||
$manifest = is_file($manifestPath) ? json_decode(file_get_contents($manifestPath), true) : null;
|
||||
$buildsDir = dirname(__DIR__) . '/builds';
|
||||
$zips = is_dir($buildsDir) ? glob("$buildsDir/*.zip") : [];
|
||||
|
||||
$lastAudit = $db->query('SELECT * FROM audit_log ORDER BY id DESC LIMIT 10')->fetchAll();
|
||||
|
||||
Layout::header('Dashboard', 'dashboard');
|
||||
?>
|
||||
<h1>Dashboard</h1>
|
||||
|
||||
<div class="row">
|
||||
<div class="card col">
|
||||
<div class="kpi-label">Licenses actives</div>
|
||||
<div class="kpi" style="color: var(--installed)"><?= $stats['licenses_active'] ?></div>
|
||||
</div>
|
||||
<div class="card col">
|
||||
<div class="kpi-label">Expirées</div>
|
||||
<div class="kpi" style="color: var(--busy)"><?= $stats['licenses_expired'] ?></div>
|
||||
</div>
|
||||
<div class="card col">
|
||||
<div class="kpi-label">Révoquées</div>
|
||||
<div class="kpi" style="color: var(--danger)"><?= $stats['licenses_revoked'] ?></div>
|
||||
</div>
|
||||
<div class="card col">
|
||||
<div class="kpi-label">Machines vues (30j)</div>
|
||||
<div class="kpi"><?= $stats['machines_30d'] ?></div>
|
||||
</div>
|
||||
<div class="card col">
|
||||
<div class="kpi-label">Validations (24h)</div>
|
||||
<div class="kpi"><?= $stats['audit_24h'] ?></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>État du dépôt de versions</h2>
|
||||
<div class="card">
|
||||
<p>
|
||||
<strong><?= count($manifest['versions'] ?? []) ?></strong> entrée(s) dans le manifest •
|
||||
<strong><?= count($zips) ?></strong> ZIP(s) dans <code>builds/</code> •
|
||||
signature manifest :
|
||||
<?= empty($manifest['signature'])
|
||||
? "<span class='badge badge-warning'>NON SIGNÉ</span>"
|
||||
: "<span class='badge badge-success'>SIGNÉ Ed25519</span>" ?>
|
||||
</p>
|
||||
<?php if (!empty($manifest['versions'])): ?>
|
||||
<p class="muted">Dernière version annoncée : <code>v<?= htmlspecialchars($manifest['latest'] ?? '?') ?></code>
|
||||
(publiée le <?= htmlspecialchars(substr($manifest['publishedAt'] ?? '', 0, 10)) ?>)</p>
|
||||
<?php endif; ?>
|
||||
<a href="versions.php" class="btn btn-primary">Gérer les versions →</a>
|
||||
</div>
|
||||
|
||||
<h2>Activité récente</h2>
|
||||
<div class="card">
|
||||
<?php if (empty($lastAudit)): ?>
|
||||
<p class="muted">Aucune activité enregistrée.</p>
|
||||
<?php else: ?>
|
||||
<table>
|
||||
<thead><tr><th>Date</th><th>Événement</th><th>License</th><th>IP</th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($lastAudit as $row):
|
||||
$cls = match($row['event']) {
|
||||
'validate_ok' => 'badge-success',
|
||||
'validate_invalid', 'validate_revoked', 'machine_limit' => 'badge-danger',
|
||||
'validate_expired' => 'badge-warning',
|
||||
default => 'badge-secondary',
|
||||
};
|
||||
?>
|
||||
<tr>
|
||||
<td class="muted"><?= htmlspecialchars($row['ts']) ?></td>
|
||||
<td><span class="badge <?= $cls ?>"><?= htmlspecialchars($row['event']) ?></span></td>
|
||||
<td><?= $row['license_id'] ? '#' . htmlspecialchars((string)$row['license_id']) : '<span class="muted">—</span>' ?></td>
|
||||
<td class="muted"><?= htmlspecialchars($row['ip'] ?? '—') ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<a href="audit.php" class="btn btn-secondary" style="margin-top:16px">Voir tout →</a>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php Layout::footer();
|
||||
74
server/admin/lib/Auth.php
Normal file
74
server/admin/lib/Auth.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PSLauncher\Admin;
|
||||
|
||||
final class Auth
|
||||
{
|
||||
public static function start(): void
|
||||
{
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_set_cookie_params([
|
||||
'lifetime' => 0,
|
||||
'path' => '/',
|
||||
'secure' => !empty($_SERVER['HTTPS']),
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
]);
|
||||
session_name('PSLAUNCHER_ADMIN');
|
||||
session_start();
|
||||
}
|
||||
if (!isset($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
public static function isLoggedIn(): bool
|
||||
{
|
||||
return !empty($_SESSION['admin']);
|
||||
}
|
||||
|
||||
public static function login(string $username, string $password, array $config): bool
|
||||
{
|
||||
$hash = $config['admin_password_hash'] ?? '';
|
||||
if ($hash === '') return false;
|
||||
if (!password_verify($password, $hash)) return false;
|
||||
|
||||
$_SESSION['admin'] = ['user' => $username, 'at' => time()];
|
||||
// régénère l'ID après login pour éviter session fixation
|
||||
session_regenerate_id(true);
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function logout(): void
|
||||
{
|
||||
$_SESSION = [];
|
||||
if (ini_get('session.use_cookies')) {
|
||||
$p = session_get_cookie_params();
|
||||
setcookie(session_name(), '', time() - 3600, $p['path'], $p['domain'] ?? '', $p['secure'], $p['httponly']);
|
||||
}
|
||||
session_destroy();
|
||||
}
|
||||
|
||||
public static function requireLogin(): void
|
||||
{
|
||||
self::start();
|
||||
if (!self::isLoggedIn()) {
|
||||
header('Location: login.php');
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
public static function csrfToken(): string
|
||||
{
|
||||
return $_SESSION['csrf'] ?? '';
|
||||
}
|
||||
|
||||
public static function checkCsrf(): void
|
||||
{
|
||||
$token = $_POST['csrf'] ?? '';
|
||||
if (!hash_equals($_SESSION['csrf'] ?? '', $token)) {
|
||||
http_response_code(403);
|
||||
die('CSRF token invalid');
|
||||
}
|
||||
}
|
||||
}
|
||||
84
server/admin/lib/Layout.php
Normal file
84
server/admin/lib/Layout.php
Normal file
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PSLauncher\Admin;
|
||||
|
||||
final class Layout
|
||||
{
|
||||
public static function header(string $title, string $active = ''): void
|
||||
{
|
||||
Auth::start();
|
||||
$isLoggedIn = Auth::isLoggedIn();
|
||||
$titleEsc = htmlspecialchars($title);
|
||||
$nav = $isLoggedIn ? self::navHtml($active) : '';
|
||||
echo <<<HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex,nofollow">
|
||||
<title>{$titleEsc} — PS_Launcher Admin</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
{$nav}
|
||||
<main>
|
||||
HTML;
|
||||
}
|
||||
|
||||
public static function footer(): void
|
||||
{
|
||||
echo "</main></body></html>";
|
||||
}
|
||||
|
||||
private static function navHtml(string $active): string
|
||||
{
|
||||
$items = [
|
||||
'dashboard' => ['index.php', 'Dashboard'],
|
||||
'licenses' => ['licenses.php', 'Licenses'],
|
||||
'versions' => ['versions.php', 'Versions'],
|
||||
'audit' => ['audit.php', 'Audit'],
|
||||
];
|
||||
$links = '';
|
||||
foreach ($items as $k => [$href, $label]) {
|
||||
$cls = ($k === $active) ? 'active' : '';
|
||||
$links .= sprintf(
|
||||
'<a href="%s" class="%s">%s</a>',
|
||||
htmlspecialchars($href),
|
||||
$cls,
|
||||
htmlspecialchars($label)
|
||||
);
|
||||
}
|
||||
return <<<HTML
|
||||
<nav>
|
||||
<strong class="brand">PS_Launcher Admin</strong>
|
||||
{$links}
|
||||
<span class="spacer"></span>
|
||||
<a href="logout.php" class="logout">Déconnexion</a>
|
||||
</nav>
|
||||
HTML;
|
||||
}
|
||||
|
||||
public static function flash(?string $msg, string $type = 'success'): void
|
||||
{
|
||||
if ($msg === null || $msg === '') return;
|
||||
$cls = $type === 'error' ? 'error' : 'success';
|
||||
echo "<div class='flash {$cls}'>" . nl2br(htmlspecialchars($msg)) . "</div>";
|
||||
}
|
||||
|
||||
public static function csrfField(): string
|
||||
{
|
||||
return '<input type="hidden" name="csrf" value="' . htmlspecialchars(Auth::csrfToken()) . '">';
|
||||
}
|
||||
|
||||
public static function formatBytes(int $bytes): string
|
||||
{
|
||||
if ($bytes <= 0) return '—';
|
||||
$units = ['o', 'Ko', 'Mo', 'Go', 'To'];
|
||||
$u = 0;
|
||||
$v = (float)$bytes;
|
||||
while ($v >= 1024 && $u < count($units) - 1) { $v /= 1024; $u++; }
|
||||
return number_format($v, 1) . ' ' . $units[$u];
|
||||
}
|
||||
}
|
||||
213
server/admin/licenses.php
Normal file
213
server/admin/licenses.php
Normal 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();
|
||||
53
server/admin/login.php
Normal file
53
server/admin/login.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
require __DIR__ . '/lib/Auth.php';
|
||||
require __DIR__ . '/lib/Layout.php';
|
||||
|
||||
use PSLauncher\Admin\Auth;
|
||||
use PSLauncher\Admin\Layout;
|
||||
|
||||
Auth::start();
|
||||
|
||||
// Si déjà connecté, on redirige
|
||||
if (Auth::isLoggedIn()) {
|
||||
header('Location: index.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
$config = require __DIR__ . '/../api/config.php';
|
||||
$error = null;
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
Auth::checkCsrf();
|
||||
$user = trim($_POST['username'] ?? '');
|
||||
$pass = $_POST['password'] ?? '';
|
||||
if (Auth::login($user, $pass, $config)) {
|
||||
header('Location: index.php');
|
||||
exit;
|
||||
}
|
||||
$error = 'Identifiants invalides';
|
||||
sleep(1); // throttling très basique
|
||||
}
|
||||
|
||||
Layout::header('Connexion');
|
||||
?>
|
||||
<div style="max-width: 400px; margin: 80px auto;">
|
||||
<div class="card">
|
||||
<h1 style="margin-bottom: 8px;">PS_Launcher</h1>
|
||||
<p class="muted" style="margin-top: 0; margin-bottom: 24px;">Backoffice administration</p>
|
||||
<?php Layout::flash($error, 'error'); ?>
|
||||
<form method="post">
|
||||
<?= Layout::csrfField() ?>
|
||||
<div class="field">
|
||||
<label>Utilisateur</label>
|
||||
<input type="text" name="username" required autofocus value="admin">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Mot de passe</label>
|
||||
<input type="password" name="password" required>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="submit" style="width:100%; padding: 10px;">Connexion</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<?php Layout::footer();
|
||||
9
server/admin/logout.php
Normal file
9
server/admin/logout.php
Normal file
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
require __DIR__ . '/lib/Auth.php';
|
||||
|
||||
use PSLauncher\Admin\Auth;
|
||||
|
||||
Auth::start();
|
||||
Auth::logout();
|
||||
header('Location: login.php');
|
||||
347
server/admin/versions.php
Normal file
347
server/admin/versions.php
Normal file
@@ -0,0 +1,347 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
require __DIR__ . '/lib/Auth.php';
|
||||
require __DIR__ . '/lib/Layout.php';
|
||||
|
||||
use PSLauncher\Admin\Auth;
|
||||
use PSLauncher\Admin\Layout;
|
||||
|
||||
Auth::requireLogin();
|
||||
$config = require __DIR__ . '/../api/config.php';
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$manifestPath = "$root/manifest/versions.json";
|
||||
$buildsDir = "$root/builds";
|
||||
$notesDir = "$root/releasenotes";
|
||||
|
||||
$message = null; $messageType = 'success';
|
||||
|
||||
function loadManifest(string $path): array
|
||||
{
|
||||
if (!is_file($path)) return ['schemaVersion' => 1, 'product' => 'PROSERVE_UE', 'latest' => null, 'versions' => []];
|
||||
return json_decode(file_get_contents($path), true) ?? [];
|
||||
}
|
||||
|
||||
function saveManifest(string $path, array $manifest): void
|
||||
{
|
||||
// Re-tri par SemVer descendant
|
||||
usort($manifest['versions'], fn($a, $b) => version_compare($b['version'], $a['version']));
|
||||
file_put_contents(
|
||||
$path,
|
||||
json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"
|
||||
);
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
Auth::checkCsrf();
|
||||
$action = $_POST['action'] ?? '';
|
||||
$manifest = loadManifest($manifestPath);
|
||||
|
||||
try {
|
||||
if ($action === 'add') {
|
||||
$version = trim($_POST['version'] ?? '');
|
||||
$minLicDate = trim($_POST['min_license_date'] ?? '');
|
||||
$releasedAt = trim($_POST['released_at'] ?? '');
|
||||
$notes = $_POST['notes'] ?? '';
|
||||
$available = isset($_POST['available']);
|
||||
|
||||
if (!preg_match('/^\d+\.\d+\.\d+$/', $version)) {
|
||||
throw new Exception('Numéro de version invalide (format X.Y.Z attendu).');
|
||||
}
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $minLicDate)) {
|
||||
throw new Exception('Date min_license_date invalide.');
|
||||
}
|
||||
foreach ($manifest['versions'] as $v) {
|
||||
if ($v['version'] === $version) throw new Exception("v{$version} existe déjà dans le manifest.");
|
||||
}
|
||||
|
||||
$releasedAtIso = $releasedAt !== ''
|
||||
? (new DateTime($releasedAt, new DateTimeZone('UTC')))->format('Y-m-d\TH:i:s\Z')
|
||||
: (new DateTimeImmutable('now', new DateTimeZone('UTC')))->format('Y-m-d\TH:i:s\Z');
|
||||
|
||||
$base = $config['base_url'] ?? 'https://asterionvr.com/PS_Launcher';
|
||||
$manifest['versions'][] = [
|
||||
'version' => $version,
|
||||
'releasedAt' => $releasedAtIso,
|
||||
'executable' => 'PROSERVE_UE_5_5.exe',
|
||||
'installFolderTemplate' => 'Proserve v{version}',
|
||||
'download' => [
|
||||
'url' => "{$base}/builds/proserve-{$version}.zip",
|
||||
'sizeBytes' => 0,
|
||||
'sha256' => 'REPLACE_AFTER_BUILD',
|
||||
],
|
||||
'releaseNotesUrl' => "{$base}/api/releasenotes/{$version}",
|
||||
'minLicenseDate' => $minLicDate,
|
||||
'availableForDownload' => $available,
|
||||
];
|
||||
|
||||
saveManifest($manifestPath, $manifest);
|
||||
|
||||
if ($notes !== '') {
|
||||
if (!is_dir($notesDir)) mkdir($notesDir, 0755, true);
|
||||
file_put_contents("$notesDir/{$version}.md", $notes);
|
||||
}
|
||||
$message = "v{$version} ajoutée. Upload le ZIP en SFTP dans builds/, puis clique « Sync (sign-manifest) ».";
|
||||
}
|
||||
elseif ($action === 'edit_notes') {
|
||||
$version = $_POST['version'] ?? '';
|
||||
$notes = $_POST['notes'] ?? '';
|
||||
if (!preg_match('/^\d+\.\d+\.\d+$/', $version)) throw new Exception('Version invalide.');
|
||||
if (!is_dir($notesDir)) mkdir($notesDir, 0755, true);
|
||||
file_put_contents("$notesDir/{$version}.md", $notes);
|
||||
$message = "Release notes de v{$version} mises à jour.";
|
||||
}
|
||||
elseif ($action === 'edit_meta') {
|
||||
$version = $_POST['version'] ?? '';
|
||||
$minLicDate = trim($_POST['min_license_date'] ?? '');
|
||||
$releasedAt = trim($_POST['released_at'] ?? '');
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $minLicDate)) {
|
||||
throw new Exception('min_license_date invalide.');
|
||||
}
|
||||
foreach ($manifest['versions'] as &$v) {
|
||||
if ($v['version'] === $version) {
|
||||
$v['minLicenseDate'] = $minLicDate;
|
||||
if ($releasedAt !== '') {
|
||||
$v['releasedAt'] = (new DateTime($releasedAt, new DateTimeZone('UTC')))->format('Y-m-d\TH:i:s\Z');
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
unset($v);
|
||||
saveManifest($manifestPath, $manifest);
|
||||
$message = "Méta de v{$version} mises à jour.";
|
||||
}
|
||||
elseif ($action === 'toggle_available') {
|
||||
$version = $_POST['version'] ?? '';
|
||||
foreach ($manifest['versions'] as &$v) {
|
||||
if ($v['version'] === $version) {
|
||||
$v['availableForDownload'] = !($v['availableForDownload'] ?? true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
unset($v);
|
||||
saveManifest($manifestPath, $manifest);
|
||||
$message = "Disponibilité de v{$version} mise à jour.";
|
||||
}
|
||||
elseif ($action === 'delete') {
|
||||
$version = $_POST['version'] ?? '';
|
||||
$manifest['versions'] = array_values(array_filter(
|
||||
$manifest['versions'],
|
||||
fn($v) => $v['version'] !== $version
|
||||
));
|
||||
saveManifest($manifestPath, $manifest);
|
||||
$message = "v{$version} retirée du manifest. Le ZIP reste dans builds/ (à supprimer en SFTP si voulu).";
|
||||
}
|
||||
elseif ($action === 'sync') {
|
||||
$output = [];
|
||||
$exitCode = 0;
|
||||
$cwd = escapeshellarg($root);
|
||||
exec("cd $cwd && php tools/sign-manifest.php 2>&1", $output, $exitCode);
|
||||
$message = "Sortie du script :\n" . implode("\n", $output);
|
||||
if ($exitCode !== 0) $messageType = 'error';
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
$message = $e->getMessage();
|
||||
$messageType = 'error';
|
||||
}
|
||||
}
|
||||
|
||||
$manifest = loadManifest($manifestPath);
|
||||
$zips = is_dir($buildsDir) ? array_map('basename', glob("$buildsDir/*.zip") ?: []) : [];
|
||||
$zipSizes = [];
|
||||
foreach ($zips as $z) $zipSizes[$z] = filesize("$buildsDir/$z");
|
||||
|
||||
// Pour l'édition : pré-charge les release notes existantes
|
||||
$existingNotes = [];
|
||||
foreach ($manifest['versions'] ?? [] as $v) {
|
||||
$f = "$notesDir/{$v['version']}.md";
|
||||
$existingNotes[$v['version']] = is_file($f) ? file_get_contents($f) : '';
|
||||
}
|
||||
|
||||
Layout::header('Versions', 'versions');
|
||||
?>
|
||||
<h1>Versions</h1>
|
||||
|
||||
<?php Layout::flash($message, $messageType); ?>
|
||||
|
||||
<div class="card">
|
||||
<h2>Workflow d'une nouvelle release</h2>
|
||||
<ol class="muted">
|
||||
<li>Ajoute l'entrée du manifest avec le formulaire ci-dessous (version, date min de license, release notes).</li>
|
||||
<li>Upload le ZIP correspondant via SFTP dans <code>www/PS_Launcher/builds/</code> en respectant le nom <code>proserve-{version}.zip</code>.</li>
|
||||
<li>Clique <strong>🔁 Sync (sign-manifest)</strong> pour calculer le SHA-256, mettre à jour <code>sizeBytes</code>, bumper <code>latest</code>, et signer le manifest avec Ed25519.</li>
|
||||
<li>Les clients PS_Launcher détecteront la nouvelle version au prochain « Vérifier les MAJ ».</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Ajouter une version</h2>
|
||||
<form method="post">
|
||||
<?= Layout::csrfField() ?>
|
||||
<input type="hidden" name="action" value="add">
|
||||
<div class="row">
|
||||
<div class="col field">
|
||||
<label>Version (X.Y.Z)</label>
|
||||
<input type="text" name="version" placeholder="1.4.8" required pattern="\d+\.\d+\.\d+">
|
||||
</div>
|
||||
<div class="col field">
|
||||
<label>Date de release</label>
|
||||
<input type="datetime-local" name="released_at">
|
||||
</div>
|
||||
<div class="col field">
|
||||
<label>min_license_date (license requise)</label>
|
||||
<input type="date" name="min_license_date" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Release notes (Markdown)</label>
|
||||
<textarea name="notes" rows="8" placeholder="# Proserve v1.4.8 ## Nouveautés - ..." style="font-family: 'Cascadia Code', Consolas, monospace;"></textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label><input type="checkbox" name="available" checked> Disponible au téléchargement</label>
|
||||
</div>
|
||||
<button class="btn btn-success" type="submit">Ajouter au manifest</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="toolbar">
|
||||
<h2 style="margin: 0; flex: 1;">Manifest actuel</h2>
|
||||
<span class="muted">
|
||||
Signature :
|
||||
<?= empty($manifest['signature'])
|
||||
? "<span class='badge badge-warning'>NON SIGNÉ</span>"
|
||||
: "<span class='badge badge-success'>SIGNÉ Ed25519</span>" ?>
|
||||
<?php if (!empty($manifest['latest'])): ?>
|
||||
• latest : <code>v<?= htmlspecialchars($manifest['latest']) ?></code>
|
||||
<?php endif; ?>
|
||||
</span>
|
||||
<form method="post" style="display:inline">
|
||||
<?= Layout::csrfField() ?>
|
||||
<input type="hidden" name="action" value="sync">
|
||||
<button class="btn btn-primary" type="submit">🔁 Sync (sign-manifest)</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Version</th>
|
||||
<th>Release</th>
|
||||
<th>min_license</th>
|
||||
<th>ZIP</th>
|
||||
<th>Hash</th>
|
||||
<th>Visible</th>
|
||||
<th style="text-align:right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($manifest['versions'] ?? [] as $v):
|
||||
$zipBase = basename(parse_url($v['download']['url'], PHP_URL_PATH) ?? '');
|
||||
$zipExists = in_array($zipBase, $zips, true);
|
||||
$hashed = !empty($v['download']['sha256']) && !str_starts_with($v['download']['sha256'], 'REPLACE');
|
||||
?>
|
||||
<tr>
|
||||
<td><strong>v<?= htmlspecialchars($v['version']) ?></strong></td>
|
||||
<td class="muted"><?= htmlspecialchars(substr($v['releasedAt'] ?? '', 0, 10)) ?></td>
|
||||
<td class="muted"><?= htmlspecialchars($v['minLicenseDate'] ?? '—') ?></td>
|
||||
<td>
|
||||
<?php if ($zipExists): ?>
|
||||
<span class="badge badge-success">présent</span>
|
||||
<span class="muted"><?= Layout::formatBytes($zipSizes[$zipBase] ?? 0) ?></span>
|
||||
<?php else: ?>
|
||||
<span class="badge badge-warning">absent</span>
|
||||
<div class="muted" style="font-size: 11px;">attendu : <code><?= htmlspecialchars($zipBase) ?></code></div>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td>
|
||||
<?php if ($hashed): ?>
|
||||
<code title="<?= htmlspecialchars($v['download']['sha256']) ?>"><?= substr($v['download']['sha256'], 0, 12) ?>…</code>
|
||||
<?php else: ?>
|
||||
<span class="badge badge-warning">à calculer</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td>
|
||||
<form method="post" style="display:inline">
|
||||
<?= Layout::csrfField() ?>
|
||||
<input type="hidden" name="action" value="toggle_available">
|
||||
<input type="hidden" name="version" value="<?= htmlspecialchars($v['version']) ?>">
|
||||
<button class="btn btn-secondary" type="submit">
|
||||
<?= ($v['availableForDownload'] ?? true) ? '✓' : '✗' ?>
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
<td style="text-align: right; white-space: nowrap;">
|
||||
<details style="display: inline-block; margin: 0 4px;">
|
||||
<summary class="btn btn-secondary">Méta</summary>
|
||||
<form method="post" style="margin-top: 8px;">
|
||||
<?= Layout::csrfField() ?>
|
||||
<input type="hidden" name="action" value="edit_meta">
|
||||
<input type="hidden" name="version" value="<?= htmlspecialchars($v['version']) ?>">
|
||||
<div class="field">
|
||||
<label>min_license_date</label>
|
||||
<input type="date" name="min_license_date" value="<?= htmlspecialchars($v['minLicenseDate'] ?? '') ?>" required>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Date de release (UTC)</label>
|
||||
<input type="datetime-local" name="released_at" value="<?= htmlspecialchars(substr($v['releasedAt'] ?? '', 0, 16)) ?>">
|
||||
</div>
|
||||
<button class="btn btn-primary" type="submit">Enregistrer</button>
|
||||
</form>
|
||||
</details>
|
||||
<details style="display: inline-block; margin: 0 4px;">
|
||||
<summary class="btn btn-secondary">Notes</summary>
|
||||
<form method="post" style="margin-top: 8px;">
|
||||
<?= Layout::csrfField() ?>
|
||||
<input type="hidden" name="action" value="edit_notes">
|
||||
<input type="hidden" name="version" value="<?= htmlspecialchars($v['version']) ?>">
|
||||
<textarea name="notes" rows="10" style="font-family: 'Cascadia Code', Consolas, monospace; min-width: 400px;"><?= htmlspecialchars($existingNotes[$v['version']] ?? '') ?></textarea>
|
||||
<br><br>
|
||||
<button class="btn btn-primary" type="submit">Enregistrer les notes</button>
|
||||
</form>
|
||||
</details>
|
||||
<form method="post" style="display:inline" onsubmit="return confirm('Retirer v<?= htmlspecialchars($v['version']) ?> du manifest ?\n(Le ZIP reste dans builds/, supprime-le en SFTP si voulu.)')">
|
||||
<?= Layout::csrfField() ?>
|
||||
<input type="hidden" name="action" value="delete">
|
||||
<input type="hidden" name="version" value="<?= htmlspecialchars($v['version']) ?>">
|
||||
<button class="btn btn-danger" type="submit">Retirer</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php if (empty($manifest['versions'])): ?>
|
||||
<tr><td colspan="7" class="muted" style="text-align:center; padding: 32px;">Aucune version dans le manifest.</td></tr>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>ZIPs présents dans builds/</h2>
|
||||
<?php if (empty($zips)): ?>
|
||||
<p class="muted">Aucun ZIP. Upload tes fichiers via SFTP dans <code>www/PS_Launcher/builds/</code>, puis clique « Sync » ci-dessus.</p>
|
||||
<?php else: ?>
|
||||
<table>
|
||||
<thead><tr><th>Fichier</th><th>Taille</th><th>Référencé ?</th></tr></thead>
|
||||
<tbody>
|
||||
<?php
|
||||
$referencedNames = [];
|
||||
foreach ($manifest['versions'] ?? [] as $v) {
|
||||
$referencedNames[] = basename(parse_url($v['download']['url'], PHP_URL_PATH) ?? '');
|
||||
}
|
||||
foreach ($zips as $z):
|
||||
$referenced = in_array($z, $referencedNames, true);
|
||||
?>
|
||||
<tr>
|
||||
<td><code><?= htmlspecialchars($z) ?></code></td>
|
||||
<td class="muted"><?= Layout::formatBytes($zipSizes[$z]) ?></td>
|
||||
<td><?= $referenced
|
||||
? "<span class='badge badge-success'>oui</span>"
|
||||
: "<span class='badge badge-warning'>orphelin</span>" ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php Layout::footer();
|
||||
@@ -33,4 +33,11 @@ return [
|
||||
|
||||
// Limites de validation
|
||||
'validate_max_per_minute_per_ip' => 10,
|
||||
|
||||
// === BACKOFFICE ADMIN ===
|
||||
// Mot de passe bcrypt pour la connexion à /PS_Launcher/admin/
|
||||
// Génère le hash via SSH OVH :
|
||||
// php -r "echo password_hash('motdepasse_choisi', PASSWORD_DEFAULT);"
|
||||
// puis colle le résultat ci-dessous.
|
||||
'admin_password_hash' => '',
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user