v0.6 + v1.0: HMAC download URLs, launcher self-update, Inno Setup installer

Three deliverables shipped together so the next deployment cycle has a
clean distribution story.

(1) Auto-update of the launcher itself
---------------------------------------
- Models: RemoteManifest gains an optional `launcher` section
  (LauncherInfo: version, minRequired, download {url,size,sha256},
   releaseNotesUrl). Server-side, sign-manifest.php passes it through
  unchanged; admins edit versions.json with the new launcher entry +
  upload PSLauncher-X.Y.Z.exe to /builds/launcher/.
- Core: ILauncherSelfUpdater compares assembly version against
  manifest.launcher.version using the existing SemVer parser, and
  reuses DownloadManager (Range/resume/sha256 already proven on the
  game ZIPs) to download the new exe into
  %LocalAppData%/PSLauncher/selfupdate/.
- New project PSLauncher.Updater (~34 MB self-contained console exe):
  spawned by the main app with --target / --source / --pid / --launch.
  Waits for the main process to exit (or for the file lock to release),
  backs up the current exe to .bak, copies the new file in place, and
  restarts. .bak survives the swap so the user can roll back manually.
- App.csproj now declares Version=0.5.0 — currently shipped baseline.
  PSLauncher.App.csproj sets a fixed AssemblyVersion so reflection-based
  comparison works deterministically.
- MainViewModel.PromptLauncherUpdate: dialog after CheckForUpdates if
  the manifest advertises a newer launcher. Download with progress in
  the existing footer, then Application.Shutdown() so the Updater can
  do its job.

(2) Inno Setup installer
------------------------
installer/PSLauncher.iss + build-installer.ps1 produce a single
PSLauncher-Setup-X.Y.Z.exe (~80 MB) that installs into
Program Files\ASTERION VR\PSLauncher\, drops both PSLauncher.exe and
PSLauncher.Updater.exe side by side (the updater MUST live next to
the target), creates Start Menu + optional Desktop shortcuts, and
registers a clean uninstall entry. The user's %LocalAppData%
(license, logs, cache) is intentionally untouched on uninstall — same
license survives a reinstall.

build-installer.ps1 chains dotnet publish for both projects and ISCC
in one command. README explains the bump-version workflow.

(3) HMAC-signed download URLs
-----------------------------
- New PHP route GET /api/download-url/{version} (Authorization: Bearer
  <licenseKey> or ?key=...). Validates the license, checks
  download_entitlement_until >= minLicenseDate of the version, and
  returns a HMAC-signed URL (path|exp|licId, hash_hmac SHA-256, valid
  1 h) + sha256 + sizeBytes for verification.
- /builds/.htaccess routes every *.zip request to gate.php. gate.php
  validates exp, lic, sig (constant-time hash_equals), then streams
  the file with Range: support so the launcher's resume keeps working.
  Audit log gets a download_url_issued entry per request.
- Client-side wired transparently: LicenseService gains
  GetSignedDownloadUrlAsync(version) that GETs the endpoint with the
  decrypted license key from DPAPI. MainViewModel calls it before
  every download; if the endpoint returns 404/401/network-error, the
  client falls back to the manifest's plain download.url (graceful
  degradation for setups that haven't deployed gate.php yet).

Note on PHP streaming for 14 GB ZIPs: gate.php uses set_time_limit(0)
+ ignore_user_abort(true) + 1 MiB chunked fread with periodic flush.
Works on OVH mutualisé but holds a PHP-FPM slot for the duration. If
parallel downloads scale past a few clients, switch to
mod_xsendfile or migrate /builds/ to Cloudflare R2 with native
S3-presigned URLs and remove the gate entirely.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-02 09:38:13 +02:00
parent b10a3fbabf
commit b7de228bc9
20 changed files with 798 additions and 2 deletions

View File

