Add ElevatedTaskService and remove MSIX packaging
Introduce IElevatedTaskService and ElevatedTaskService to manage scheduled-task based elevated launch and autostart. Update App.xaml.cs to bootstrap elevation, attempt managed elevated launch, and handle task registration markers. Refactor AutostartService to delegate autostart operations to the elevated task service, remove legacy registry usage where appropriate, add logging, and update DI registration and unit tests. Remove MSIX packaging support and related tooling: delete build/build-msix.ps1, remove MSIX publish/validation/upload steps from GitHub Actions, drop MSIX-related csproj targets and EnableMsixTooling, and update docs/README/.gitignore to no longer reference MSIX artifacts.
This commit is contained in:
@@ -84,21 +84,6 @@ jobs:
|
||||
|
||||
& iscc.exe "/DMyAppVersion=$version" "/DMyAppSourceDir=$sourceDir" "Installer/setup.iss"
|
||||
|
||||
- name: Publish MSIX
|
||||
run: dotnet publish "ThreadPilot.csproj" --configuration Release -p:PublishProfile=WinX64-MSIX
|
||||
|
||||
- name: Validate MSIX output
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$msixFiles = Get-ChildItem "artifacts/release/msix" -Recurse -File -Include *.msix,*.appx,*.msixbundle,*.appxbundle -ErrorAction SilentlyContinue
|
||||
if (-not $msixFiles)
|
||||
{
|
||||
throw "MSIX package generation failed: no package artifacts found in artifacts/release/msix."
|
||||
}
|
||||
|
||||
Write-Host "MSIX artifacts found: $($msixFiles.Count)"
|
||||
|
||||
- name: Prepare signing certificate (optional)
|
||||
shell: pwsh
|
||||
run: |
|
||||
@@ -134,7 +119,6 @@ jobs:
|
||||
$targets += Get-ChildItem "artifacts/release/singlefile" -Recurse -File -Include *.exe -ErrorAction SilentlyContinue
|
||||
$targets += Get-ChildItem "artifacts/release/readytorun" -Recurse -File -Include *.exe -ErrorAction SilentlyContinue
|
||||
$targets += Get-ChildItem "artifacts/release/installer" -Recurse -File -Include *.exe -ErrorAction SilentlyContinue
|
||||
$targets += Get-ChildItem "artifacts/release/msix" -Recurse -File -Include *.msix,*.appx,*.msixbundle,*.appxbundle -ErrorAction SilentlyContinue
|
||||
|
||||
foreach ($target in $targets)
|
||||
{
|
||||
@@ -226,7 +210,6 @@ jobs:
|
||||
$releaseFiles = @()
|
||||
$releaseFiles += Get-ChildItem "artifacts/release/packages" -File -ErrorAction SilentlyContinue
|
||||
$releaseFiles += Get-ChildItem "artifacts/release/installer/*.exe" -File -ErrorAction SilentlyContinue
|
||||
$releaseFiles += Get-ChildItem "artifacts/release/msix" -Recurse -File -Include *.msix,*.appx,*.msixbundle,*.appxbundle -ErrorAction SilentlyContinue
|
||||
|
||||
$releaseFiles | ForEach-Object {
|
||||
$hash = Get-FileHash $_.FullName -Algorithm SHA256
|
||||
@@ -284,12 +267,6 @@ jobs:
|
||||
name: release-packages
|
||||
path: artifacts/release/packages
|
||||
|
||||
- name: Upload msix artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-msix
|
||||
path: artifacts/release/msix
|
||||
|
||||
- name: Upload checksums artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -358,12 +335,6 @@ jobs:
|
||||
name: release-packages
|
||||
path: release-assets/packages
|
||||
|
||||
- name: Download msix artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-msix
|
||||
path: release-assets/msix
|
||||
|
||||
- name: Download checksums artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
@@ -407,10 +378,6 @@ jobs:
|
||||
files: |
|
||||
release-assets/installer/*.exe
|
||||
release-assets/packages/*.zip
|
||||
release-assets/msix/**/*.msix
|
||||
release-assets/msix/**/*.appx
|
||||
release-assets/msix/**/*.msixbundle
|
||||
release-assets/msix/**/*.appxbundle
|
||||
release-assets/SHA256SUMS.txt
|
||||
winget-manifests/**/*.yaml
|
||||
sbom/manifest.spdx.json
|
||||
|
||||
@@ -93,8 +93,6 @@ Logs/
|
||||
Installer/Output/
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msixbundle
|
||||
*.msm
|
||||
*.msp
|
||||
*.lnk
|
||||
|
||||
+67
-20
@@ -25,7 +25,6 @@ namespace ThreadPilot
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
@@ -36,6 +35,9 @@ namespace ThreadPilot
|
||||
|
||||
public partial class App : System.Windows.Application
|
||||
{
|
||||
private const string RegisterLaunchTaskArgument = "--register-launch-task";
|
||||
private const string LaunchedViaTaskArgument = "--launched-via-task";
|
||||
|
||||
private Mutex? singleInstanceMutex;
|
||||
private int uiExceptionDialogOpen;
|
||||
private DateTime lastUiExceptionDialogUtc = DateTime.MinValue;
|
||||
@@ -63,6 +65,8 @@ namespace ThreadPilot
|
||||
bool startMinimized = false;
|
||||
bool isAutostart = false;
|
||||
bool isSmokeTest = false;
|
||||
bool registerLaunchTask = false;
|
||||
bool launchedViaTask = false;
|
||||
#if DEBUG
|
||||
bool isTestMode = false;
|
||||
#endif
|
||||
@@ -89,10 +93,71 @@ namespace ThreadPilot
|
||||
isAutostart = true;
|
||||
startMinimized = true;
|
||||
break;
|
||||
case RegisterLaunchTaskArgument:
|
||||
registerLaunchTask = true;
|
||||
break;
|
||||
case LaunchedViaTaskArgument:
|
||||
launchedViaTask = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Enforce single-instance: bail out if another instance is already running
|
||||
// Set up global exception handlers first
|
||||
AppDomain.CurrentDomain.UnhandledException += this.OnUnhandledException;
|
||||
this.DispatcherUnhandledException += this.OnDispatcherUnhandledException;
|
||||
TaskScheduler.UnobservedTaskException += this.OnUnobservedTaskException;
|
||||
|
||||
// Check elevation status first
|
||||
var elevationService = this.ServiceProvider.GetRequiredService<IElevationService>();
|
||||
var elevatedTaskService = this.ServiceProvider.GetRequiredService<IElevatedTaskService>();
|
||||
var logger = this.ServiceProvider.GetRequiredService<ILogger<App>>();
|
||||
var isRunningAsAdministrator = elevationService.IsRunningAsAdministrator();
|
||||
|
||||
if (isRunningAsAdministrator)
|
||||
{
|
||||
logger.LogInformation("Application is running with administrator privileges");
|
||||
|
||||
var launchTaskEnsured = Task.Run(async () => await elevatedTaskService.EnsureLaunchTaskAsync()).GetAwaiter().GetResult();
|
||||
if (!launchTaskEnsured)
|
||||
{
|
||||
logger.LogWarning("Failed to ensure managed elevated launch task during startup. Future launches may require one-time elevation again.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (launchedViaTask)
|
||||
{
|
||||
logger.LogWarning("Application was launched via managed task marker but is still not elevated. Continuing in limited mode.");
|
||||
}
|
||||
#if DEBUG
|
||||
else if (!isSmokeTest && !isTestMode)
|
||||
#else
|
||||
else if (!isSmokeTest)
|
||||
#endif
|
||||
{
|
||||
var launchedElevatedInstance = Task.Run(async () => await elevatedTaskService.TryRunLaunchTaskAsync()).GetAwaiter().GetResult();
|
||||
if (launchedElevatedInstance)
|
||||
{
|
||||
logger.LogInformation("Managed elevated launch task started successfully. Exiting current non-elevated instance.");
|
||||
this.Shutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!registerLaunchTask)
|
||||
{
|
||||
logger.LogInformation("Managed elevated launch task is unavailable. Requesting one-time elevation to bootstrap persistent launch.");
|
||||
var restartInitiated = Task.Run(async () => await elevationService.RestartWithElevation(new[] { RegisterLaunchTaskArgument })).GetAwaiter().GetResult();
|
||||
if (restartInitiated)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogWarning("Application is running without administrator privileges. Elevated operations will require explicit elevation.");
|
||||
}
|
||||
|
||||
// Enforce single-instance after elevation bootstrap logic to avoid mutex races during handoff.
|
||||
if (!isSmokeTest)
|
||||
{
|
||||
bool createdNew;
|
||||
@@ -110,24 +175,6 @@ namespace ThreadPilot
|
||||
}
|
||||
}
|
||||
|
||||
// Set up global exception handlers first
|
||||
AppDomain.CurrentDomain.UnhandledException += this.OnUnhandledException;
|
||||
this.DispatcherUnhandledException += this.OnDispatcherUnhandledException;
|
||||
TaskScheduler.UnobservedTaskException += this.OnUnobservedTaskException;
|
||||
|
||||
// Check elevation status first
|
||||
var elevationService = this.ServiceProvider.GetRequiredService<IElevationService>();
|
||||
var logger = this.ServiceProvider.GetRequiredService<ILogger<App>>();
|
||||
|
||||
if (!elevationService.IsRunningAsAdministrator())
|
||||
{
|
||||
logger.LogWarning("Application is running without administrator privileges. Elevated operations will require explicit elevation.");
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogInformation("Application is running with administrator privileges");
|
||||
}
|
||||
|
||||
base.OnStartup(e);
|
||||
|
||||
// Check for test mode
|
||||
|
||||
@@ -41,7 +41,6 @@ Latest artifacts are published on each tagged release in [GitHub Releases](https
|
||||
|---|---|---|
|
||||
| Installer (Recommended) | `ThreadPilot_v1.1.1_Setup.exe` | Standard Windows installer (Inno Setup) for most users |
|
||||
| Portable | `ThreadPilot_v1.1.1_singlefile_win-x64.zip` | No-install deployment for power users |
|
||||
| MSIX (Secondary) | `ThreadPilot_1.1.1.0_win-x64.msix` | Advanced/enterprise sideload scenarios |
|
||||
|
||||
Verification example:
|
||||
|
||||
@@ -54,7 +53,6 @@ Install flow summary:
|
||||
1. Download the package matching your deployment model.
|
||||
2. Installer package (recommended): run `ThreadPilot_vX.Y.Z_Setup.exe` and complete the wizard.
|
||||
3. Portable package: extract ZIP and launch `ThreadPilot.exe`.
|
||||
4. MSIX package (secondary): install only if your environment supports sideload trust requirements.
|
||||
|
||||
Notes:
|
||||
|
||||
|
||||
+104
-30
@@ -37,6 +37,7 @@ namespace ThreadPilot.Services
|
||||
|
||||
private readonly ILogger<AutostartService> logger;
|
||||
private readonly IElevationService elevationService;
|
||||
private readonly IElevatedTaskService elevatedTaskService;
|
||||
private bool isAutostartEnabled;
|
||||
private string? autostartPath;
|
||||
|
||||
@@ -46,10 +47,11 @@ namespace ThreadPilot.Services
|
||||
|
||||
public string? AutostartPath => this.autostartPath;
|
||||
|
||||
public AutostartService(ILogger<AutostartService> logger, IElevationService elevationService)
|
||||
public AutostartService(ILogger<AutostartService> logger, IElevationService elevationService, IElevatedTaskService elevatedTaskService)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.elevationService = elevationService ?? throw new ArgumentNullException(nameof(elevationService));
|
||||
this.elevatedTaskService = elevatedTaskService ?? throw new ArgumentNullException(nameof(elevatedTaskService));
|
||||
|
||||
// Initialize current status without surfacing startup exceptions.
|
||||
TaskSafety.FireAndForget(this.CheckAutostartStatusAsync(), ex =>
|
||||
@@ -72,19 +74,28 @@ namespace ThreadPilot.Services
|
||||
var arguments = this.GetAutostartArguments(startMinimized);
|
||||
var fullCommand = $"\"{executablePath}\" {arguments}";
|
||||
|
||||
using var key = Registry.CurrentUser.OpenSubKey(REGISTRYKEYPATH, true);
|
||||
if (key == null)
|
||||
// Clean up legacy registry-based startup to keep a single elevated startup mechanism.
|
||||
this.TryRemoveLegacyRegistryAutostart();
|
||||
|
||||
if (!this.elevationService.IsRunningAsAdministrator())
|
||||
{
|
||||
LogAutostartRegistryKeyMissing(this.logger);
|
||||
LogAutostartRequiresElevation(this.logger);
|
||||
|
||||
var elevationRequested = await this.elevationService.RequestElevationIfNeeded();
|
||||
if (!elevationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
LogAutostartDeferredToElevatedInstance(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
key.SetValue(APPLICATIONNAME, fullCommand, RegistryValueKind.String);
|
||||
|
||||
// For elevated apps, also create a scheduled task as backup
|
||||
if (this.elevationService.IsRunningAsAdministrator())
|
||||
var scheduledTaskCreated = await this.elevatedTaskService.EnsureAutostartTaskAsync(executablePath, arguments);
|
||||
if (!scheduledTaskCreated)
|
||||
{
|
||||
await this.CreateElevatedStartupTask(executablePath, arguments);
|
||||
LogAutostartTaskRegistrationFailed(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.isAutostartEnabled = true;
|
||||
@@ -112,21 +123,30 @@ namespace ThreadPilot.Services
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(REGISTRYKEYPATH, true);
|
||||
if (key == null)
|
||||
if (!this.elevationService.IsRunningAsAdministrator())
|
||||
{
|
||||
LogAutostartRegistryRemovalKeyMissing(this.logger);
|
||||
LogAutostartDisableRequiresElevation(this.logger);
|
||||
|
||||
var elevationRequested = await this.elevationService.RequestElevationIfNeeded();
|
||||
if (!elevationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
LogAutostartDisableDeferredToElevatedInstance(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (key.GetValue(APPLICATIONNAME) != null)
|
||||
this.TryRemoveLegacyRegistryAutostart();
|
||||
|
||||
var scheduledTaskRemoved = await this.elevatedTaskService.RemoveAutostartTaskAsync();
|
||||
if (!scheduledTaskRemoved)
|
||||
{
|
||||
key.DeleteValue(APPLICATIONNAME, false);
|
||||
LogAutostartDisabled(this.logger);
|
||||
LogAutostartTaskRemovalFailed(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Also remove the scheduled task if it exists
|
||||
await this.RemoveElevatedStartupTask();
|
||||
LogAutostartDisabled(this.logger);
|
||||
|
||||
this.isAutostartEnabled = false;
|
||||
this.autostartPath = null;
|
||||
@@ -146,32 +166,28 @@ namespace ThreadPilot.Services
|
||||
}
|
||||
}
|
||||
|
||||
public Task<bool> CheckAutostartStatusAsync()
|
||||
public async Task<bool> CheckAutostartStatusAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(REGISTRYKEYPATH, false);
|
||||
if (key == null)
|
||||
{
|
||||
this.isAutostartEnabled = false;
|
||||
this.autostartPath = null;
|
||||
return Task.FromResult(false);
|
||||
}
|
||||
var taskRegistered = await this.elevatedTaskService.IsAutostartTaskRegisteredAsync();
|
||||
var legacyRegistryValue = this.TryReadLegacyRegistryAutostart();
|
||||
|
||||
var value = key.GetValue(APPLICATIONNAME) as string;
|
||||
this.isAutostartEnabled = !string.IsNullOrEmpty(value);
|
||||
this.autostartPath = value;
|
||||
this.isAutostartEnabled = taskRegistered || !string.IsNullOrWhiteSpace(legacyRegistryValue);
|
||||
this.autostartPath = taskRegistered
|
||||
? $"task://{this.elevatedTaskService.AutostartTaskName}"
|
||||
: legacyRegistryValue;
|
||||
|
||||
LogAutostartStatusChecked(this.logger, this.isAutostartEnabled, this.autostartPath);
|
||||
|
||||
return Task.FromResult(this.isAutostartEnabled);
|
||||
return this.isAutostartEnabled;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogCheckAutostartStatusFailed(this.logger, ex);
|
||||
this.isAutostartEnabled = false;
|
||||
this.autostartPath = null;
|
||||
return Task.FromResult(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,6 +250,37 @@ namespace ThreadPilot.Services
|
||||
}
|
||||
}
|
||||
|
||||
private string? TryReadLegacyRegistryAutostart()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(REGISTRYKEYPATH, false);
|
||||
return key?.GetValue(APPLICATIONNAME) as string;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogLegacyRegistryReadFailed(this.logger, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void TryRemoveLegacyRegistryAutostart()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(REGISTRYKEYPATH, true);
|
||||
if (key?.GetValue(APPLICATIONNAME) != null)
|
||||
{
|
||||
key.DeleteValue(APPLICATIONNAME, false);
|
||||
LogLegacyRegistryEntryRemoved(this.logger);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogLegacyRegistryCleanupFailed(this.logger, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a scheduled task for elevated startup as a backup to registry autostart.
|
||||
/// </summary>
|
||||
@@ -358,6 +405,33 @@ namespace ThreadPilot.Services
|
||||
[LoggerMessage(EventId = 4217, Level = LogLevel.Warning, Message = "Failed to remove elevated startup task")]
|
||||
private static partial void LogRemoveElevatedStartupTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4218, Level = LogLevel.Information, Message = "Autostart configuration requires elevation; requesting elevated restart")]
|
||||
private static partial void LogAutostartRequiresElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4219, Level = LogLevel.Information, Message = "Autostart enable request delegated to elevated instance")]
|
||||
private static partial void LogAutostartDeferredToElevatedInstance(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4220, Level = LogLevel.Warning, Message = "Failed to register elevated autostart task")]
|
||||
private static partial void LogAutostartTaskRegistrationFailed(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4221, Level = LogLevel.Information, Message = "Autostart disable requires elevation; requesting elevated restart")]
|
||||
private static partial void LogAutostartDisableRequiresElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4222, Level = LogLevel.Information, Message = "Autostart disable request delegated to elevated instance")]
|
||||
private static partial void LogAutostartDisableDeferredToElevatedInstance(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4223, Level = LogLevel.Warning, Message = "Failed to remove elevated autostart task")]
|
||||
private static partial void LogAutostartTaskRemovalFailed(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4224, Level = LogLevel.Debug, Message = "Legacy HKCU Run autostart value removed")]
|
||||
private static partial void LogLegacyRegistryEntryRemoved(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4225, Level = LogLevel.Debug, Message = "Failed to read legacy HKCU Run autostart value")]
|
||||
private static partial void LogLegacyRegistryReadFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4226, Level = LogLevel.Debug, Message = "Failed to remove legacy HKCU Run autostart value")]
|
||||
private static partial void LogLegacyRegistryCleanupFailed(ILogger logger, Exception ex);
|
||||
|
||||
private static bool IsValidExecutablePath(string executablePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executablePath) || !Path.IsPathRooted(executablePath))
|
||||
|
||||
@@ -0,0 +1,465 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Security;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Manages Scheduled Tasks used for persistent elevated launch and elevated autostart.
|
||||
/// </summary>
|
||||
public partial class ElevatedTaskService : IElevatedTaskService
|
||||
{
|
||||
private static readonly string SchTasksExecutablePath = Path.Combine(Environment.SystemDirectory, "schtasks.exe");
|
||||
private static readonly TimeSpan ScheduledTaskTimeout = TimeSpan.FromSeconds(20);
|
||||
|
||||
private readonly ILogger<ElevatedTaskService> logger;
|
||||
|
||||
public ElevatedTaskService(ILogger<ElevatedTaskService> logger)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public string LaunchTaskName => "ThreadPilot_Launch";
|
||||
|
||||
public string AutostartTaskName => "ThreadPilot_Startup";
|
||||
|
||||
public async Task<bool> EnsureLaunchTaskAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var executablePath = this.GetExecutablePath();
|
||||
if (!IsValidExecutablePath(executablePath))
|
||||
{
|
||||
LogSkipEnsureLaunchTaskInvalidPath(this.logger, executablePath ?? "(null)");
|
||||
return false;
|
||||
}
|
||||
|
||||
var taskXmlPath = Path.Combine(Path.GetTempPath(), $"threadpilot-launch-task-{Guid.NewGuid():N}.xml");
|
||||
try
|
||||
{
|
||||
WriteLaunchTaskDefinition(taskXmlPath, executablePath);
|
||||
|
||||
var result = await RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Create",
|
||||
"/TN", this.LaunchTaskName,
|
||||
"/XML", taskXmlPath,
|
||||
"/F",
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogLaunchTaskEnsured(this.logger, this.LaunchTaskName, executablePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogEnsureLaunchTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDeleteFile(taskXmlPath, this.logger);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogEnsureLaunchTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> TryRunLaunchTaskAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Run",
|
||||
"/TN", this.LaunchTaskName,
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogLaunchTaskStarted(this.logger, this.LaunchTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogRunLaunchTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogRunLaunchTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> EnsureAutostartTaskAsync(string executablePath, string arguments)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!IsValidExecutablePath(executablePath))
|
||||
{
|
||||
LogSkipEnsureAutostartTaskInvalidPath(this.logger, executablePath);
|
||||
return false;
|
||||
}
|
||||
|
||||
var taskRunCommand = BuildCommand(executablePath, arguments);
|
||||
var result = await RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Create",
|
||||
"/TN", this.AutostartTaskName,
|
||||
"/TR", taskRunCommand,
|
||||
"/SC", "ONLOGON",
|
||||
"/RL", "HIGHEST",
|
||||
"/F",
|
||||
"/RU", Environment.UserName,
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogAutostartTaskEnsured(this.logger, this.AutostartTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogEnsureAutostartTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogEnsureAutostartTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveAutostartTaskAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Delete",
|
||||
"/TN", this.AutostartTaskName,
|
||||
"/F",
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogAutostartTaskRemoved(this.logger, this.AutostartTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Exit code 1 is expected when task doesn't exist; treat as already removed.
|
||||
if (result.ExitCode == 1)
|
||||
{
|
||||
LogAutostartTaskAlreadyRemoved(this.logger, this.AutostartTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogRemoveAutostartTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogRemoveAutostartTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> IsAutostartTaskRegisteredAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Query",
|
||||
"/TN", this.AutostartTaskName,
|
||||
});
|
||||
|
||||
var exists = result.ExitCode == 0;
|
||||
LogAutostartTaskQueryResult(this.logger, this.AutostartTaskName, exists, result.ExitCode);
|
||||
return exists;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogAutostartTaskQueryException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private string? GetExecutablePath()
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentPath = Process.GetCurrentProcess().MainModule?.FileName;
|
||||
if (IsValidExecutablePath(currentPath))
|
||||
{
|
||||
return currentPath;
|
||||
}
|
||||
|
||||
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
|
||||
if (!string.IsNullOrWhiteSpace(assemblyLocation) &&
|
||||
assemblyLocation.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var candidatePath = Path.ChangeExtension(assemblyLocation, ".exe");
|
||||
if (IsValidExecutablePath(candidatePath))
|
||||
{
|
||||
return candidatePath;
|
||||
}
|
||||
}
|
||||
|
||||
return IsValidExecutablePath(assemblyLocation)
|
||||
? assemblyLocation
|
||||
: null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogGetExecutablePathFailed(this.logger, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildCommand(string executablePath, string arguments)
|
||||
{
|
||||
var trimmedArguments = arguments?.Trim();
|
||||
return string.IsNullOrWhiteSpace(trimmedArguments)
|
||||
? $"\"{executablePath}\""
|
||||
: $"\"{executablePath}\" {trimmedArguments}";
|
||||
}
|
||||
|
||||
private static bool IsValidExecutablePath(string? executablePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executablePath) || !Path.IsPathRooted(executablePath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return File.Exists(executablePath) &&
|
||||
string.Equals(Path.GetExtension(executablePath), ".exe", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static void WriteLaunchTaskDefinition(string taskXmlPath, string executablePath)
|
||||
{
|
||||
var userName = WindowsIdentity.GetCurrent().Name;
|
||||
if (string.IsNullOrWhiteSpace(userName))
|
||||
{
|
||||
throw new InvalidOperationException("Could not determine current user identity for launch task registration.");
|
||||
}
|
||||
|
||||
var workingDirectory = Path.GetDirectoryName(executablePath);
|
||||
if (string.IsNullOrWhiteSpace(workingDirectory))
|
||||
{
|
||||
throw new InvalidOperationException("Could not determine working directory for launch task registration.");
|
||||
}
|
||||
|
||||
var escapedUserName = SecurityElement.Escape(userName);
|
||||
var escapedExecutablePath = SecurityElement.Escape(executablePath);
|
||||
var escapedArguments = SecurityElement.Escape("--launched-via-task");
|
||||
var escapedWorkingDirectory = SecurityElement.Escape(workingDirectory);
|
||||
|
||||
var taskXml = $@"<?xml version=""1.0"" encoding=""UTF-16""?>
|
||||
<Task version=""1.4"" xmlns=""http://schemas.microsoft.com/windows/2004/02/mit/task"">
|
||||
<RegistrationInfo>
|
||||
<Author>ThreadPilot</Author>
|
||||
<Description>Launches ThreadPilot with highest available privileges on demand.</Description>
|
||||
</RegistrationInfo>
|
||||
<Principals>
|
||||
<Principal id=""Author"">
|
||||
<UserId>{escapedUserName}</UserId>
|
||||
<LogonType>InteractiveToken</LogonType>
|
||||
<RunLevel>HighestAvailable</RunLevel>
|
||||
</Principal>
|
||||
</Principals>
|
||||
<Settings>
|
||||
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
||||
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
||||
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
||||
<AllowHardTerminate>false</AllowHardTerminate>
|
||||
<StartWhenAvailable>false</StartWhenAvailable>
|
||||
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
||||
<IdleSettings>
|
||||
<StopOnIdleEnd>false</StopOnIdleEnd>
|
||||
<RestartOnIdle>false</RestartOnIdle>
|
||||
</IdleSettings>
|
||||
<AllowStartOnDemand>true</AllowStartOnDemand>
|
||||
<Enabled>true</Enabled>
|
||||
<Hidden>false</Hidden>
|
||||
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
||||
<WakeToRun>false</WakeToRun>
|
||||
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
||||
<Priority>7</Priority>
|
||||
</Settings>
|
||||
<Actions Context=""Author"">
|
||||
<Exec>
|
||||
<Command>{escapedExecutablePath}</Command>
|
||||
<Arguments>{escapedArguments}</Arguments>
|
||||
<WorkingDirectory>{escapedWorkingDirectory}</WorkingDirectory>
|
||||
</Exec>
|
||||
</Actions>
|
||||
</Task>";
|
||||
|
||||
File.WriteAllText(taskXmlPath, taskXml, Encoding.Unicode);
|
||||
}
|
||||
|
||||
private static async Task<ProcessResult> RunSchTasksAsync(IReadOnlyList<string> arguments)
|
||||
{
|
||||
if (!File.Exists(SchTasksExecutablePath))
|
||||
{
|
||||
return new ProcessResult(-1, string.Empty, "schtasks.exe not found in system directory");
|
||||
}
|
||||
|
||||
var processInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = SchTasksExecutablePath,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
};
|
||||
|
||||
foreach (var argument in arguments)
|
||||
{
|
||||
processInfo.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
using var process = Process.Start(processInfo);
|
||||
if (process == null)
|
||||
{
|
||||
return new ProcessResult(-1, string.Empty, "Could not start schtasks.exe");
|
||||
}
|
||||
|
||||
var outputTask = process.StandardOutput.ReadToEndAsync();
|
||||
var errorTask = process.StandardError.ReadToEndAsync();
|
||||
var exitTask = process.WaitForExitAsync();
|
||||
var completedTask = await Task.WhenAny(exitTask, Task.Delay(ScheduledTaskTimeout));
|
||||
|
||||
if (completedTask != exitTask)
|
||||
{
|
||||
try
|
||||
{
|
||||
process.Kill(entireProcessTree: true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Best-effort kill for timeout.
|
||||
}
|
||||
|
||||
return new ProcessResult(-1, await outputTask, $"schtasks timeout after {ScheduledTaskTimeout.TotalSeconds} seconds");
|
||||
}
|
||||
|
||||
await exitTask;
|
||||
return new ProcessResult(process.ExitCode, await outputTask, await errorTask);
|
||||
}
|
||||
|
||||
private static void TryDeleteFile(string path, ILogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogDeleteTemporaryFileFailed(logger, path, ex);
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(EventId = 4250, Level = LogLevel.Warning, Message = "Skipping launch task registration due to invalid executable path: {Path}")]
|
||||
private static partial void LogSkipEnsureLaunchTaskInvalidPath(ILogger logger, string path);
|
||||
|
||||
[LoggerMessage(EventId = 4251, Level = LogLevel.Information, Message = "Ensured elevated launch task '{TaskName}' for executable '{ExecutablePath}'")]
|
||||
private static partial void LogLaunchTaskEnsured(ILogger logger, string taskName, string executablePath);
|
||||
|
||||
[LoggerMessage(EventId = 4252, Level = LogLevel.Warning, Message = "Failed to ensure elevated launch task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogEnsureLaunchTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4253, Level = LogLevel.Warning, Message = "Exception while ensuring elevated launch task")]
|
||||
private static partial void LogEnsureLaunchTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4254, Level = LogLevel.Information, Message = "Started elevated launch task '{TaskName}'")]
|
||||
private static partial void LogLaunchTaskStarted(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4255, Level = LogLevel.Warning, Message = "Failed to run elevated launch task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogRunLaunchTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4256, Level = LogLevel.Warning, Message = "Exception while running elevated launch task")]
|
||||
private static partial void LogRunLaunchTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4257, Level = LogLevel.Warning, Message = "Skipping autostart task registration due to invalid executable path: {Path}")]
|
||||
private static partial void LogSkipEnsureAutostartTaskInvalidPath(ILogger logger, string path);
|
||||
|
||||
[LoggerMessage(EventId = 4258, Level = LogLevel.Information, Message = "Ensured elevated autostart task '{TaskName}'")]
|
||||
private static partial void LogAutostartTaskEnsured(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4259, Level = LogLevel.Warning, Message = "Failed to ensure elevated autostart task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogEnsureAutostartTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4260, Level = LogLevel.Warning, Message = "Exception while ensuring elevated autostart task")]
|
||||
private static partial void LogEnsureAutostartTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4261, Level = LogLevel.Information, Message = "Removed elevated autostart task '{TaskName}'")]
|
||||
private static partial void LogAutostartTaskRemoved(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4262, Level = LogLevel.Debug, Message = "Elevated autostart task '{TaskName}' was already absent")]
|
||||
private static partial void LogAutostartTaskAlreadyRemoved(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4263, Level = LogLevel.Warning, Message = "Failed to remove elevated autostart task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogRemoveAutostartTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4264, Level = LogLevel.Warning, Message = "Exception while removing elevated autostart task")]
|
||||
private static partial void LogRemoveAutostartTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4265, Level = LogLevel.Debug, Message = "Autostart task query for '{TaskName}': Exists={Exists}, ExitCode={ExitCode}")]
|
||||
private static partial void LogAutostartTaskQueryResult(ILogger logger, string taskName, bool exists, int exitCode);
|
||||
|
||||
[LoggerMessage(EventId = 4266, Level = LogLevel.Warning, Message = "Exception while querying elevated autostart task")]
|
||||
private static partial void LogAutostartTaskQueryException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4267, Level = LogLevel.Warning, Message = "Failed to resolve executable path while ensuring elevated tasks")]
|
||||
private static partial void LogGetExecutablePathFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4268, Level = LogLevel.Debug, Message = "Failed to delete temporary file '{Path}'")]
|
||||
private static partial void LogDeleteTemporaryFileFailed(ILogger logger, string path, Exception ex);
|
||||
|
||||
private readonly struct ProcessResult
|
||||
{
|
||||
public ProcessResult(int exitCode, string standardOutput, string standardError)
|
||||
{
|
||||
this.ExitCode = exitCode;
|
||||
this.StandardOutput = standardOutput;
|
||||
this.StandardError = standardError;
|
||||
}
|
||||
|
||||
public int ExitCode { get; }
|
||||
|
||||
public string StandardOutput { get; }
|
||||
|
||||
public string StandardError { get; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing Scheduled Task-based elevation entrypoints.
|
||||
/// </summary>
|
||||
public interface IElevatedTaskService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the managed task name used for on-demand elevated launch.
|
||||
/// </summary>
|
||||
string LaunchTaskName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the managed task name used for elevated logon autostart.
|
||||
/// </summary>
|
||||
string AutostartTaskName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Ensures the managed on-demand elevated launch task exists and targets the current executable.
|
||||
/// </summary>
|
||||
/// <returns>True when the task exists and is up to date; otherwise false.</returns>
|
||||
Task<bool> EnsureLaunchTaskAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Runs the managed on-demand elevated launch task.
|
||||
/// </summary>
|
||||
/// <returns>True if task execution was started successfully; otherwise false.</returns>
|
||||
Task<bool> TryRunLaunchTaskAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Ensures elevated autostart task exists and points to the provided executable command.
|
||||
/// </summary>
|
||||
/// <param name="executablePath">Absolute executable path.</param>
|
||||
/// <param name="arguments">Command-line arguments for autostart launches.</param>
|
||||
/// <returns>True if task was created/updated successfully; otherwise false.</returns>
|
||||
Task<bool> EnsureAutostartTaskAsync(string executablePath, string arguments);
|
||||
|
||||
/// <summary>
|
||||
/// Removes the managed elevated autostart task.
|
||||
/// </summary>
|
||||
/// <returns>True when the task is removed (or already absent); otherwise false.</returns>
|
||||
Task<bool> RemoveAutostartTaskAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the managed elevated autostart task is currently registered.
|
||||
/// </summary>
|
||||
/// <returns>True when the task exists; otherwise false.</returns>
|
||||
Task<bool> IsAutostartTaskRegisteredAsync();
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,7 @@ namespace ThreadPilot.Services
|
||||
// Security and elevation services
|
||||
services.AddSingleton<ISecurityService, SecurityService>();
|
||||
services.AddSingleton<IElevationService, ElevationService>();
|
||||
services.AddSingleton<IElevatedTaskService, ElevatedTaskService>();
|
||||
|
||||
// System tweaks service
|
||||
services.AddSingleton<ISystemTweaksService, SystemTweaksService>();
|
||||
|
||||
@@ -43,7 +43,8 @@ namespace ThreadPilot.Core.Tests
|
||||
private static AutostartService CreateService()
|
||||
{
|
||||
var elevationService = new Mock<IElevationService>(MockBehavior.Loose);
|
||||
return new AutostartService(NullLogger<AutostartService>.Instance, elevationService.Object);
|
||||
var elevatedTaskService = new Mock<IElevatedTaskService>(MockBehavior.Loose);
|
||||
return new AutostartService(NullLogger<AutostartService>.Instance, elevationService.Object, elevatedTaskService.Object);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UseWPF>true</UseWPF>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<EnableMsixTooling>true</EnableMsixTooling>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationIcon>assets\icons\ico.ico</ApplicationIcon>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
@@ -73,10 +72,6 @@
|
||||
<Compile Remove="Tests\GameBoostIntegrationTest.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="GenerateMsixFromPublishOutput" AfterTargets="Publish" Condition="'$(GenerateMsixFromPublish)' == 'true'">
|
||||
<Exec Command="powershell -NoProfile -ExecutionPolicy Bypass -File "$(MSBuildProjectDirectory)\build\build-msix.ps1" -ProjectDir "$(MSBuildProjectDirectory)" -PublishDir "$(PublishDir)." -OutputDir "$(MsixOutputDir)." -Version "$(Version)"" />
|
||||
</Target>
|
||||
|
||||
<Import Project="Directory.Publish.props" Condition="Exists('Directory.Publish.props')" />
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$PublishDir,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$OutputDir,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Version,
|
||||
|
||||
[string]$ProjectDir = (Get-Location).Path,
|
||||
[string]$PackageIdentityName = "PrimeBuild.ThreadPilot",
|
||||
[string]$PackagePublisher = "CN=Prime Build",
|
||||
[string]$ExecutableName = "ThreadPilot.exe",
|
||||
[string]$DisplayName = "ThreadPilot",
|
||||
[string]$PublisherDisplayName = "Prime Build",
|
||||
[string]$Description = "ThreadPilot process and power plan manager",
|
||||
[string]$MinWindowsVersion = "10.0.19041.0",
|
||||
[string]$MaxWindowsVersionTested = "10.0.26100.0",
|
||||
[switch]$KeepStaging
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Resolve-AbsolutePath {
|
||||
param([Parameter(Mandatory = $true)][string]$Path)
|
||||
|
||||
if ([System.IO.Path]::IsPathRooted($Path)) {
|
||||
return [System.IO.Path]::GetFullPath($Path)
|
||||
}
|
||||
|
||||
return [System.IO.Path]::GetFullPath((Join-Path $ProjectDir $Path))
|
||||
}
|
||||
|
||||
function Convert-ToMsixVersion {
|
||||
param([Parameter(Mandatory = $true)][string]$RawVersion)
|
||||
|
||||
$parts = $RawVersion.Split('.') | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }
|
||||
$normalized = @()
|
||||
|
||||
foreach ($part in $parts) {
|
||||
$numericPart = ($part -replace '[^0-9]', '')
|
||||
if ([string]::IsNullOrWhiteSpace($numericPart)) {
|
||||
$numericPart = '0'
|
||||
}
|
||||
|
||||
$value = [int]$numericPart
|
||||
if ($value -lt 0) {
|
||||
$value = 0
|
||||
}
|
||||
if ($value -gt 65535) {
|
||||
$value = 65535
|
||||
}
|
||||
|
||||
$normalized += $value
|
||||
}
|
||||
|
||||
while ($normalized.Count -lt 4) {
|
||||
$normalized += 0
|
||||
}
|
||||
|
||||
return "{0}.{1}.{2}.{3}" -f $normalized[0], $normalized[1], $normalized[2], $normalized[3]
|
||||
}
|
||||
|
||||
function Find-MakeAppxPath {
|
||||
if (-not [string]::IsNullOrWhiteSpace($env:MAKEAPPX_EXE) -and (Test-Path -LiteralPath $env:MAKEAPPX_EXE)) {
|
||||
return $env:MAKEAPPX_EXE
|
||||
}
|
||||
|
||||
$kitsRoot = "C:\Program Files (x86)\Windows Kits\10\bin"
|
||||
if (-not (Test-Path -LiteralPath $kitsRoot)) {
|
||||
throw "Windows SDK was not found at '$kitsRoot'. Install Windows 10/11 SDK to enable MSIX packaging."
|
||||
}
|
||||
|
||||
$candidate = Get-ChildItem -LiteralPath $kitsRoot -Directory |
|
||||
Sort-Object Name -Descending |
|
||||
ForEach-Object { Join-Path $_.FullName "x64\makeappx.exe" } |
|
||||
Where-Object { Test-Path -LiteralPath $_ } |
|
||||
Select-Object -First 1
|
||||
|
||||
if (-not $candidate) {
|
||||
throw "makeappx.exe not found under Windows SDK bin folders."
|
||||
}
|
||||
|
||||
return $candidate
|
||||
}
|
||||
|
||||
function New-AppLogo {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][int]$Size,
|
||||
[Parameter(Mandatory = $true)][string]$OutputPath
|
||||
)
|
||||
|
||||
$bmp = New-Object System.Drawing.Bitmap($Size, $Size)
|
||||
try {
|
||||
$graphics = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
try {
|
||||
$graphics.Clear([System.Drawing.Color]::FromArgb(255, 22, 112, 214))
|
||||
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
|
||||
|
||||
$fontSize = [Math]::Max(12.0, $Size * 0.42)
|
||||
$font = New-Object System.Drawing.Font("Segoe UI", $fontSize, [System.Drawing.FontStyle]::Bold, [System.Drawing.GraphicsUnit]::Pixel)
|
||||
try {
|
||||
$stringFormat = New-Object System.Drawing.StringFormat
|
||||
try {
|
||||
$stringFormat.Alignment = [System.Drawing.StringAlignment]::Center
|
||||
$stringFormat.LineAlignment = [System.Drawing.StringAlignment]::Center
|
||||
$brush = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::White)
|
||||
try {
|
||||
$graphics.DrawString("TP", $font, $brush, [System.Drawing.RectangleF]::new(0, 0, $Size, $Size), $stringFormat)
|
||||
$bmp.Save($OutputPath, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
}
|
||||
finally {
|
||||
$brush.Dispose()
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$stringFormat.Dispose()
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$font.Dispose()
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$graphics.Dispose()
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$bmp.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
$publishPath = Resolve-AbsolutePath -Path $PublishDir
|
||||
$outputPath = Resolve-AbsolutePath -Path $OutputDir
|
||||
$projectPath = Resolve-AbsolutePath -Path $ProjectDir
|
||||
|
||||
if (-not (Test-Path -LiteralPath $publishPath)) {
|
||||
throw "Publish directory not found: $publishPath"
|
||||
}
|
||||
|
||||
$executablePath = Join-Path $publishPath $ExecutableName
|
||||
if (-not (Test-Path -LiteralPath $executablePath)) {
|
||||
throw "Expected executable '$ExecutableName' was not found in publish directory: $publishPath"
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Path $outputPath -Force | Out-Null
|
||||
|
||||
$stagingPath = Join-Path $outputPath "_msix_stage"
|
||||
if (Test-Path -LiteralPath $stagingPath) {
|
||||
Remove-Item -LiteralPath $stagingPath -Recurse -Force
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Path $stagingPath -Force | Out-Null
|
||||
Copy-Item -Path (Join-Path $publishPath "*") -Destination $stagingPath -Recurse -Force
|
||||
|
||||
$assetsPath = Join-Path $stagingPath "Assets"
|
||||
New-Item -ItemType Directory -Path $assetsPath -Force | Out-Null
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$square44 = Join-Path $assetsPath "Square44x44Logo.png"
|
||||
$square150 = Join-Path $assetsPath "Square150x150Logo.png"
|
||||
$storeLogo = Join-Path $assetsPath "StoreLogo.png"
|
||||
|
||||
New-AppLogo -Size 44 -OutputPath $square44
|
||||
New-AppLogo -Size 150 -OutputPath $square150
|
||||
New-AppLogo -Size 50 -OutputPath $storeLogo
|
||||
|
||||
$msixVersion = Convert-ToMsixVersion -RawVersion $Version
|
||||
$manifestPath = Join-Path $stagingPath "AppxManifest.xml"
|
||||
|
||||
$manifestContent = @"
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="uap rescap">
|
||||
<Identity Name="$PackageIdentityName" Publisher="$PackagePublisher" Version="$msixVersion" ProcessorArchitecture="x64" />
|
||||
<Properties>
|
||||
<DisplayName>$DisplayName</DisplayName>
|
||||
<PublisherDisplayName>$PublisherDisplayName</PublisherDisplayName>
|
||||
<Description>$Description</Description>
|
||||
<Logo>Assets\StoreLogo.png</Logo>
|
||||
</Properties>
|
||||
<Dependencies>
|
||||
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="$MinWindowsVersion" MaxVersionTested="$MaxWindowsVersionTested" />
|
||||
</Dependencies>
|
||||
<Resources>
|
||||
<Resource Language="en-us" />
|
||||
</Resources>
|
||||
<Applications>
|
||||
<Application Id="ThreadPilot" Executable="$ExecutableName" EntryPoint="Windows.FullTrustApplication">
|
||||
<uap:VisualElements DisplayName="$DisplayName" Description="$Description" BackgroundColor="transparent" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" />
|
||||
</Application>
|
||||
</Applications>
|
||||
<Capabilities>
|
||||
<rescap:Capability Name="runFullTrust" />
|
||||
</Capabilities>
|
||||
</Package>
|
||||
"@
|
||||
|
||||
[System.IO.File]::WriteAllText($manifestPath, $manifestContent, [System.Text.UTF8Encoding]::new($false))
|
||||
|
||||
$makeAppx = Find-MakeAppxPath
|
||||
$msixFileName = "ThreadPilot_{0}_win-x64.msix" -f $msixVersion
|
||||
$msixPath = Join-Path $outputPath $msixFileName
|
||||
|
||||
if (Test-Path -LiteralPath $msixPath) {
|
||||
Remove-Item -LiteralPath $msixPath -Force
|
||||
}
|
||||
|
||||
Write-Host "Creating MSIX package at: $msixPath"
|
||||
& $makeAppx pack /d $stagingPath /p $msixPath /o
|
||||
|
||||
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $msixPath)) {
|
||||
throw "MSIX packaging failed. Expected artifact not found: $msixPath"
|
||||
}
|
||||
|
||||
if (-not $KeepStaging) {
|
||||
Remove-Item -LiteralPath $stagingPath -Recurse -Force
|
||||
}
|
||||
|
||||
Write-Host "MSIX package created successfully: $msixPath"
|
||||
@@ -32,7 +32,6 @@ if (-not (Test-Path -LiteralPath $notesPath)) {
|
||||
$artifacts = @()
|
||||
$artifacts += Get-ChildItem "artifacts/release/packages" -File -ErrorAction SilentlyContinue
|
||||
$artifacts += Get-ChildItem "artifacts/release/installer" -File -Include *.exe -ErrorAction SilentlyContinue
|
||||
$artifacts += Get-ChildItem "artifacts/release/msix" -Recurse -File -Include *.msix,*.appx,*.msixbundle,*.appxbundle -ErrorAction SilentlyContinue
|
||||
|
||||
$checksums = Join-Path $projectRoot "artifacts/release/SHA256SUMS.txt"
|
||||
if (Test-Path -LiteralPath $checksums) {
|
||||
|
||||
@@ -34,4 +34,4 @@ Release can proceed only when all gates are marked complete or explicitly waived
|
||||
- Tests: `dotnet test Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj --configuration Release` (20 passed, 0 failed).
|
||||
- Dependency security: `dotnet list ThreadPilot.csproj package --vulnerable --include-transitive` (no vulnerable packages).
|
||||
- Secret hygiene: local gitleaks run, report `docs/audits/GITLEAKS_REPORT_2026-04-15.json` (no leaks).
|
||||
- Packaging: installer/msix/packages/checksums generated in `artifacts/release/`.
|
||||
- Packaging: installer/packages/checksums generated in `artifacts/release/`.
|
||||
|
||||
@@ -14,14 +14,12 @@ Use this checklist before creating a release tag. It is aligned with local build
|
||||
Goal: keep only 1.1.1 artifacts in artifacts/release.
|
||||
|
||||
- [ ] Delete old installer: artifacts/release/installer/ThreadPilot_v1.1.0_Setup.exe
|
||||
- [ ] Delete old msix: artifacts/release/msix/ThreadPilot_1.1.0.0_win-x64.msix
|
||||
- [ ] Delete old zips: artifacts/release/ThreadPilot_v1.1.0_Installer.zip, artifacts/release/ThreadPilot_v1.1.0_Portable.zip
|
||||
- [ ] Delete temporary staging dirs: artifacts/release/package-stage, artifacts/release/_stage_installer, artifacts/release/_stage_portable
|
||||
|
||||
Expected state:
|
||||
|
||||
- [ ] artifacts/release/installer/ThreadPilot_v1.1.1_Setup.exe
|
||||
- [ ] artifacts/release/msix/ThreadPilot_1.1.1.0_win-x64.msix
|
||||
- [ ] artifacts/release/packages/ThreadPilot_v1.1.1_Installer.zip
|
||||
- [ ] artifacts/release/packages/ThreadPilot_v1.1.1_Portable.zip
|
||||
|
||||
@@ -44,11 +42,9 @@ Commands:
|
||||
Commands:
|
||||
|
||||
./build/build-installer.ps1 -Version "1.1.1"
|
||||
dotnet publish "ThreadPilot.csproj" --configuration Release -p:PublishProfile=WinX64-MSIX
|
||||
./build/package-release-zips.ps1 -Version "1.1.1"
|
||||
|
||||
- [ ] Installer generated in artifacts/release/installer
|
||||
- [ ] MSIX generated in artifacts/release/msix
|
||||
- [ ] Zip packages generated in artifacts/release/packages
|
||||
- [ ] Inno Setup warnings target is zero (artifacts/release/installer_iscc_setup.log)
|
||||
|
||||
@@ -78,7 +74,6 @@ Commands:
|
||||
$releaseFiles = @()
|
||||
$releaseFiles += Get-ChildItem "artifacts/release/packages" -File -ErrorAction SilentlyContinue
|
||||
$releaseFiles += Get-ChildItem "artifacts/release/installer/*.exe" -File -ErrorAction SilentlyContinue
|
||||
$releaseFiles += Get-ChildItem "artifacts/release/msix" -Recurse -File -Include *.msix,*.appx,*.msixbundle,*.appxbundle -ErrorAction SilentlyContinue
|
||||
|
||||
$releaseFiles | ForEach-Object {
|
||||
$hash = Get-FileHash $_.FullName -Algorithm SHA256
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
| Build | Complete | Yes | Release build currently passing |
|
||||
| Tests | Complete | Yes | Core test suite currently green |
|
||||
| Security scan | Complete | Yes | No vulnerable packages and no secret leaks |
|
||||
| Packaging | Complete | Yes | Installer, msix, zip artifacts and checksums generated |
|
||||
| Packaging | Complete | Yes | Installer, portable zip artifacts and checksums generated |
|
||||
| Documentation | Complete | Yes | Release docs and governance artifacts updated |
|
||||
| Compatibility smoke tests | Deferred | Yes | Execute on final release candidate |
|
||||
|
||||
|
||||
@@ -7,16 +7,15 @@ This document describes production packaging for ThreadPilot v1.1.1.
|
||||
- Windows 11 build machine (or GitHub Actions `windows-latest`)
|
||||
- .NET SDK 8.x
|
||||
- Optional for signing:
|
||||
- Code-signing certificate (`.pfx`) for Authenticode/MSIX signing
|
||||
- Code-signing certificate (`.pfx`) for Authenticode signing
|
||||
- Optional strong-name key (`.snk`) if strong naming is required
|
||||
|
||||
## Publish Profiles
|
||||
|
||||
The repository provides three publish profiles under `Properties/PublishProfiles`:
|
||||
The repository provides two publish profiles under `Properties/PublishProfiles`:
|
||||
|
||||
- `WinX64-SingleFile.pubxml`
|
||||
- `WinX64-ReadyToRun.pubxml`
|
||||
- `WinX64-MSIX.pubxml`
|
||||
|
||||
Shared packaging defaults are in `Directory.Publish.props`.
|
||||
|
||||
@@ -72,19 +71,6 @@ Output folder:
|
||||
|
||||
- `artifacts/release/readytorun/`
|
||||
|
||||
### 4) MSIX package (secondary)
|
||||
|
||||
```powershell
|
||||
dotnet publish ThreadPilot.csproj -c Release -p:PublishProfile=WinX64-MSIX
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
- `artifacts/release/msix/ThreadPilot_<version>_win-x64.msix`
|
||||
- `artifacts/release/msix/publish/` (packaging input folder used to create the MSIX)
|
||||
|
||||
`WinX64-MSIX.pubxml` enables a post-publish packaging target that calls `build/build-msix.ps1` and creates the `.msix` using the Windows SDK `makeappx.exe` tool.
|
||||
|
||||
## Code Signing
|
||||
|
||||
### Strong name (optional)
|
||||
@@ -108,11 +94,6 @@ Sign binaries after publish:
|
||||
signtool sign /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 /f path\to\cert.pfx /p <password> artifacts\release\singlefile\ThreadPilot.exe
|
||||
```
|
||||
|
||||
For MSIX signing:
|
||||
|
||||
- Sign the produced `.msix`/`.appx` using `signtool` with the same certificate.
|
||||
- Keep `AppxPackageSigningEnabled=false` in profile and sign in CI so secrets are not stored in project files.
|
||||
|
||||
## CI Signing Placeholders
|
||||
|
||||
`.github/workflows/release.yml` supports optional signing with these repository secrets:
|
||||
@@ -125,7 +106,7 @@ Expose these values to the workflow as environment variables (same names) via re
|
||||
When both secrets are present:
|
||||
|
||||
1. The workflow decodes the certificate to the runner temp directory.
|
||||
2. `signtool.exe` signs `.exe` and MSIX/AppX artifacts before ZIP packaging.
|
||||
2. `signtool.exe` signs `.exe` artifacts before ZIP packaging.
|
||||
3. SHA-256 checksums are generated for signed outputs.
|
||||
|
||||
When secrets are missing, the release still builds and publishes unsigned artifacts.
|
||||
@@ -145,10 +126,9 @@ iscc Installer/setup.iss
|
||||
3. `dotnet test ThreadPilot_1.sln --configuration Release --no-build`
|
||||
4. Publish Single-file and ReadyToRun profiles
|
||||
5. Build Inno Setup installer from Single-file output
|
||||
6. Publish MSIX as secondary artifact
|
||||
7. Sign artifacts
|
||||
8. Generate SHA-256 checksums
|
||||
9. Upload release artifacts
|
||||
6. Sign artifacts
|
||||
7. Generate SHA-256 checksums
|
||||
8. Upload release artifacts
|
||||
|
||||
Optional automation for publishing the GitHub release after artifacts are ready:
|
||||
|
||||
@@ -163,8 +143,6 @@ The release workflow (`.github/workflows/release.yml`) now builds:
|
||||
- Inno Setup installer (`.exe`) as primary installer artifact
|
||||
- Single-file package (ZIP)
|
||||
- ReadyToRun package (ZIP)
|
||||
- MSIX artifact (secondary)
|
||||
- SHA-256 checksum manifest
|
||||
- Optional signing of EXE/MSIX artifacts when signing secrets are configured
|
||||
- Explicit MSIX validation (workflow fails if no package artifact is generated)
|
||||
- Optional signing of EXE artifacts when signing secrets are configured
|
||||
|
||||
|
||||
@@ -6,21 +6,18 @@ Scope: Final one-shot packaging execution after completion of non-packaging phas
|
||||
## Commands Executed
|
||||
|
||||
1. build/build-installer.ps1 -Version 1.1.1
|
||||
2. dotnet publish ThreadPilot.csproj --configuration Release -p:PublishProfile=WinX64-MSIX
|
||||
3. build/package-release-zips.ps1 -Version 1.1.1
|
||||
4. SHA256 manifest generation to artifacts/release/SHA256SUMS.txt
|
||||
2. build/package-release-zips.ps1 -Version 1.1.1
|
||||
3. SHA256 manifest generation to artifacts/release/SHA256SUMS.txt
|
||||
|
||||
## Result
|
||||
|
||||
- Installer build: success
|
||||
- MSIX publish: success
|
||||
- Release ZIP packaging: success
|
||||
- Checksum generation: success
|
||||
|
||||
## Produced Artifacts
|
||||
|
||||
- artifacts/release/installer/ThreadPilot_v1.1.1_Setup.exe
|
||||
- artifacts/release/msix/ThreadPilot_1.1.1.0_win-x64.msix
|
||||
- artifacts/release/packages/ThreadPilot_v1.1.1_Portable.zip
|
||||
- artifacts/release/packages/ThreadPilot_v1.1.1_Installer.zip
|
||||
- artifacts/release/SHA256SUMS.txt
|
||||
|
||||
@@ -17,24 +17,18 @@ Date: 2026-04-15
|
||||
./build/build-installer.ps1 -Version "<version>"
|
||||
```
|
||||
|
||||
2. Build MSIX (secondary artifact):
|
||||
|
||||
```powershell
|
||||
dotnet publish ThreadPilot.csproj --configuration Release -p:PublishProfile=WinX64-MSIX
|
||||
```
|
||||
|
||||
3. Build ZIP packages:
|
||||
2. Build ZIP packages:
|
||||
|
||||
```powershell
|
||||
./build/package-release-zips.ps1 -Version "<version>"
|
||||
```
|
||||
|
||||
4. Generate checksums:
|
||||
3. Generate checksums:
|
||||
|
||||
```powershell
|
||||
$hashFile = "artifacts/release/SHA256SUMS.txt"
|
||||
if (Test-Path $hashFile) { Remove-Item $hashFile -Force }
|
||||
Get-ChildItem "artifacts/release" -Recurse -File -Include *.zip,*.exe,*.msix,*.appx,*.msixbundle,*.appxbundle |
|
||||
Get-ChildItem "artifacts/release" -Recurse -File -Include *.zip,*.exe |
|
||||
ForEach-Object {
|
||||
$hash = Get-FileHash $_.FullName -Algorithm SHA256
|
||||
"$($hash.Hash) $($_.Name)" | Out-File -FilePath $hashFile -Append -Encoding utf8
|
||||
|
||||
Reference in New Issue
Block a user