Skip to content

feat: add auto updater #117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion .github/workflows/release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ jobs:
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
token_format: "access_token"

- name: Install gcloud
uses: google-github-actions/setup-gcloud@77e7a554d41e2ee56fc945c52dfd3f33d12def9a # 2.1.4

- name: Install wix
shell: pwsh
run: |
Expand Down Expand Up @@ -120,6 +123,51 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

- name: Update appcast
if: startsWith(github.ref, 'refs/tags/')
shell: pwsh
run: |
$ErrorActionPreference = "Stop"

# The Update-AppCast.ps1 script fetches the release notes from GitHub,
# which might take a few seconds to be ready.
Start-Sleep -Seconds 10

# Save the appcast signing key to a temporary file.
$keyPath = Join-Path $env:TEMP "appcast-key.pem"
$key = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($env:APPCAST_SIGNATURE_KEY_BASE64))
Set-Content -Path $keyPath -Value $key

# Download the old appcast from GCS.
$oldAppCastPath = Join-Path $env:TEMP "appcast.old.xml"
& gsutil cp $env:APPCAST_GCS_URI $oldAppCastPath
if ($LASTEXITCODE -ne 0) { throw "Failed to download appcast" }

# Generate the new appcast and signature.
$newAppCastPath = Join-Path $env:TEMP "appcast.new.xml"
$newAppCastSignaturePath = $newAppCastPath + ".signature"
& ./scripts/Update-AppCast.ps1 `
-tag "${{ github.ref_name }}" `
-channel stable `
-x64Path "${{ steps.release.outputs.X64_OUTPUT_PATH }}" `
-arm64Path "${{ steps.release.outputs.ARM64_OUTPUT_PATH }}" `
-keyPath $keyPath `
-inputAppCastPath $oldAppCastPath `
-outputAppCastPath $newAppCastPath `
-outputAppCastSignaturePath $newAppCastSignaturePath
if ($LASTEXITCODE -ne 0) { throw "Failed to generate new appcast" }

# Upload the new appcast and signature to GCS.
& gsutil -h "Cache-Control:no-cache,max-age=0" cp $newAppCastPath $env:APPCAST_GCS_URI
if ($LASTEXITCODE -ne 0) { throw "Failed to upload new appcast" }
& gsutil -h "Cache-Control:no-cache,max-age=0" cp $newAppCastSignaturePath $env:APPCAST_SIGNATURE_GCS_URI
if ($LASTEXITCODE -ne 0) { throw "Failed to upload new appcast signature" }
env:
APPCAST_GCS_URI: gs://releases.coder.com/coder-desktop/windows/appcast.xml
APPCAST_SIGNATURE_GCS_URI: gs://releases.coder.com/coder-desktop/windows/appcast.xml.signature
APPCAST_SIGNATURE_KEY_BASE64: ${{ secrets.APPCAST_SIGNATURE_KEY_BASE64 }}
GCLOUD_ACCESS_TOKEN: ${{ steps.gcloud_auth.outputs.access_token }}

winget:
runs-on: depot-windows-latest
needs: release
Expand Down Expand Up @@ -177,7 +225,6 @@ jobs:
# to GitHub and then making a PR in a different repo.
WINGET_GH_TOKEN: ${{ secrets.CDRCI_GITHUB_TOKEN }}


- name: Comment on PR
run: |
# wait 30 seconds
Expand Down
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -411,3 +411,12 @@ publish
*.wixmdb
*.wixprj
*.wixproj

appcast.xml
appcast.xml.signature
*.key
*.key.*
*.pem
*.pem.*
*.pub
*.pub.*
13 changes: 10 additions & 3 deletions App/App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
<DefineConstants>DISABLE_XAML_GENERATED_MAIN;DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION</DefineConstants>

<AssemblyName>Coder Desktop</AssemblyName>
<AssemblyTitle>Coder Desktop</AssemblyTitle>
<Company>Coder Technologies Inc.</Company>
<Product>Coder Desktop</Product>
<Copyright>© Coder Technologies Inc.</Copyright>
<ApplicationIcon>coder.ico</ApplicationIcon>
</PropertyGroup>

