v0.4: licensing — server validation, DPAPI cache, Ed25519 signed responses

UX bonus: clicking "Reprendre" on an interrupted download skips the
release-notes confirmation dialog (the user already approved when they
first clicked Installer).

Server side
-----------
- migrations/001_init.sql: licenses, license_machines, rate_limit,
  audit_log on InnoDB/utf8mb4. Foreign keys, unique on license_key, slot
  uniqueness per (license_id, machine_id).
- api/lib/Db.php: thin PDO singleton (exception mode, prepared, no emul).
- api/lib/Crypto.php: Ed25519 sign/verify via libsodium (sodium_crypto_*),
  HMAC-SHA-256 helper for v0.6, canonicalJson() that strips `signature`
  before serializing — must match exactly the encoding done client-side
  before verify.
- api/routes/ValidateLicense.php: POST /license/validate. Looks up the
  key, walks the machine slot logic (insert or update last_seen),
  enforces max_machines, returns a payload signed Ed25519 + status of
  valid/expired/revoked/machine_limit_exceeded/invalid. Audit logs every
  outcome. Rate-limit 10/min/IP via the rate_limit table.
- tools/generate-keypair.php: prints a fresh sodium keypair so the
  operator drops the hex into config.php and the public_key_hex into the
  launcher resource.
- tools/issue-license.php: PRSRV-XXXX-XXXX-XXXX-XXXX generator (32-char
  unambiguous alphabet), inserts the license, prints the key once.
- tools/sign-manifest.php: now also signs the manifest itself with
  Ed25519 after computing the per-zip sha256s.
- config.example.php: schema rewritten with sections db / hmac / ed25519
  / jwt / rate-limit. config.php remains gitignored.

Client side
-----------
- Models/License.cs: LicenseValidationRequest + LicenseValidationResponse
  with CanDownload(VersionManifest) — entitlement_until vs version's
  minLicenseDate. The status valid|expired|revoked|machine_limit_exceeded
  flow is preserved end-to-end.
- Core/Licensing/LicenseService.cs:
  * machineId = SHA-256 of HKLM/Software/Microsoft/Cryptography/MachineGuid
    + UserName (stable, no PII leak)
  * online ValidateAsync calls /license/validate with launcher version
  * embedded server-pubkey.txt drives Ed25519 verification of the
    response (skipped gracefully if pubkey not yet provisioned)
  * SaveCached / GetCached use DPAPI CurrentUser scope on the license
    key; the cleartext key never touches disk
  * GetCached has a 7-day offline grace window after the last successful
    validation, so going offline doesn't lock the user out
- Core/Resources/server-pubkey.txt: EmbeddedResource. Default content is
  a comment, which the service treats as "no pubkey configured" and
  bypasses verification. Operator pastes the real hex post-deploy and
  rebuilds.
- Core/PSLauncher.Core.csproj: Polly, NSec.Cryptography (Ed25519),
  System.Security.Cryptography.ProtectedData (DPAPI).
- App/Views/OnboardingDialog.xaml(.cs): first-launch / "🔑 Activer"
  modal. Calls LicenseService, displays status messages with red
  foreground on errors and green-tinted secondary text otherwise.
- ViewModels/VersionRowViewModel.cs: new LicenseAllowsDownload property.
  Install button label switches to "🔒 License insuffisante" when the
  user's entitlement_until precedes the version's minLicenseDate;
  CanInstall is false in that case so the click is a no-op too.
- ViewModels/MainViewModel.cs: loads the cached license at startup (no
  network call), surfaces it as LicenseSummary in the top bar, exposes
  ActivateLicenseCommand to (re)open the onboarding dialog. RebuildList
  applies the per-version license filter so older installed versions
  remain launchable but newer-than-license ones can't be downloaded.
- Views/MainWindow.xaml: top bar gains a "🔑 Activer / changer" button
  next to the license summary.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-01 10:12:37 +02:00
parent 9bdcdabb9e
commit 7a29dbb049
20 changed files with 977 additions and 34 deletions

View File