@@ -97,6 +97,7 @@ public partial class App : Application
services.AddSingleton<IDownloadManager, DownloadManager>();
services.AddSingleton<IUpdateChecker, UpdateChecker>();
services.AddSingleton<ILauncherSelfUpdater, LauncherSelfUpdater>();
services.AddSingleton<ILicenseService>(sp =>
new LicenseService(

View File

@@ -12,6 +12,9 @@
<ApplicationIcon></ApplicationIcon>
<AssemblyName>PSLauncher</AssemblyName>
<RootNamespace>PSLauncher.App</RootNamespace>
<Version>0.5.0</Version>
<AssemblyVersion>0.5.0.0</AssemblyVersion>
<FileVersion>0.5.0.0</FileVersion>
<!-- Single-file self-contained publish profile (used by `dotnet publish`) -->
<PublishSingleFile>true</PublishSingleFile>

View File

@@ -30,6 +30,7 @@ public sealed partial class MainViewModel : ObservableObject
private readonly IDownloadManager _downloadManager;
private readonly IZipInstaller _zipInstaller;
private readonly ILicenseService _licenseService;
private readonly ILauncherSelfUpdater _selfUpdater;
private readonly IToastService _toastService;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<MainViewModel> _logger;
@@ -158,6 +159,7 @@ public sealed partial class MainViewModel : ObservableObject
IDownloadManager downloadManager,
IZipInstaller zipInstaller,
ILicenseService licenseService,
ILauncherSelfUpdater selfUpdater,
IToastService toastService,
IServiceProvider serviceProvider,
ILogger<MainViewModel> logger)
@@ -171,6 +173,7 @@ public sealed partial class MainViewModel : ObservableObject
_downloadManager = downloadManager;
_zipInstaller = zipInstaller;
_licenseService = licenseService;
_selfUpdater = selfUpdater;
_toastService = toastService;
_serviceProvider = serviceProvider;
_logger = logger;
@@ -282,6 +285,13 @@ public sealed partial class MainViewModel : ObservableObject
_lastManifest = result.Manifest;
RebuildList();
// Détection MAJ du launcher lui-même (présent en `manifest.launcher`).
// Lancée en arrière-plan pour ne pas bloquer l'affichage des résultats produit.
if (result.Manifest?.Launcher is { } launcher && _selfUpdater.IsNewerThanCurrent(launcher))
{
_ = Application.Current.Dispatcher.BeginInvoke(() => PromptLauncherUpdate(launcher));
}
if (result.IsLatestNewerThanInstalled && result.LatestRemote is not null)
StatusMessage = $"Nouvelle version disponible : v{result.LatestRemote.Version}";
else if (result.LatestRemote is not null)
@@ -301,6 +311,40 @@ public sealed partial class MainViewModel : ObservableObject
}
private bool CanCheckUpdates() => !IsBusy;
private async void PromptLauncherUpdate(LauncherInfo launcher)
{
try
{
var dialog = new Views.LauncherUpdateDialog(launcher, _selfUpdater.GetCurrentVersion())
{
Owner = Application.Current.MainWindow
};
dialog.ShowDialog();
if (!dialog.UpdateRequested) return;
IsBusy = true;
StatusMessage = "Téléchargement du nouveau launcher…";
var progress = new Progress<DownloadProgress>(p =>
{
if (p.TotalBytes > 0) ProgressPercent = (double)p.BytesDownloaded / p.TotalBytes * 100.0;
ProgressDetail = $"⬇ Launcher v{launcher.Version} : {FormatSize(p.BytesDownloaded)} / {FormatSize(p.TotalBytes)}";
});
await _selfUpdater.DownloadAndApplyAsync(launcher, progress, CancellationToken.None);
StatusMessage = "Mise à jour du launcher en cours… le launcher va se relancer.";
await Task.Delay(800); // laisse le temps au toast / message de s'afficher
Application.Current.Shutdown();
}
catch (Exception ex)
{
_logger.LogError(ex, "Self-update failed");
MessageBox.Show($"Mise à jour du launcher échouée :\n\n{ex.Message}",
"Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
StatusMessage = $"Erreur self-update : {ex.Message}";
IsBusy = false;
}
}
[RelayCommand]
private void OpenSettings()
{
@@ -427,9 +471,13 @@ public sealed partial class MainViewModel : ObservableObject
if (!dialog.DownloadRequested) return;
}
// 3) Download
// 3) Download — tente d'abord d'obtenir une URL HMAC-signée par le serveur
// (endpoint /api/download-url/{version}). Fallback transparent sur l'URL
// publique du manifest si le serveur n'a pas le endpoint configuré.
row.State = VersionRowState.Downloading;
var url = new Uri(row.Remote.Download.Url);
var signed = await _licenseService.GetSignedDownloadUrlAsync(row.Version, ct);
var urlString = signed ?? row.Remote.Download.Url;
var url = new Uri(urlString);
var job = new DownloadJob(row.Version, url, row.Remote.Download.SizeBytes, row.Remote.Download.Sha256);
var dlProgress = new Progress<DownloadProgress>(p => UpdateDlProgress(row, p));
StatusMessage = $"Téléchargement v{row.Version}…";

View File

@@ -0,0 +1,53 @@
<Window x:Class="PSLauncher.App.Views.LauncherUpdateDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Mise à jour du launcher"
Width="500" Height="320"
ResizeMode="NoResize"
WindowStartupLocation="CenterOwner"
Background="{StaticResource Brush.Bg.Window}">
<Grid Margin="32,28">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
Text="Mise à jour du launcher disponible"
FontSize="20" FontWeight="SemiBold"
Foreground="{StaticResource Brush.Text.Primary}" />
<StackPanel Grid.Row="1" Margin="0,12,0,0">
<TextBlock x:Name="VersionText"
FontSize="14"
Foreground="{StaticResource Brush.Text.Primary}" />
<TextBlock x:Name="SizeText"
FontSize="12"
Foreground="{StaticResource Brush.Text.Secondary}"
Margin="0,4,0,0" />
</StackPanel>
<Border Grid.Row="2" Background="{StaticResource Brush.Bg.Card}"
BorderBrush="{StaticResource Brush.Border}" BorderThickness="1"
CornerRadius="6" Padding="16" Margin="0,16,0,0">
<TextBlock Text="Le launcher va se mettre à jour : il téléchargera le nouveau binaire, se fermera, sera remplacé, puis se relancera automatiquement. Cela prend quelques secondes."
Foreground="{StaticResource Brush.Text.Secondary}"
TextWrapping="Wrap" />
</Border>
<StackPanel Grid.Row="3" 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="⬇ Mettre à jour"
Padding="32,8"
IsDefault="True"
Click="OnUpdate" />
</StackPanel>
</Grid>
</Window>

View File

@@ -0,0 +1,41 @@
using System.Windows;
using PSLauncher.Models;
namespace PSLauncher.App.Views;
public partial class LauncherUpdateDialog : Window
{
public bool UpdateRequested { get; private set; }
public LauncherUpdateDialog(LauncherInfo info, string currentVersion)
{
InitializeComponent();
VersionText.Text = $"v{currentVersion} → v{info.Version}";
SizeText.Text = info.Download.SizeBytes > 0
? $"Taille : {FormatSize(info.Download.SizeBytes)}"
: "";
}
private void OnUpdate(object sender, RoutedEventArgs e)
{
UpdateRequested = true;
DialogResult = true;
Close();
}
private void OnLater(object sender, RoutedEventArgs e)
{
UpdateRequested = false;
DialogResult = false;
Close();
}
private static string FormatSize(long bytes)
{
if (bytes <= 0) return "—";
string[] units = { "o", "Ko", "Mo", "Go" };
double v = bytes; int u = 0;
while (v >= 1024 && u < units.Length - 1) { v /= 1024; u++; }
return $"{v:0.#} {units[u]}";
}
}

View File

@@ -11,4 +11,11 @@ public interface ILicenseService
bool HasLicense();
string GetMachineId();
bool CanDownloadVersion(LicenseValidationResponse? license, VersionManifest version);
/// <summary>
/// Demande au serveur une URL HMAC-signée valide 1 h pour le ZIP de cette version.
/// Retourne null si l'endpoint n'est pas dispo / pas configuré (ancien serveur),
/// auquel cas l'appelant retombe sur l'URL publique du manifest.
/// </summary>
Task<string?> GetSignedDownloadUrlAsync(string version, CancellationToken ct);
}