Expand All @@ -31,9 +35,7 @@

<ItemGroup>
<Content Include="coder.ico" />
</ItemGroup>

<ItemGroup>
<EmbeddedResource Include="Assets\changelog.css" />
<Manifest Include="$(ApplicationManifest)" />
</ItemGroup>

Expand Down Expand Up @@ -68,12 +70,17 @@
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.4" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.6.250108002" />
<PackageReference Include="NetSparkleUpdater.SparkleUpdater" Version="3.0.2" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="WinUIEx" Version="2.5.1" />
</ItemGroup>

<ItemGroup Condition="'$(Configuration)' == 'Debug'">
<PackageReference Include="Serilog.Sinks.Debug" Version="3.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CoderSdk\CoderSdk.csproj" />
<ProjectReference Include="..\MutagenSdk\MutagenSdk.csproj" />
Expand Down
69 changes: 54 additions & 15 deletions App/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,38 @@
using Microsoft.Win32;
using Microsoft.Windows.AppLifecycle;
using Microsoft.Windows.AppNotifications;
using NetSparkleUpdater.Interfaces;
using Serilog;
using LaunchActivatedEventArgs = Microsoft.UI.Xaml.LaunchActivatedEventArgs;

namespace Coder.Desktop.App;

public partial class App : Application
{
private readonly IServiceProvider _services;

private bool _handleWindowClosed = true;
private const string MutagenControllerConfigSection = "MutagenController";
private const string UpdaterConfigSection = "Updater";

#if !DEBUG
private const string ConfigSubKey = @"SOFTWARE\Coder Desktop\App";
private const string logFilename = "app.log";
private const string LogFilename = "app.log";
private const string DefaultLogLevel = "Information";
#else
private const string ConfigSubKey = @"SOFTWARE\Coder Desktop\DebugApp";
private const string logFilename = "debug-app.log";
private const string LogFilename = "debug-app.log";
private const string DefaultLogLevel = "Debug";
#endif

// HACK: This is exposed for dispatcher queue access. The notifier uses
// this to ensure action callbacks run in the UI thread (as
// activation events aren't in the main thread).
public TrayWindow? TrayWindow;

private readonly IServiceProvider _services;
private readonly ILogger<App> _logger;
private readonly IUriHandler _uriHandler;
private readonly IUserNotifier _userNotifier;

private bool _handleWindowClosed = true;

private readonly ISettingsManager<CoderConnectSettings> _settingsManager;

Expand All @@ -58,7 +68,17 @@ public App()
configBuilder.Add(
new RegistryConfigurationSource(Registry.LocalMachine, ConfigSubKey));
configBuilder.Add(
new RegistryConfigurationSource(Registry.CurrentUser, ConfigSubKey));
new RegistryConfigurationSource(
Registry.CurrentUser,
ConfigSubKey,
// Block "Updater:" configuration from HKCU, so that updater
// settings can only be set at the HKLM level.
//
// HACK: This isn't super robust, but the security risk is
// minor anyway. Malicious apps running as the user could
// likely override this setting by altering the memory of
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One way to remove this risk is by always treating registry as a source of truth instead of relying on the in-memory value to block this.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think reading directly from registry would prevent people from attaching a debugger to override this if they really wanted to. Unless there's an easy solution (that isn't hacky, like reading the registry directly in SparkleUpdateController) I don't think it's worth making changes to this

// this app.
UpdaterConfigSection + ":"));

var services = builder.Services;

Expand All @@ -71,6 +91,7 @@ public App()
services.AddSingleton<ICoderApiClientFactory, CoderApiClientFactory>();
services.AddSingleton<IAgentApiClientFactory, AgentApiClientFactory>();