@@ -1,30 +1,36 @@
<?php
// === À RENSEIGNER LORS DU DÉPLOIEMENT ===
// Ce fichier ne doit JAMAIS contenir de creds en clair commitées sur git public.
// Place ce fichier sur le serveur uniquement. Pour git, prévois un config.example.php.
// Copier ce fichier en config.php sur le serveur, puis le compléter.
// Le fichier config.php est gitignored.
return [
// Base path public sous lequel le launcher est servi (utilisé pour générer les URLs absolues)
'base_url' => 'https://www.exemple-asterion.com/PS_Launcher',
// Base path public sous lequel le launcher est servi
'base_url' => 'https://asterionvr.com/PS_Launcher',
// MySQL (utilisé à partir de v0.4, license)
// MySQL (depuis le manager OVH : Hébergements -> Bases de données)
'db' => [
'dsn' => 'mysql:host=localhost;dbname=pslauncher;charset=utf8mb4',
// Format DSN OVH typique : mysql:host=<bdd>.mysql.db;dbname=<bdd>;charset=utf8mb4
'dsn' => 'mysql:host=localhost;dbname=replace_me;charset=utf8mb4',
'username' => 'replace_me',
'password' => 'replace_me',
],
// HMAC secret pour les URLs présignées de /builds/ (v0.6)
// HMAC secret pour les URLs présignées de /builds/ (v0.6, optionnel)
// Génère 64 hex chars : `php -r "echo bin2hex(random_bytes(32));"`
'hmac_secret' => 'replace_with_random_64_bytes_hex',
// Clés Ed25519 pour signer manifest et réponses license (v0.4)
// Génère un keypair via tools/generate-keypair.php
// Clés Ed25519 pour signer la réponse de validation license et le manifest.
// Génère le keypair via : `php tools/generate-keypair.php`
// Recopie les hex strings ci-dessous, et embarque la public_key_hex dans le launcher.
'ed25519' => [
'private_key_hex' => '', // 64 bytes hex
'public_key_hex' => '', // 32 bytes hex (à embarquer aussi dans le launcher)
'private_key_hex' => '', // 128 hex chars (sodium secret key, contient la pub key)
'public_key_hex' => '', // 64 hex chars (32 bytes)
],
// JWT (v0.4)
// (v0.4-β) JWT pour les URLs de download protégées (optionnel pour le moment)
'jwt_secret' => 'replace_with_random_secret',
'jwt_ttl_seconds' => 900, // 15 min
// Limites de validation
'validate_max_per_minute_per_ip' => 10,
];

View File