View File

@@ -153,6 +153,33 @@ public sealed class LicenseService : ILicenseService
return license.CanDownload(version);
}
public async Task<string?> GetSignedDownloadUrlAsync(string version, CancellationToken ct)
{
var key = GetDecryptedKey();
if (string.IsNullOrEmpty(key)) return null;
var url = TrimSlash(_serverBaseUrlProvider()) + "/download-url/" + version;
try
{
using var req = new HttpRequestMessage(HttpMethod.Get, url);
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", key);
using var resp = await _http.SendAsync(req, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode)
{
_logger.LogInformation("Signed URL endpoint returned {Status} — falling back to public URL", (int)resp.StatusCode);
return null;
}
var body = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(body);
return doc.RootElement.TryGetProperty("url", out var u) ? u.GetString() : null;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Signed URL fetch failed, falling back to public URL");
return null;
}
}
public string? GetDecryptedKey()
{
if (string.IsNullOrEmpty(_config.License.EncryptedKey)) return null;

View File

@@ -0,0 +1,20 @@
using PSLauncher.Models;
namespace PSLauncher.Core.Updates;
public interface ILauncherSelfUpdater
{
/// <summary>Compare la version courante avec celle annoncée dans le manifest.</summary>
bool IsNewerThanCurrent(LauncherInfo launcher);
string GetCurrentVersion();
/// <summary>
/// Télécharge le nouveau binaire dans un dossier de staging et déclenche l'updater.
/// L'application courante doit s'arrêter rapidement après le retour de cette méthode.
/// </summary>
Task<bool> DownloadAndApplyAsync(
LauncherInfo launcher,
IProgress<DownloadProgress>? progress,
CancellationToken ct);
}

View File

@@ -0,0 +1,106 @@
using System.Diagnostics;
using System.Reflection;
using Microsoft.Extensions.Logging;
using PSLauncher.Core.Configuration;
using PSLauncher.Core.Downloads;
using PSLauncher.Core.Installations;
using PSLauncher.Models;
using SysProcess = System.Diagnostics.Process;
namespace PSLauncher.Core.Updates;
public sealed class LauncherSelfUpdater : ILauncherSelfUpdater
{
private readonly IDownloadManager _downloadManager;
private readonly IConfigStore _configStore;
private readonly ILogger<LauncherSelfUpdater> _logger;
public LauncherSelfUpdater(
IDownloadManager downloadManager,
IConfigStore configStore,
ILogger<LauncherSelfUpdater> logger)
{
_downloadManager = downloadManager;
_configStore = configStore;
_logger = logger;
}
public string GetCurrentVersion()
{
var asm = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
var v = asm.GetName().Version;
return v is null ? "0.0.0" : $"{v.Major}.{v.Minor}.{v.Build}";
}
public bool IsNewerThanCurrent(LauncherInfo launcher)
{
var current = SemVer.Parse(GetCurrentVersion());
var remote = SemVer.Parse(launcher.Version);
return remote.CompareTo(current) > 0;
}
public async Task<bool> DownloadAndApplyAsync(
LauncherInfo launcher,
IProgress<DownloadProgress>? progress,
CancellationToken ct)
{
// 1. Localise le PSLauncher.exe en cours d'exécution
var processModule = SysProcess.GetCurrentProcess().MainModule
?? throw new InvalidOperationException("Cannot locate current process module");
var targetExe = processModule.FileName!;
var installDir = Path.GetDirectoryName(targetExe)!;
_logger.LogInformation("Self-update target: {Path}", targetExe);
// 2. Télécharge le nouveau exe dans le cache
var stagingDir = Path.Combine(_configStore.ConfigDirectory, "selfupdate");
Directory.CreateDirectory(stagingDir);
var downloadJob = new DownloadJob(
$"launcher-{launcher.Version}",
new Uri(launcher.Download.Url),
launcher.Download.SizeBytes,
launcher.Download.Sha256);
var downloadedPath = await _downloadManager.DownloadAsync(downloadJob, progress, ct).ConfigureAwait(false);
_logger.LogInformation("New launcher downloaded to {Path}", downloadedPath);
// 3. Localise PSLauncher.Updater.exe (à côté du target)
var updaterPath = Path.Combine(installDir, "PSLauncher.Updater.exe");
if (!File.Exists(updaterPath))
{
// Fallback : tente de copier l'updater depuis le dossier d'install vers un staging
// si jamais il a été supprimé. Pour la v1, on demande à l'utilisateur de réinstaller.
throw new FileNotFoundException(
"PSLauncher.Updater.exe est manquant à côté de PSLauncher.exe. " +
"Réinstalle le launcher depuis l'installeur officiel.",
updaterPath);
}
// 4. Copie le .new dans le staging dir si downloaded est ailleurs
var newPath = Path.Combine(stagingDir, $"PSLauncher-{launcher.Version}.exe");
if (!string.Equals(downloadedPath, newPath, StringComparison.OrdinalIgnoreCase))
{
if (File.Exists(newPath)) File.Delete(newPath);
File.Move(downloadedPath, newPath);
}
// 5. Lance l'updater détaché
var pid = Environment.ProcessId;
var psi = new ProcessStartInfo
{
FileName = updaterPath,
UseShellExecute = false,
CreateNoWindow = true,
};
psi.ArgumentList.Add($"--target={targetExe}");
psi.ArgumentList.Add($"--source={newPath}");
psi.ArgumentList.Add($"--pid={pid}");
psi.ArgumentList.Add("--launch");
_logger.LogInformation("Spawning updater {Updater} (target={Target}, source={Source}, pid={Pid})",
updaterPath, targetExe, newPath, pid);
SysProcess.Start(psi);
return true; // l'appelant doit Application.Current.Shutdown() après
}
}

View File

@@ -24,6 +24,24 @@ public sealed class RemoteManifest
[JsonPropertyName("signature")]
public string? Signature { get; set; }
[JsonPropertyName("launcher")]
public LauncherInfo? Launcher { get; set; }
}
public sealed class LauncherInfo
{
[JsonPropertyName("version")]
public string Version { get; set; } = string.Empty;
[JsonPropertyName("minRequired")]
public string? MinRequired { get; set; }
[JsonPropertyName("download")]
public DownloadDescriptor Download { get; set; } = new();
[JsonPropertyName("releaseNotesUrl")]
public string? ReleaseNotesUrl { get; set; }
}
public sealed class VersionManifest

