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:
@@ -1,30 +1,36 @@
|
|||||||
<?php
|
<?php
|
||||||
// === À RENSEIGNER LORS DU DÉPLOIEMENT ===
|
// === À RENSEIGNER LORS DU DÉPLOIEMENT ===
|
||||||
// Ce fichier ne doit JAMAIS contenir de creds en clair commitées sur git public.
|
// Copier ce fichier en config.php sur le serveur, puis le compléter.
|
||||||
// Place ce fichier sur le serveur uniquement. Pour git, prévois un config.example.php.
|
// Le fichier config.php est gitignored.
|
||||||
|
|
||||||
return [
|
return [
|
||||||
// Base path public sous lequel le launcher est servi (utilisé pour générer les URLs absolues)
|
// Base path public sous lequel le launcher est servi
|
||||||
'base_url' => 'https://www.exemple-asterion.com/PS_Launcher',
|
'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' => [
|
'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',
|
'username' => 'replace_me',
|
||||||
'password' => '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',
|
'hmac_secret' => 'replace_with_random_64_bytes_hex',
|
||||||
|
|
||||||
// Clés Ed25519 pour signer manifest et réponses license (v0.4)
|
// Clés Ed25519 pour signer la réponse de validation license et le manifest.
|
||||||
// Génère un keypair via tools/generate-keypair.php
|
// 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' => [
|
'ed25519' => [
|
||||||
'private_key_hex' => '', // 64 bytes hex
|
'private_key_hex' => '', // 128 hex chars (sodium secret key, contient la pub key)
|
||||||
'public_key_hex' => '', // 32 bytes hex (à embarquer aussi dans le launcher)
|
'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_secret' => 'replace_with_random_secret',
|
||||||
'jwt_ttl_seconds' => 900, // 15 min
|
'jwt_ttl_seconds' => 900, // 15 min
|
||||||
|
|
||||||
|
// Limites de validation
|
||||||
|
'validate_max_per_minute_per_ip' => 10,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -52,6 +52,14 @@ if ($method === 'GET' && preg_match('#^releasenotes/([0-9]+\.[0-9]+\.[0-9]+)$#',
|
|||||||
return;
|
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') {
|
if ($method === 'GET' && $route === 'health') {
|
||||||
Response::json([
|
Response::json([
|
||||||
'status' => 'ok',
|
'status' => 'ok',
|
||||||
|
|||||||
65
server/api/lib/Crypto.php
Normal file
65
server/api/lib/Crypto.php
Normal 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
26
server/api/lib/Db.php
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
135
server/api/routes/ValidateLicense.php
Normal file
135
server/api/routes/ValidateLicense.php
Normal 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 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
49
server/migrations/001_init.sql
Normal file
49
server/migrations/001_init.sql
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
-- PS_Launcher schema v1
|
||||||
|
-- À jouer dans la base MySQL OVH créée via le manager.
|
||||||
|
-- Charset : utf8mb4 obligatoire (ownership names accentués, JSON details).
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS licenses (
|
||||||
|
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
license_key VARCHAR(64) NOT NULL UNIQUE,
|
||||||
|
owner_name VARCHAR(255) NOT NULL,
|
||||||
|
issued_at DATETIME NOT NULL,
|
||||||
|
download_entitlement_until DATETIME NOT NULL,
|
||||||
|
max_machines INT UNSIGNED NOT NULL DEFAULT 1,
|
||||||
|
revoked_at DATETIME NULL,
|
||||||
|
notes TEXT NULL,
|
||||||
|
INDEX idx_license_key (license_key),
|
||||||
|
INDEX idx_revoked (revoked_at),
|
||||||
|
INDEX idx_entitlement (download_entitlement_until)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS license_machines (
|
||||||
|
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
license_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
machine_id VARCHAR(128) NOT NULL,
|
||||||
|
machine_label VARCHAR(255) NULL,
|
||||||
|
first_seen DATETIME NOT NULL,
|
||||||
|
last_seen DATETIME NOT NULL,
|
||||||
|
UNIQUE KEY uk_license_machine (license_id, machine_id),
|
||||||
|
INDEX idx_last_seen (last_seen),
|
||||||
|
CONSTRAINT fk_machine_license FOREIGN KEY (license_id)
|
||||||
|
REFERENCES licenses(id) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS rate_limit (
|
||||||
|
ip VARCHAR(45) PRIMARY KEY,
|
||||||
|
window_start DATETIME NOT NULL,
|
||||||
|
counter INT UNSIGNED NOT NULL DEFAULT 0
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS audit_log (
|
||||||
|
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
ts DATETIME NOT NULL,
|
||||||
|
license_id BIGINT UNSIGNED NULL,
|
||||||
|
ip VARCHAR(45) NULL,
|
||||||
|
event VARCHAR(64) NOT NULL,
|
||||||
|
detail JSON NULL,
|
||||||
|
INDEX idx_ts (ts),
|
||||||
|
INDEX idx_event (event),
|
||||||
|
CONSTRAINT fk_audit_license FOREIGN KEY (license_id)
|
||||||
|
REFERENCES licenses(id) ON DELETE SET NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
22
server/tools/generate-keypair.php
Normal file
22
server/tools/generate-keypair.php
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Génère un keypair Ed25519 pour PS_Launcher.
|
||||||
|
*
|
||||||
|
* Usage (SSH OVH dans www/PS_Launcher) :
|
||||||
|
* php tools/generate-keypair.php
|
||||||
|
*
|
||||||
|
* Recopie ensuite :
|
||||||
|
* - private_key_hex et public_key_hex dans api/config.php (section ed25519)
|
||||||
|
* - public_key_hex dans le launcher : src/PSLauncher.App/Resources/server-pubkey.txt
|
||||||
|
*/
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/api/lib/Crypto.php';
|
||||||
|
|
||||||
|
$kp = \PSLauncher\Crypto::generateKeypair();
|
||||||
|
|
||||||
|
echo "==== KEYPAIR Ed25519 — copie ces valeurs en lieu sûr ====\n\n";
|
||||||
|
echo "private_key_hex (à mettre UNIQUEMENT dans api/config.php) :\n";
|
||||||
|
echo $kp['private_key_hex'] . "\n\n";
|
||||||
|
echo "public_key_hex (config.php ET embarqué dans le launcher) :\n";
|
||||||
|
echo $kp['public_key_hex'] . "\n";
|
||||||
63
server/tools/issue-license.php
Normal file
63
server/tools/issue-license.php
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Émet une nouvelle license dans la base. La clé est imprimée en clair sur stdout
|
||||||
|
* (à transmettre au client par canal sécurisé). Aucune trace en clair côté serveur :
|
||||||
|
* la base ne stocke que la clé via UNIQUE pour la lookup constant-time.
|
||||||
|
*
|
||||||
|
* Usage (SSH OVH) :
|
||||||
|
* php tools/issue-license.php "ACME Corp" 2026-12-31 [maxMachines=1]
|
||||||
|
*/
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/api/lib/Db.php';
|
||||||
|
$config = require dirname(__DIR__) . '/api/config.php';
|
||||||
|
|
||||||
|
if ($argc < 3) {
|
||||||
|
fwrite(STDERR, "Usage: php tools/issue-license.php \"<owner_name>\" <YYYY-MM-DD entitlement_until> [max_machines=1]\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
$owner = $argv[1];
|
||||||
|
$until = $argv[2];
|
||||||
|
$maxMachines = (int)($argv[3] ?? 1);
|
||||||
|
|
||||||
|
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $until)) {
|
||||||
|
fwrite(STDERR, "entitlement_until must be YYYY-MM-DD\n"); exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
$db = \PSLauncher\Db::get($config);
|
||||||
|
|
||||||
|
// Génère une clé du type PRSRV-XXXX-XXXX-XXXX-XXXX (groupes alphanumériques)
|
||||||
|
function genKey(): string {
|
||||||
|
$alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // pas de 0/O/1/I/L
|
||||||
|
$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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Boucle au cas (très improbable) où collision UNIQUE
|
||||||
|
for ($attempts = 0; $attempts < 5; $attempts++) {
|
||||||
|
$key = genKey();
|
||||||
|
try {
|
||||||
|
$stmt = $db->prepare(
|
||||||
|
'INSERT INTO licenses (license_key, owner_name, issued_at, download_entitlement_until, max_machines)
|
||||||
|
VALUES (?, ?, NOW(), ?, ?)'
|
||||||
|
);
|
||||||
|
$stmt->execute([$key, $owner, $until . ' 23:59:59', $maxMachines]);
|
||||||
|
$id = $db->lastInsertId();
|
||||||
|
echo "==== License émise ====\n";
|
||||||
|
echo "id : {$id}\n";
|
||||||
|
echo "owner : {$owner}\n";
|
||||||
|
echo "until : {$until}\n";
|
||||||
|
echo "key : {$key}\n";
|
||||||
|
exit(0);
|
||||||
|
} catch (\PDOException $e) {
|
||||||
|
if (str_contains($e->getMessage(), 'Duplicate')) continue;
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fwrite(STDERR, "Failed to generate unique key after retries\n"); exit(3);
|
||||||
@@ -78,11 +78,24 @@ if (!empty($hashedVersions)) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// (v0.4) Signature Ed25519 — pour l'instant on laisse 'signature' = null.
|
// (v0.4) Signature Ed25519 du manifest
|
||||||
// $config = require __DIR__ . '/../api/config.php';
|
$configPath = dirname(__DIR__) . '/api/config.php';
|
||||||
// $sk = sodium_hex2bin($config['ed25519']['private_key_hex']);
|
if (is_file($configPath)) {
|
||||||
// $payload = json_encode($manifest, JSON_UNESCAPED_SLASHES);
|
require_once dirname(__DIR__) . '/api/lib/Crypto.php';
|
||||||
// $manifest['signature'] = base64_encode(sodium_crypto_sign_detached($payload, $sk));
|
$config = require $configPath;
|
||||||
|
$sk = $config['ed25519']['private_key_hex'] ?? '';
|
||||||
|
if ($sk !== '' && strlen($sk) === 128) {
|
||||||
|
// Retire signature précédente, encode canonical, signe, ré-injecte
|
||||||
|
$manifest['signature'] = null;
|
||||||
|
$payload = \PSLauncher\Crypto::canonicalJson($manifest);
|
||||||
|
$manifest['signature'] = \PSLauncher\Crypto::signEd25519($payload, $sk);
|
||||||
|
echo " [sign] manifest signed (Ed25519)\n";
|
||||||
|
} else {
|
||||||
|
echo " [warn] ed25519.private_key_hex non configuré, manifest non signé\n";
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
echo " [warn] config.php absent, manifest non signé\n";
|
||||||
|
}
|
||||||
|
|
||||||
file_put_contents(
|
file_put_contents(
|
||||||
$manifestPath,
|
$manifestPath,
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ using PSLauncher.Core.Configuration;
|
|||||||
using PSLauncher.Core.Downloads;
|
using PSLauncher.Core.Downloads;
|
||||||
using PSLauncher.Core.Installations;
|
using PSLauncher.Core.Installations;
|
||||||
using PSLauncher.Core.Integrity;
|
using PSLauncher.Core.Integrity;
|
||||||
|
using PSLauncher.Core.Licensing;
|
||||||
using PSLauncher.Core.Manifests;
|
using PSLauncher.Core.Manifests;
|
||||||
using PSLauncher.Core.Process;
|
using PSLauncher.Core.Process;
|
||||||
using PSLauncher.Core.Updates;
|
using PSLauncher.Core.Updates;
|
||||||
@@ -66,6 +67,14 @@ public partial class App : Application
|
|||||||
services.AddSingleton<IDownloadManager, DownloadManager>();
|
services.AddSingleton<IDownloadManager, DownloadManager>();
|
||||||
services.AddSingleton<IUpdateChecker, UpdateChecker>();
|
services.AddSingleton<IUpdateChecker, UpdateChecker>();
|
||||||
|
|
||||||
|
services.AddSingleton<ILicenseService>(sp =>
|
||||||
|
new LicenseService(
|
||||||
|
sp.GetRequiredService<HttpClient>(),
|
||||||
|
() => sp.GetRequiredService<LocalConfig>().ServerBaseUrl,
|
||||||
|
sp.GetRequiredService<IConfigStore>(),
|
||||||
|
sp.GetRequiredService<LocalConfig>(),
|
||||||
|
sp.GetRequiredService<ILogger<LicenseService>>()));
|
||||||
|
|
||||||
services.AddSingleton<MainViewModel>();
|
services.AddSingleton<MainViewModel>();
|
||||||
services.AddSingleton<MainWindow>();
|
services.AddSingleton<MainWindow>();
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ using PSLauncher.App.Views;
|
|||||||
using PSLauncher.Core.Configuration;
|
using PSLauncher.Core.Configuration;
|
||||||
using PSLauncher.Core.Downloads;
|
using PSLauncher.Core.Downloads;
|
||||||
using PSLauncher.Core.Installations;
|
using PSLauncher.Core.Installations;
|
||||||
|
using PSLauncher.Core.Licensing;
|
||||||
using PSLauncher.Core.Manifests;
|
using PSLauncher.Core.Manifests;
|
||||||
using PSLauncher.Core.Process;
|
using PSLauncher.Core.Process;
|
||||||
using PSLauncher.Core.Updates;
|
using PSLauncher.Core.Updates;
|
||||||
@@ -26,8 +27,11 @@ public sealed partial class MainViewModel : ObservableObject
|
|||||||
private readonly IUpdateChecker _updateChecker;
|
private readonly IUpdateChecker _updateChecker;
|
||||||
private readonly IDownloadManager _downloadManager;
|
private readonly IDownloadManager _downloadManager;
|
||||||
private readonly IZipInstaller _zipInstaller;
|
private readonly IZipInstaller _zipInstaller;
|
||||||
|
private readonly ILicenseService _licenseService;
|
||||||
private readonly ILogger<MainViewModel> _logger;
|
private readonly ILogger<MainViewModel> _logger;
|
||||||
|
|
||||||
|
private LicenseValidationResponse? _license;
|
||||||
|
|
||||||
private RemoteManifest? _lastManifest;
|
private RemoteManifest? _lastManifest;
|
||||||
private CancellationTokenSource? _activeDownloadCts;
|
private CancellationTokenSource? _activeDownloadCts;
|
||||||
private VersionRowViewModel? _activeRow;
|
private VersionRowViewModel? _activeRow;
|
||||||
@@ -57,7 +61,18 @@ public sealed partial class MainViewModel : ObservableObject
|
|||||||
[ObservableProperty] private double _progressPercent;
|
[ObservableProperty] private double _progressPercent;
|
||||||
[ObservableProperty] private string? _progressDetail;
|
[ObservableProperty] private string? _progressDetail;
|
||||||
|
|
||||||
public string LicenseSummary => "License : non configurée (v0.4)";
|
public string LicenseSummary
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (_license is null) return "License : non configurée";
|
||||||
|
if (_license.Status == "valid")
|
||||||
|
return $"License : {_license.OwnerName} • exp. {_license.DownloadEntitlementUntil:dd/MM/yyyy}";
|
||||||
|
if (_license.Status == "expired")
|
||||||
|
return $"License expirée le {_license.DownloadEntitlementUntil:dd/MM/yyyy}";
|
||||||
|
return $"License : {_license.Status}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public string EmptyHint =>
|
public string EmptyHint =>
|
||||||
"Aucune version locale ni distante.\n" +
|
"Aucune version locale ni distante.\n" +
|
||||||
@@ -85,6 +100,7 @@ public sealed partial class MainViewModel : ObservableObject
|
|||||||
IUpdateChecker updateChecker,
|
IUpdateChecker updateChecker,
|
||||||
IDownloadManager downloadManager,
|
IDownloadManager downloadManager,
|
||||||
IZipInstaller zipInstaller,
|
IZipInstaller zipInstaller,
|
||||||
|
ILicenseService licenseService,
|
||||||
ILogger<MainViewModel> logger)
|
ILogger<MainViewModel> logger)
|
||||||
{
|
{
|
||||||
_registry = registry;
|
_registry = registry;
|
||||||
@@ -95,7 +111,13 @@ public sealed partial class MainViewModel : ObservableObject
|
|||||||
_updateChecker = updateChecker;
|
_updateChecker = updateChecker;
|
||||||
_downloadManager = downloadManager;
|
_downloadManager = downloadManager;
|
||||||
_zipInstaller = zipInstaller;
|
_zipInstaller = zipInstaller;
|
||||||
|
_licenseService = licenseService;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
|
||||||
|
// Charge la license depuis le cache (pas d'appel réseau au démarrage,
|
||||||
|
// ça reste rapide ; un refresh proactif arrive dès qu'on clique « Vérifier les MAJ »)
|
||||||
|
_license = _licenseService.GetCached();
|
||||||
|
|
||||||
RebuildList();
|
RebuildList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,10 +153,15 @@ public sealed partial class MainViewModel : ObservableObject
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Marque les rows distantes qui ont un DL en pause (partial + state.json présents)
|
// Marque les rows distantes qui ont un DL en pause (partial + state.json présents)
|
||||||
|
// et applique le filtre license
|
||||||
foreach (var r in rows.Where(r => r.IsRemoteOnly))
|
foreach (var r in rows.Where(r => r.IsRemoteOnly))
|
||||||
{
|
{
|
||||||
var st = _downloadManager.GetResumableState(r.Version);
|
var st = _downloadManager.GetResumableState(r.Version);
|
||||||
if (st is not null) r.ResumableBytes = st.DownloadedBytes;
|
if (st is not null) r.ResumableBytes = st.DownloadedBytes;
|
||||||
|
|
||||||
|
// License : la version est-elle téléchargeable selon notre entitlement ?
|
||||||
|
r.LicenseAllowsDownload = r.Remote is not null
|
||||||
|
&& _licenseService.CanDownloadVersion(_license, r.Remote);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Featured : plus haute installée, sinon plus haute distante
|
// Featured : plus haute installée, sinon plus haute distante
|
||||||
@@ -199,6 +226,20 @@ public sealed partial class MainViewModel : ObservableObject
|
|||||||
}
|
}
|
||||||
private bool CanCheckUpdates() => !IsBusy;
|
private bool CanCheckUpdates() => !IsBusy;
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
|
private async Task ActivateLicenseAsync()
|
||||||
|
{
|
||||||
|
var dialog = new Views.OnboardingDialog(_licenseService) { Owner = Application.Current.MainWindow };
|
||||||
|
dialog.ShowDialog();
|
||||||
|
if (dialog.LicenseActivated)
|
||||||
|
{
|
||||||
|
_license = _licenseService.GetCached();
|
||||||
|
OnPropertyChanged(nameof(LicenseSummary));
|
||||||
|
RebuildList();
|
||||||
|
}
|
||||||
|
await Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
private void OpenInstallRoot()
|
private void OpenInstallRoot()
|
||||||
{
|
{
|
||||||
@@ -245,21 +286,28 @@ public sealed partial class MainViewModel : ObservableObject
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// 1) Récupère release notes (best effort)
|
// Si reprise d'un DL interrompu, on saute la popup de release notes :
|
||||||
string notes = "_Aucune release note fournie._";
|
// l'utilisateur a déjà confirmé sa décision la première fois.
|
||||||
if (!string.IsNullOrEmpty(row.Remote.ReleaseNotesUrl))
|
var isResume = row.HasResumableDownload;
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
notes = await _manifestService.FetchReleaseNotesAsync(row.Remote.ReleaseNotesUrl, ct);
|
|
||||||
}
|
|
||||||
catch (Exception ex) { _logger.LogWarning(ex, "Release notes fetch failed"); notes = "_Release notes indisponibles._"; }
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2) Dialog de confirmation avec release notes
|
if (!isResume)
|
||||||
var dialog = new UpdateAvailableDialog(row.Remote, notes) { Owner = Application.Current.MainWindow };
|
{
|
||||||
dialog.ShowDialog();
|
// 1) Récupère release notes (best effort)
|
||||||
if (!dialog.DownloadRequested) return;
|
string notes = "_Aucune release note fournie._";
|
||||||
|
if (!string.IsNullOrEmpty(row.Remote.ReleaseNotesUrl))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
notes = await _manifestService.FetchReleaseNotesAsync(row.Remote.ReleaseNotesUrl, ct);
|
||||||
|
}
|
||||||
|
catch (Exception ex) { _logger.LogWarning(ex, "Release notes fetch failed"); notes = "_Release notes indisponibles._"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) Dialog de confirmation avec release notes
|
||||||
|
var dialog = new UpdateAvailableDialog(row.Remote, notes) { Owner = Application.Current.MainWindow };
|
||||||
|
dialog.ShowDialog();
|
||||||
|
if (!dialog.DownloadRequested) return;
|
||||||
|
}
|
||||||
|
|
||||||
// 3) Download
|
// 3) Download
|
||||||
row.State = VersionRowState.Downloading;
|
row.State = VersionRowState.Downloading;
|
||||||
|
|||||||
@@ -42,12 +42,20 @@ public sealed partial class VersionRowViewModel : ObservableObject
|
|||||||
[NotifyPropertyChangedFor(nameof(HasResumableDownload))]
|
[NotifyPropertyChangedFor(nameof(HasResumableDownload))]
|
||||||
private long _resumableBytes;
|
private long _resumableBytes;
|
||||||
|
|
||||||
|
[ObservableProperty]
|
||||||
|
[NotifyPropertyChangedFor(nameof(InstallButtonLabel))]
|
||||||
|
[NotifyPropertyChangedFor(nameof(LicenseAllowsInstall))]
|
||||||
|
[NotifyCanExecuteChangedFor(nameof(InstallCommand))]
|
||||||
|
private bool _licenseAllowsDownload = true;
|
||||||
|
|
||||||
public bool HasResumableDownload => ResumableBytes > 0;
|
public bool HasResumableDownload => ResumableBytes > 0;
|
||||||
|
public bool LicenseAllowsInstall => LicenseAllowsDownload;
|
||||||
|
|
||||||
public string InstallButtonLabel
|
public string InstallButtonLabel
|
||||||
{
|
{
|
||||||
get
|
get
|
||||||
{
|
{
|
||||||
|
if (!LicenseAllowsDownload) return "🔒 License insuffisante";
|
||||||
if (!HasResumableDownload) return "⬇ Installer";
|
if (!HasResumableDownload) return "⬇ Installer";
|
||||||
if (Remote is null || Remote.Download.SizeBytes <= 0) return "↻ Reprendre";
|
if (Remote is null || Remote.Download.SizeBytes <= 0) return "↻ Reprendre";
|
||||||
var pct = (double)ResumableBytes / Remote.Download.SizeBytes * 100.0;
|
var pct = (double)ResumableBytes / Remote.Download.SizeBytes * 100.0;
|
||||||
@@ -133,7 +141,7 @@ public sealed partial class VersionRowViewModel : ObservableObject
|
|||||||
|
|
||||||
[RelayCommand(CanExecute = nameof(CanInstall))]
|
[RelayCommand(CanExecute = nameof(CanInstall))]
|
||||||
private void Install() => InstallHandler?.Invoke(this);
|
private void Install() => InstallHandler?.Invoke(this);
|
||||||
private bool CanInstall() => State == VersionRowState.AvailableIdle;
|
private bool CanInstall() => State == VersionRowState.AvailableIdle && LicenseAllowsDownload;
|
||||||
|
|
||||||
[RelayCommand(CanExecute = nameof(CanUninstall))]
|
[RelayCommand(CanExecute = nameof(CanUninstall))]
|
||||||
private void Uninstall() => UninstallHandler?.Invoke(this);
|
private void Uninstall() => UninstallHandler?.Invoke(this);
|
||||||
|
|||||||
@@ -172,7 +172,10 @@
|
|||||||
Margin="0,0,12,0" />
|
Margin="0,0,12,0" />
|
||||||
<TextBlock Text="{Binding LicenseSummary}"
|
<TextBlock Text="{Binding LicenseSummary}"
|
||||||
Foreground="{StaticResource Brush.Text.Secondary}"
|
Foreground="{StaticResource Brush.Text.Secondary}"
|
||||||
VerticalAlignment="Center" />
|
VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||||
|
<Button Style="{StaticResource SecondaryButton}"
|
||||||
|
Content="🔑 Activer / changer"
|
||||||
|
Command="{Binding ActivateLicenseCommand}" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Grid>
|
</Grid>
|
||||||
</Border>
|
</Border>
|
||||||
|
|||||||
66
src/PSLauncher.App/Views/OnboardingDialog.xaml
Normal file
66
src/PSLauncher.App/Views/OnboardingDialog.xaml
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
<Window x:Class="PSLauncher.App.Views.OnboardingDialog"
|
||||||
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
Title="Activation PROSERVE Launcher"
|
||||||
|
Width="540" Height="420"
|
||||||
|
MinWidth="480" MinHeight="380"
|
||||||
|
WindowStartupLocation="CenterOwner"
|
||||||
|
ResizeMode="CanResize"
|
||||||
|
Background="{StaticResource Brush.Bg.Window}">
|
||||||
|
<Grid Margin="32,28">
|
||||||
|
<Grid.RowDefinitions>
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="*" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
</Grid.RowDefinitions>
|
||||||
|
|
||||||
|
<TextBlock Grid.Row="0" Text="Activer votre license"
|
||||||
|
FontSize="22" FontWeight="SemiBold"
|
||||||
|
Foreground="{StaticResource Brush.Text.Primary}" />
|
||||||
|
|
||||||
|
<TextBlock Grid.Row="1"
|
||||||
|
Text="Saisis la clé fournie par ASTERION. Elle te donne accès aux téléchargements jusqu'à la date de validité associée."
|
||||||
|
TextWrapping="Wrap"
|
||||||
|
Foreground="{StaticResource Brush.Text.Secondary}"
|
||||||
|
Margin="0,8,0,18" />
|
||||||
|
|
||||||
|
<TextBlock Grid.Row="2" Text="Clé de license"
|
||||||
|
FontSize="12" FontWeight="Bold"
|
||||||
|
Foreground="{StaticResource Brush.Text.Secondary}" />
|
||||||
|
<TextBox Grid.Row="3" x:Name="KeyBox"
|
||||||
|
Margin="0,6,0,16"
|
||||||
|
Padding="10,8"
|
||||||
|
FontFamily="Consolas" FontSize="14"
|
||||||
|
CharacterCasing="Upper"
|
||||||
|
Background="#1A1A20"
|
||||||
|
Foreground="{StaticResource Brush.Text.Primary}"
|
||||||
|
BorderBrush="{StaticResource Brush.Border}"
|
||||||
|
BorderThickness="1"
|
||||||
|
Text="PRSRV-XXXX-XXXX-XXXX-XXXX" />
|
||||||
|
|
||||||
|
<ScrollViewer Grid.Row="4" VerticalScrollBarVisibility="Auto">
|
||||||
|
<StackPanel x:Name="StatusPanel">
|
||||||
|
<TextBlock x:Name="StatusText"
|
||||||
|
TextWrapping="Wrap"
|
||||||
|
Foreground="{StaticResource Brush.Text.Secondary}" />
|
||||||
|
</StackPanel>
|
||||||
|
</ScrollViewer>
|
||||||
|
|
||||||
|
<StackPanel Grid.Row="5" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,18,0,0">
|
||||||
|
<Button Style="{StaticResource SecondaryButton}"
|
||||||
|
Content="Plus tard"
|
||||||
|
IsCancel="True"
|
||||||
|
Margin="0,0,12,0"
|
||||||
|
Click="OnLater" />
|
||||||
|
<Button Style="{StaticResource AccentButton}"
|
||||||
|
Content="Activer"
|
||||||
|
Padding="32,10"
|
||||||
|
IsDefault="True"
|
||||||
|
Click="OnActivate"
|
||||||
|
x:Name="ActivateButton" />
|
||||||
|
</StackPanel>
|
||||||
|
</Grid>
|
||||||
|
</Window>
|
||||||
91
src/PSLauncher.App/Views/OnboardingDialog.xaml.cs
Normal file
91
src/PSLauncher.App/Views/OnboardingDialog.xaml.cs
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Media;
|
||||||
|
using PSLauncher.Core.Licensing;
|
||||||
|
|
||||||
|
namespace PSLauncher.App.Views;
|
||||||
|
|
||||||
|
public partial class OnboardingDialog : Window
|
||||||
|
{
|
||||||
|
private readonly ILicenseService _licenseService;
|
||||||
|
|
||||||
|
public bool LicenseActivated { get; private set; }
|
||||||
|
|
||||||
|
public OnboardingDialog(ILicenseService licenseService, string? prefilledKey = null)
|
||||||
|
{
|
||||||
|
_licenseService = licenseService;
|
||||||
|
InitializeComponent();
|
||||||
|
if (!string.IsNullOrEmpty(prefilledKey)) KeyBox.Text = prefilledKey;
|
||||||
|
KeyBox.SelectAll();
|
||||||
|
KeyBox.Focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void OnActivate(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
var key = KeyBox.Text?.Trim().ToUpperInvariant() ?? string.Empty;
|
||||||
|
if (string.IsNullOrEmpty(key) || key.Contains("XXXX"))
|
||||||
|
{
|
||||||
|
ShowStatus("Saisis une clé valide au format PRSRV-XXXX-XXXX-XXXX-XXXX.", isError: true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ActivateButton.IsEnabled = false;
|
||||||
|
ShowStatus("Validation en cours…", isError: false);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var resp = await _licenseService.ValidateAsync(key, CancellationToken.None);
|
||||||
|
switch (resp.Status)
|
||||||
|
{
|
||||||
|
case "valid":
|
||||||
|
_licenseService.SaveCached(key, resp);
|
||||||
|
ShowStatus($"License activée ({resp.OwnerName}). Téléchargements autorisés jusqu'au {resp.DownloadEntitlementUntil:dd/MM/yyyy}.", isError: false);
|
||||||
|
LicenseActivated = true;
|
||||||
|
DialogResult = true;
|
||||||
|
Close();
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "expired":
|
||||||
|
_licenseService.SaveCached(key, resp); // on cache quand même pour permettre de lancer les versions installées
|
||||||
|
ShowStatus($"License expirée le {resp.DownloadEntitlementUntil:dd/MM/yyyy}. Tu peux toujours utiliser les versions déjà installées, mais plus en télécharger de nouvelles.", isError: true);
|
||||||
|
LicenseActivated = true;
|
||||||
|
DialogResult = true;
|
||||||
|
Close();
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "revoked":
|
||||||
|
ShowStatus("Cette license a été révoquée. Contacte ASTERION.", isError: true);
|
||||||
|
break;
|
||||||
|
case "machine_limit_exceeded":
|
||||||
|
ShowStatus(resp.Message ?? "Cette license a atteint son nombre maximum de machines.", isError: true);
|
||||||
|
break;
|
||||||
|
case "invalid":
|
||||||
|
default:
|
||||||
|
ShowStatus(resp.Message ?? "Clé de license inconnue.", isError: true);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ShowStatus($"Erreur de communication avec le serveur :\n{ex.Message}", isError: true);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ActivateButton.IsEnabled = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnLater(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
LicenseActivated = false;
|
||||||
|
DialogResult = false;
|
||||||
|
Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ShowStatus(string text, bool isError)
|
||||||
|
{
|
||||||
|
StatusText.Text = text;
|
||||||
|
StatusText.Foreground = isError
|
||||||
|
? new SolidColorBrush(Color.FromRgb(0xF8, 0x71, 0x71))
|
||||||
|
: (System.Windows.Media.Brush)Application.Current.FindResource("Brush.Text.Secondary");
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/PSLauncher.Core/Licensing/ILicenseService.cs
Normal file
14
src/PSLauncher.Core/Licensing/ILicenseService.cs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
using PSLauncher.Models;
|
||||||
|
|
||||||
|
namespace PSLauncher.Core.Licensing;
|
||||||
|
|
||||||
|
public interface ILicenseService
|
||||||
|
{
|
||||||
|
Task<LicenseValidationResponse> ValidateAsync(string licenseKey, CancellationToken ct);
|
||||||
|
LicenseValidationResponse? GetCached();
|
||||||
|
void SaveCached(string licenseKey, LicenseValidationResponse response);
|
||||||
|
void Clear();
|
||||||
|
bool HasLicense();
|
||||||
|
string GetMachineId();
|
||||||
|
bool CanDownloadVersion(LicenseValidationResponse? license, VersionManifest version);
|
||||||
|
}
|
||||||
253
src/PSLauncher.Core/Licensing/LicenseService.cs
Normal file
253
src/PSLauncher.Core/Licensing/LicenseService.cs
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NSec.Cryptography;
|
||||||
|
using PSLauncher.Core.Configuration;
|
||||||
|
using PSLauncher.Models;
|
||||||
|
|
||||||
|
namespace PSLauncher.Core.Licensing;
|
||||||
|
|
||||||
|
public sealed class LicenseService : ILicenseService
|
||||||
|
{
|
||||||
|
private const int CachedValidityDays = 7;
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||||
|
{
|
||||||
|
PropertyNameCaseInsensitive = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
private readonly Func<string> _serverBaseUrlProvider;
|
||||||
|
private readonly IConfigStore _configStore;
|
||||||
|
private readonly LocalConfig _config;
|
||||||
|
private readonly ILogger<LicenseService> _logger;
|
||||||
|
private readonly string? _serverPublicKeyHex;
|
||||||
|
|
||||||
|
public LicenseService(
|
||||||
|
HttpClient http,
|
||||||
|
Func<string> serverBaseUrlProvider,
|
||||||
|
IConfigStore configStore,
|
||||||
|
LocalConfig config,
|
||||||
|
ILogger<LicenseService> logger)
|
||||||
|
{
|
||||||
|
_http = http;
|
||||||
|
_serverBaseUrlProvider = serverBaseUrlProvider;
|
||||||
|
_configStore = configStore;
|
||||||
|
_config = config;
|
||||||
|
_logger = logger;
|
||||||
|
_serverPublicKeyHex = TryReadEmbeddedPublicKey();
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool HasLicense() => !string.IsNullOrEmpty(_config.License.EncryptedKey);
|
||||||
|
|
||||||
|
public string GetMachineId()
|
||||||
|
{
|
||||||
|
// Combine MachineGuid + nom utilisateur, hash SHA-256 → ID stable, sans leak du GUID brut
|
||||||
|
string raw;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography");
|
||||||
|
raw = (key?.GetValue("MachineGuid") as string) ?? Environment.MachineName;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
raw = Environment.MachineName;
|
||||||
|
}
|
||||||
|
var input = $"{raw}|{Environment.UserName}";
|
||||||
|
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(input));
|
||||||
|
return Convert.ToHexString(hash).ToLowerInvariant();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<LicenseValidationResponse> ValidateAsync(string licenseKey, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var url = TrimSlash(_serverBaseUrlProvider()) + "/license/validate";
|
||||||
|
var req = new LicenseValidationRequest
|
||||||
|
{
|
||||||
|
LicenseKey = licenseKey,
|
||||||
|
MachineId = GetMachineId(),
|
||||||
|
MachineLabel = $"{Environment.MachineName} / {Environment.UserName}",
|
||||||
|
LauncherVersion = GetLauncherVersion(),
|
||||||
|
};
|
||||||
|
|
||||||
|
_logger.LogInformation("Validating license at {Url} (key {KeyHint}…)", url, licenseKey.Length >= 8 ? licenseKey[..8] : licenseKey);
|
||||||
|
|
||||||
|
using var httpReq = new HttpRequestMessage(HttpMethod.Post, url);
|
||||||
|
httpReq.Content = JsonContent.Create(req);
|
||||||
|
using var resp = await _http.SendAsync(httpReq, ct).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var bodyText = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||||
|
LicenseValidationResponse? parsed;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
parsed = JsonSerializer.Deserialize<LicenseValidationResponse>(bodyText, JsonOptions);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"Réponse serveur invalide : {ex.Message}\n{bodyText}", ex);
|
||||||
|
}
|
||||||
|
if (parsed is null)
|
||||||
|
throw new InvalidOperationException("Réponse serveur vide");
|
||||||
|
|
||||||
|
// Statuts d'erreur applicatifs renvoyés en 4xx avec un body décrivant l'erreur
|
||||||
|
if (!resp.IsSuccessStatusCode && string.IsNullOrEmpty(parsed.Status))
|
||||||
|
{
|
||||||
|
parsed.Status = "invalid";
|
||||||
|
parsed.Message ??= $"HTTP {(int)resp.StatusCode}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vérification de la signature serveur (si on a la clé publique embarquée et une signature)
|
||||||
|
if (!string.IsNullOrEmpty(_serverPublicKeyHex) && !string.IsNullOrEmpty(parsed.Signature))
|
||||||
|
{
|
||||||
|
if (!VerifySignature(parsed, parsed.Signature, _serverPublicKeyHex!))
|
||||||
|
{
|
||||||
|
_logger.LogError("License response signature INVALID — possible MITM");
|
||||||
|
throw new InvalidOperationException("Réponse serveur non authentifiée (signature invalide)");
|
||||||
|
}
|
||||||
|
_logger.LogDebug("License response signature OK");
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LicenseValidationResponse? GetCached()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(_config.License.EncryptedKey)) return null;
|
||||||
|
if (_config.License.LastValidationAt is null) return null;
|
||||||
|
|
||||||
|
// Cache offline valide 7 jours après la dernière validation réussie
|
||||||
|
var age = DateTime.UtcNow - _config.License.LastValidationAt.Value;
|
||||||
|
if (age.TotalDays > CachedValidityDays) return null;
|
||||||
|
|
||||||
|
return new LicenseValidationResponse
|
||||||
|
{
|
||||||
|
Status = _config.License.CachedEntitlementUntil >= DateTime.UtcNow ? "valid" : "expired",
|
||||||
|
OwnerName = _config.License.CachedOwnerName,
|
||||||
|
DownloadEntitlementUntil = _config.License.CachedEntitlementUntil,
|
||||||
|
ServerTime = _config.License.LastValidationAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SaveCached(string licenseKey, LicenseValidationResponse response)
|
||||||
|
{
|
||||||
|
var encrypted = ProtectKey(licenseKey);
|
||||||
|
_config.License.EncryptedKey = encrypted;
|
||||||
|
_config.License.LastValidationAt = DateTime.UtcNow;
|
||||||
|
_config.License.CachedOwnerName = response.OwnerName;
|
||||||
|
_config.License.CachedEntitlementUntil = response.DownloadEntitlementUntil;
|
||||||
|
_configStore.Save(_config);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Clear()
|
||||||
|
{
|
||||||
|
_config.License = new LicenseConfig();
|
||||||
|
_configStore.Save(_config);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool CanDownloadVersion(LicenseValidationResponse? license, VersionManifest version)
|
||||||
|
{
|
||||||
|
if (license is null) return false;
|
||||||
|
return license.CanDownload(version);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string? GetDecryptedKey()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(_config.License.EncryptedKey)) return null;
|
||||||
|
try { return UnprotectKey(_config.License.EncryptedKey); }
|
||||||
|
catch (Exception ex) { _logger.LogWarning(ex, "Failed to decrypt cached license key"); return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- DPAPI -----
|
||||||
|
|
||||||
|
private static string ProtectKey(string clearKey)
|
||||||
|
{
|
||||||
|
var data = Encoding.UTF8.GetBytes(clearKey);
|
||||||
|
var protectedBytes = ProtectedData.Protect(data, optionalEntropy: null, scope: DataProtectionScope.CurrentUser);
|
||||||
|
return Convert.ToBase64String(protectedBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string UnprotectKey(string base64)
|
||||||
|
{
|
||||||
|
var protectedBytes = Convert.FromBase64String(base64);
|
||||||
|
var data = ProtectedData.Unprotect(protectedBytes, optionalEntropy: null, scope: DataProtectionScope.CurrentUser);
|
||||||
|
return Encoding.UTF8.GetString(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- Signature -----
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Encode canonical du payload en JSON sans le champ 'signature', exactement comme côté PHP
|
||||||
|
/// (Crypto::canonicalJson : JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE).
|
||||||
|
/// </summary>
|
||||||
|
public static byte[] CanonicalBytesFor(LicenseValidationResponse response)
|
||||||
|
{
|
||||||
|
// On reconstruit un dictionnaire ordonné comme côté PHP, sans signature
|
||||||
|
var dict = new Dictionary<string, object?>
|
||||||
|
{
|
||||||
|
["status"] = response.Status,
|
||||||
|
["licenseId"] = response.LicenseId,
|
||||||
|
["ownerName"] = response.OwnerName,
|
||||||
|
["issuedAt"] = FormatDateAtom(response.IssuedAt),
|
||||||
|
["downloadEntitlementUntil"] = FormatDateAtom(response.DownloadEntitlementUntil),
|
||||||
|
["maxMachines"] = response.MaxMachines,
|
||||||
|
["serverTime"] = FormatDateAtom(response.ServerTime),
|
||||||
|
};
|
||||||
|
var opts = new JsonSerializerOptions
|
||||||
|
{
|
||||||
|
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
|
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
||||||
|
};
|
||||||
|
return JsonSerializer.SerializeToUtf8Bytes(dict, opts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? FormatDateAtom(DateTime? d) =>
|
||||||
|
d?.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz");
|
||||||
|
|
||||||
|
public static bool VerifySignature(LicenseValidationResponse response, string base64Signature, string publicKeyHex)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var alg = SignatureAlgorithm.Ed25519;
|
||||||
|
var pkBytes = Convert.FromHexString(publicKeyHex);
|
||||||
|
var pk = PublicKey.Import(alg, pkBytes, KeyBlobFormat.RawPublicKey);
|
||||||
|
var sig = Convert.FromBase64String(base64Signature);
|
||||||
|
var payload = CanonicalBytesFor(response);
|
||||||
|
return alg.Verify(pk, payload, sig);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- Public key embarquée -----
|
||||||
|
|
||||||
|
private static string? TryReadEmbeddedPublicKey()
|
||||||
|
{
|
||||||
|
var asm = Assembly.GetExecutingAssembly();
|
||||||
|
foreach (var name in asm.GetManifestResourceNames())
|
||||||
|
{
|
||||||
|
if (name.EndsWith("server-pubkey.txt", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
using var s = asm.GetManifestResourceStream(name);
|
||||||
|
if (s is null) continue;
|
||||||
|
using var sr = new StreamReader(s);
|
||||||
|
var hex = sr.ReadToEnd().Trim();
|
||||||
|
if (hex.StartsWith("#") || string.IsNullOrEmpty(hex)) return null; // placeholder/ commenté
|
||||||
|
return hex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetLauncherVersion()
|
||||||
|
{
|
||||||
|
var asm = Assembly.GetExecutingAssembly();
|
||||||
|
return asm.GetName().Version?.ToString() ?? "0.0.0";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string TrimSlash(string s) => s.TrimEnd('/');
|
||||||
|
}
|
||||||
@@ -10,10 +10,16 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.2" />
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.2" />
|
||||||
<PackageReference Include="Polly" Version="8.4.2" />
|
<PackageReference Include="Polly" Version="8.4.2" />
|
||||||
|
<PackageReference Include="NSec.Cryptography" Version="24.4.0" />
|
||||||
|
<PackageReference Include="System.Security.Cryptography.ProtectedData" Version="8.0.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\PSLauncher.Models\PSLauncher.Models.csproj" />
|
<ProjectReference Include="..\PSLauncher.Models\PSLauncher.Models.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<EmbeddedResource Include="Resources\server-pubkey.txt" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
6
src/PSLauncher.Core/Resources/server-pubkey.txt
Normal file
6
src/PSLauncher.Core/Resources/server-pubkey.txt
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
# Clé publique Ed25519 du serveur PS_Launcher.
|
||||||
|
# Génère-la via : `php tools/generate-keypair.php` sur le serveur OVH.
|
||||||
|
# Recopie ici les 64 hex chars de public_key_hex (rien d'autre, pas de commentaires sur la même ligne),
|
||||||
|
# puis recompile le launcher.
|
||||||
|
# Tant que ce fichier commence par '#' ou est vide, la vérification de signature
|
||||||
|
# côté client est skippée (le launcher accepte la réponse serveur sans vérifier).
|
||||||
52
src/PSLauncher.Models/License.cs
Normal file
52
src/PSLauncher.Models/License.cs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace PSLauncher.Models;
|
||||||
|
|
||||||
|
public sealed class LicenseValidationResponse
|
||||||
|
{
|
||||||
|
[JsonPropertyName("status")]
|
||||||
|
public string Status { get; set; } = "invalid";
|
||||||
|
|
||||||
|
[JsonPropertyName("licenseId")]
|
||||||
|
public string? LicenseId { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("ownerName")]
|
||||||
|
public string? OwnerName { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("issuedAt")]
|
||||||
|
public DateTime? IssuedAt { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("downloadEntitlementUntil")]
|
||||||
|
public DateTime? DownloadEntitlementUntil { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("maxMachines")]
|
||||||
|
public int? MaxMachines { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("serverTime")]
|
||||||
|
public DateTime? ServerTime { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("message")]
|
||||||
|
public string? Message { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("signature")]
|
||||||
|
public string? Signature { get; set; }
|
||||||
|
|
||||||
|
public bool IsValid => Status == "valid";
|
||||||
|
public bool IsExpired => Status == "expired";
|
||||||
|
|
||||||
|
public bool CanDownload(VersionManifest version)
|
||||||
|
{
|
||||||
|
if (!IsValid && !IsExpired) return false;
|
||||||
|
if (DownloadEntitlementUntil is null) return false;
|
||||||
|
if (version.MinLicenseDate is null) return true; // pas de minimum imposé
|
||||||
|
return DownloadEntitlementUntil >= version.MinLicenseDate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class LicenseValidationRequest
|
||||||
|
{
|
||||||
|
[JsonPropertyName("licenseKey")] public string LicenseKey { get; set; } = string.Empty;
|
||||||
|
[JsonPropertyName("machineId")] public string MachineId { get; set; } = string.Empty;
|
||||||
|
[JsonPropertyName("machineLabel")] public string? MachineLabel { get; set; }
|
||||||
|
[JsonPropertyName("launcherVersion")] public string LauncherVersion { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user