services.AddSingleton<IDispatcherQueueManager, AppDispatcherQueueManager>();
services.AddSingleton<ICredentialBackend>(_ =>
new WindowsCredentialBackend(WindowsCredentialBackend.CoderCredentialsTargetName));
services.AddSingleton<ICredentialManager, CredentialManager>();
Expand All @@ -84,6 +105,12 @@ public App()
services.AddSingleton<IRdpConnector, RdpConnector>();
services.AddSingleton<IUriHandler, UriHandler>();

services.AddOptions<UpdaterConfig>()
.Bind(builder.Configuration.GetSection(UpdaterConfigSection));
services.AddSingleton<IUpdaterUpdateAvailableViewModelFactory, UpdaterUpdateAvailableViewModelFactory>();
services.AddSingleton<IUIFactory, CoderSparkleUIFactory>();
services.AddSingleton<IUpdateController, SparkleUpdateController>();

// SignInWindow views and view models
services.AddTransient<SignInViewModel>();
services.AddTransient<SignInWindow>();
Expand Down Expand Up @@ -119,6 +146,7 @@ public App()
_services = services.BuildServiceProvider();
_logger = _services.GetRequiredService<ILogger<App>>();
_uriHandler = _services.GetRequiredService<IUriHandler>();
_userNotifier = _services.GetRequiredService<IUserNotifier>();
_settingsManager = _services.GetRequiredService<ISettingsManager<CoderConnectSettings>>();
_appLifetime = _services.GetRequiredService<IHostApplicationLifetime>();

Expand All @@ -142,16 +170,18 @@ protected override void OnLaunched(LaunchActivatedEventArgs args)
{
_logger.LogInformation("new instance launched");

_ = InitializeServicesAsync(_appLifetime.ApplicationStopping);

// Prevent the TrayWindow from closing, just hide it.
var trayWindow = _services.GetRequiredService<TrayWindow>();
trayWindow.Closed += (_, closedArgs) =>
if (TrayWindow != null)
throw new InvalidOperationException("OnLaunched was called multiple times? TrayWindow is already set");
TrayWindow = _services.GetRequiredService<TrayWindow>();
TrayWindow.Closed += (_, closedArgs) =>
{
if (!_handleWindowClosed) return;
closedArgs.Handled = true;
trayWindow.AppWindow.Hide();
TrayWindow.AppWindow.Hide();
};

_ = InitializeServicesAsync(_appLifetime.ApplicationStopping);
}

/// <summary>
Expand Down Expand Up @@ -261,27 +291,36 @@ public void OnActivated(object? sender, AppActivationArguments args)

public void HandleNotification(AppNotificationManager? sender, AppNotificationActivatedEventArgs args)
{
// right now, we don't do anything other than log
_logger.LogInformation("handled notification activation");
_logger.LogInformation("handled notification activation: {Argument}", args.Argument);
_userNotifier.HandleNotificationActivation(args.Arguments);
}

private static void AddDefaultConfig(IConfigurationBuilder builder)
{
var logPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CoderDesktop",
logFilename);
LogFilename);
builder.AddInMemoryCollection(new Dictionary<string, string?>
{
[MutagenControllerConfigSection + ":MutagenExecutablePath"] = @"C:\mutagen.exe",

["Serilog:Using:0"] = "Serilog.Sinks.File",
["Serilog:MinimumLevel"] = "Information",
["Serilog:MinimumLevel"] = DefaultLogLevel,
["Serilog:Enrich:0"] = "FromLogContext",
["Serilog:WriteTo:0:Name"] = "File",
["Serilog:WriteTo:0:Args:path"] = logPath,
["Serilog:WriteTo:0:Args:outputTemplate"] =
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} - {Message:lj}{NewLine}{Exception}",
["Serilog:WriteTo:0:Args:rollingInterval"] = "Day",

#if DEBUG
["Serilog:Using:1"] = "Serilog.Sinks.Debug",
["Serilog:Enrich:1"] = "FromLogContext",
["Serilog:WriteTo:1:Name"] = "Debug",
["Serilog:WriteTo:1:Args:outputTemplate"] =
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} - {Message:lj}{NewLine}{Exception}",
#endif
});
}
}
Loading
Loading