View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<AssemblyName>PSLauncher.Updater</AssemblyName>
<RootNamespace>PSLauncher.Updater</RootNamespace>
<Version>0.5.0</Version>
<!-- Single-file self-contained pour le publish (~10 Mo) -->
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,136 @@
using System.Diagnostics;
namespace PSLauncher.Updater;
/// <summary>
/// Mini exe qui remplace le launcher principal (qui ne peut pas s'auto-écraser pendant qu'il tourne).
///
/// Args attendus :
/// --target=&lt;chemin_complet_de_PSLauncher.exe&gt;
/// --source=&lt;chemin_du_nouveau_PSLauncher.exe&gt;
/// [--launch] : relance PSLauncher.exe une fois la copie faite
/// [--pid=&lt;PID&gt;] : attend que ce process se termine avant de copier
///
/// Workflow :
/// 1. Si --pid fourni, attend la sortie du process.
/// 2. Sinon, attend que le fichier target soit déverrouillé (poll 250 ms).
/// 3. Backup target → target.bak (au cas où).
/// 4. Copie source → target.
/// 5. Optionnellement relance target.
/// 6. Supprime source (le .new) puis target.bak après 30 s.
/// </summary>
internal static class Program
{
[STAThread]
private static int Main(string[] args)
{
try
{
var opts = ParseArgs(args);
if (string.IsNullOrEmpty(opts.Target) || string.IsNullOrEmpty(opts.Source))
{
Console.Error.WriteLine("Usage: PSLauncher.Updater --target=<exe> --source=<new.exe> [--launch] [--pid=N]");
return 2;
}
// 1. Attendre la sortie du launcher principal
if (opts.Pid is int pid)
{
try
{
var proc = Process.GetProcessById(pid);
proc.WaitForExit(60_000);
}
catch { /* déjà mort, OK */ }
}
// 2. Attendre que le target soit déverrouillé
var deadline = DateTime.UtcNow.AddSeconds(60);
while (DateTime.UtcNow < deadline)
{
if (!File.Exists(opts.Target)) break;
try
{
using var fs = File.Open(opts.Target, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
break;
}
catch (IOException)
{
Thread.Sleep(250);
}
}
// 3. Backup
var backup = opts.Target + ".bak";
try { if (File.Exists(backup)) File.Delete(backup); } catch { }
try { if (File.Exists(opts.Target)) File.Move(opts.Target, backup); } catch (Exception ex)
{
Console.Error.WriteLine($"Backup failed: {ex.Message}");
return 3;
}
// 4. Copy new file in place
try
{
File.Copy(opts.Source, opts.Target, overwrite: true);
}
catch (Exception ex)
{
Console.Error.WriteLine($"Copy failed: {ex.Message}");
// Tente la restauration
try { if (File.Exists(backup)) File.Move(backup, opts.Target, overwrite: true); } catch { }
return 4;
}
// 5. Relance
if (opts.Launch)
{
try
{
Process.Start(new ProcessStartInfo
{
FileName = opts.Target,
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(opts.Target)!,
});
}
catch (Exception ex)
{
Console.Error.WriteLine($"Relaunch failed: {ex.Message}");
}
}
// 6. Cleanup différé (le .new + .bak après 30s, en background détaché)
try { File.Delete(opts.Source); } catch { }
// .bak laissé sur place : si le nouveau exe plante au lancement, l'utilisateur
// peut renommer .bak → .exe pour récupérer l'ancien.
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Updater fatal: {ex}");
return 1;
}
}
private sealed class Options
{
public string? Target { get; set; }
public string? Source { get; set; }
public bool Launch { get; set; }
public int? Pid { get; set; }
}
private static Options ParseArgs(string[] args)
{
var o = new Options();
foreach (var a in args)
{
if (a.StartsWith("--target=", StringComparison.OrdinalIgnoreCase)) o.Target = a["--target=".Length..];
else if (a.StartsWith("--source=", StringComparison.OrdinalIgnoreCase)) o.Source = a["--source=".Length..];
else if (a.StartsWith("--pid=", StringComparison.OrdinalIgnoreCase)) o.Pid = int.TryParse(a["--pid=".Length..], out var p) ? p : null;
else if (a.Equals("--launch", StringComparison.OrdinalIgnoreCase)) o.Launch = true;
}
return o;
}
}