@@ -52,6 +52,14 @@ if ($method === 'GET' && preg_match('#^releasenotes/([0-9]+\.[0-9]+\.[0-9]+)$#',
return;
}
if ($method === 'POST' && $route === 'license/validate') {
require __DIR__ . '/lib/Db.php';
require __DIR__ . '/lib/Crypto.php';
require __DIR__ . '/routes/ValidateLicense.php';
\PSLauncher\Routes\ValidateLicense::handle($config);
return;
}
if ($method === 'GET' && $route === 'health') {
Response::json([
'status' => 'ok',

65
server/api/lib/Crypto.php Normal file
View File

@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace PSLauncher;
final class Crypto
{
/**
* Signe un payload (chaîne canonical UTF-8) avec la clé privée Ed25519.
* Retourne la signature en base64.
*/
public static function signEd25519(string $payload, string $privateKeyHex): string
{
if (strlen($privateKeyHex) !== 128) {
throw new \InvalidArgumentException('private_key_hex must be 128 hex chars (sodium secret key)');
}
$sk = sodium_hex2bin($privateKeyHex);
$sig = sodium_crypto_sign_detached($payload, $sk);
return base64_encode($sig);
}
/**
* Génère un nouveau keypair Ed25519 et retourne ['private_key_hex', 'public_key_hex'].
*/
public static function generateKeypair(): array
{
$kp = sodium_crypto_sign_keypair();
$sk = sodium_crypto_sign_secretkey($kp);
$pk = sodium_crypto_sign_publickey($kp);
return [
'private_key_hex' => sodium_bin2hex($sk),
'public_key_hex' => sodium_bin2hex($pk),
];
}
/**
* Encodage canonical d'un objet JSON pour la signature : on retire le champ
* `signature` (s'il est là), on encode sans escapes inutiles, on signe ce blob.
* Le client doit faire EXACTEMENT le même encodage avant verify.
*/
public static function canonicalJson(array $data): string
{
unset($data['signature']);
return json_encode(
$data,
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION
);
}
/**
* Hash bcrypt-comparable d'une license_key (constant-time compare).
*/
public static function constantTimeEquals(string $a, string $b): bool
{
return hash_equals($a, $b);
}
/**
* HMAC-SHA-256 hex pour les URLs présignées (v0.6).
*/
public static function hmacHex(string $message, string $secret): string
{
return hash_hmac('sha256', $message, $secret);
}
}

26
server/api/lib/Db.php Normal file
View File

@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace PSLauncher;
final class Db
{
private static ?\PDO $pdo = null;
public static function get(array $config): \PDO
{
if (self::$pdo !== null) return self::$pdo;
$cfg = $config['db'];
self::$pdo = new \PDO(
$cfg['dsn'],
$cfg['username'],
$cfg['password'],
[
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
]
);
return self::$pdo;
}
}

View File

@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace PSLauncher\Routes;
use PSLauncher\Crypto;
use PSLauncher\Db;
use PSLauncher\Response;
final class ValidateLicense
{
public static function handle(array $config): void
{
// Rate limit basique par IP
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
self::enforceRateLimit($config, $ip);
$body = json_decode(file_get_contents('php://input') ?: '[]', true) ?? [];
$licenseKey = trim((string)($body['licenseKey'] ?? ''));
$machineId = trim((string)($body['machineId'] ?? ''));
$machineLabel = trim((string)($body['machineLabel'] ?? ''));
$launcherVer = trim((string)($body['launcherVersion'] ?? ''));
if ($licenseKey === '' || $machineId === '') {
Response::error('invalid_request', 'licenseKey et machineId sont requis', 400);
}
$db = Db::get($config);
$now = (new \DateTimeImmutable('now'))->format('Y-m-d H:i:s');
$stmt = $db->prepare(
'SELECT id, license_key, owner_name, issued_at, download_entitlement_until,
max_machines, revoked_at
FROM licenses WHERE license_key = ? LIMIT 1'
);
$stmt->execute([$licenseKey]);
$lic = $stmt->fetch();
if (!$lic) {
self::audit($db, null, $ip, 'validate_invalid', ['key_prefix' => substr($licenseKey, 0, 6)]);
Response::error('invalid', 'Clé de license invalide', 401);
}
if ($lic['revoked_at'] !== null) {
self::audit($db, (int)$lic['id'], $ip, 'validate_revoked', []);
Response::error('revoked', 'License révoquée', 403);
}
// Slot machine
$slotStmt = $db->prepare(
'SELECT id FROM license_machines WHERE license_id = ? AND machine_id = ? LIMIT 1'
);
$slotStmt->execute([$lic['id'], $machineId]);
$existingSlot = $slotStmt->fetch();
if ($existingSlot) {
$db->prepare('UPDATE license_machines SET last_seen = ? WHERE id = ?')
->execute([$now, $existingSlot['id']]);
} else {
$countStmt = $db->prepare('SELECT COUNT(*) AS c FROM license_machines WHERE license_id = ?');
$countStmt->execute([$lic['id']]);
$count = (int)($countStmt->fetch()['c'] ?? 0);
if ($count >= (int)$lic['max_machines']) {
self::audit($db, (int)$lic['id'], $ip, 'machine_limit', ['count' => $count]);
Response::error('machine_limit_exceeded',
"Cette license autorise {$lic['max_machines']} machine(s) ; toutes les places sont prises.",
403, ['ownerName' => $lic['owner_name']]);
}
$db->prepare(
'INSERT INTO license_machines (license_id, machine_id, machine_label, first_seen, last_seen)
VALUES (?, ?, ?, ?, ?)'
)->execute([$lic['id'], $machineId, $machineLabel ?: null, $now, $now]);
}
// Construit la réponse, signe-la, renvoie
$entUntil = (new \DateTimeImmutable($lic['download_entitlement_until']))->format(\DateTimeInterface::ATOM);
$serverTime = (new \DateTimeImmutable('now'))->format(\DateTimeInterface::ATOM);
$expired = strtotime($lic['download_entitlement_until']) < time();
$payload = [
'status' => $expired ? 'expired' : 'valid',
'licenseId' => 'lic_' . $lic['id'],
'ownerName' => $lic['owner_name'],
'issuedAt' => (new \DateTimeImmutable($lic['issued_at']))->format(\DateTimeInterface::ATOM),
'downloadEntitlementUntil' => $entUntil,
'maxMachines' => (int)$lic['max_machines'],
'serverTime' => $serverTime,
];
// Signature Ed25519 du payload canonical
$sk = $config['ed25519']['private_key_hex'] ?? '';
if ($sk !== '') {
$payload['signature'] = Crypto::signEd25519(Crypto::canonicalJson($payload), $sk);
}
self::audit($db, (int)$lic['id'], $ip, $expired ? 'validate_expired' : 'validate_ok', [
'launcher_version' => $launcherVer,
]);
Response::json($payload, $expired ? 200 : 200);
}
private static function enforceRateLimit(array $config, string $ip): void
{
$max = (int)($config['validate_max_per_minute_per_ip'] ?? 10);
if ($max <= 0) return;
$db = Db::get($config);
$now = new \DateTimeImmutable('now');
$window = $now->modify('-1 minute')->format('Y-m-d H:i:s');
$stmt = $db->prepare('SELECT counter, window_start FROM rate_limit WHERE ip = ?');
$stmt->execute([$ip]);
$row = $stmt->fetch();
if ($row === false || $row['window_start'] < $window) {
$db->prepare('REPLACE INTO rate_limit (ip, window_start, counter) VALUES (?, ?, 1)')
->execute([$ip, $now->format('Y-m-d H:i:s')]);
return;
}
if ((int)$row['counter'] >= $max) {
Response::error('rate_limited', 'Trop de tentatives. Réessaie dans 1 minute.', 429);
}
$db->prepare('UPDATE rate_limit SET counter = counter + 1 WHERE ip = ?')->execute([$ip]);
}
private static function audit(\PDO $db, ?int $licenseId, string $ip, string $event, array $detail): void
{
try {
$db->prepare(
'INSERT INTO audit_log (ts, license_id, ip, event, detail) VALUES (NOW(), ?, ?, ?, ?)'
)->execute([$licenseId, $ip, $event, json_encode($detail, JSON_UNESCAPED_UNICODE)]);
} catch (\Throwable) { /* best-effort */ }
}
}