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:
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('/');
|
||||
}
|
||||
Reference in New Issue
Block a user