Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6eead05308 | |||
| 673a972598 | |||
| f44589454c |
@@ -25,4 +25,7 @@ public static class TypeConverters
|
||||
|
||||
public static FuncValueConverter<string, Avalonia.Media.Color> NameColorRepresentation { get; } =
|
||||
new((str)=>ColorUtils.GetColorFromString(str ?? throw new ArgumentNullException(nameof(str),"Name of color is null!")));
|
||||
|
||||
public static FuncValueConverter<string, bool> StringIsNotEmpty { get; } =
|
||||
new(iconKey => !string.IsNullOrEmpty(iconKey));
|
||||
}
|
||||
@@ -14,10 +14,11 @@ public static class LauncherConVar
|
||||
public static readonly ConVar<bool> DoMigration =
|
||||
ConVarBuilder.Build("migration.doMigrate", true);
|
||||
|
||||
public static readonly ConVar<AuthTokenCredentials[]> AuthProfiles =
|
||||
ConVarBuilder.BuildWithMigration<AuthTokenCredentials[]>("auth.profiles.v3",
|
||||
public static readonly ConVar<string[]> AuthProfiles =
|
||||
ConVarBuilder.BuildWithMigration<string[]>("auth.profiles.v4",
|
||||
MigrationQueueBuilder.Instance
|
||||
.With(new ProfileMigrationV2("auth.profiles.v2","auth.profiles.v3"))
|
||||
.With(new ProfileMigrationV2("auth.profiles.v2","auth.profiles.v4"))
|
||||
.With(new ProfileMigrationV3V4("auth.profiles.v3","auth.profiles.v4"))
|
||||
.Build(),
|
||||
[]);
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ using Nebula.Shared.Services;
|
||||
|
||||
namespace Nebula.Launcher.Models.Auth;
|
||||
|
||||
public sealed record ProfileAuthCredentials(
|
||||
AuthTokenCredentials Credentials,
|
||||
public sealed record ProfileEntry(
|
||||
ProfileAuthCredentials Credentials,
|
||||
string AuthName,
|
||||
[property: JsonIgnore] ICommand OnSelect = default!,
|
||||
[property: JsonIgnore] ICommand OnDelete = default!);
|
||||
@@ -31,7 +31,7 @@
|
||||
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0"/>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0"/>
|
||||
<PackageReference Include="libsodium" Version="1.0.20"/>
|
||||
<PackageReference Include="Robust.Natives" Version="0.1.1" />
|
||||
<PackageReference Include="Robust.Natives" Version="0.2.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -74,6 +74,7 @@ public sealed partial class HubServerListProvider : IServerListProvider
|
||||
catch (Exception e)
|
||||
{
|
||||
_errors.Add(new Exception($"Some error while loading server list from {HubUrl}. See inner exception", e));
|
||||
_errors.Add(e);
|
||||
}
|
||||
|
||||
IsLoaded = true;
|
||||
|
||||
@@ -114,7 +114,7 @@ public partial class MainViewModel : ViewModelBase
|
||||
{ "login", AccountInfoViewModel.Credentials.Value?.Login ?? "" },
|
||||
{
|
||||
"auth_server",
|
||||
AccountInfoViewModel.GetServerAuthName(AccountInfoViewModel.Credentials.Value) ?? ""
|
||||
AccountInfoViewModel.GetServerAuthName(AccountInfoViewModel.Credentials.Value?.AuthServer) ?? ""
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -34,13 +34,13 @@ public partial class AccountInfoViewModel : ViewModelBase
|
||||
[ObservableProperty] private AuthServerCredentials _authItemSelect;
|
||||
|
||||
private bool _isProfilesEmpty;
|
||||
[GenerateProperty] private PopupMessageService PopupMessageService { get; } = default!;
|
||||
[GenerateProperty] private ConfigurationService ConfigurationService { get; } = default!;
|
||||
[GenerateProperty] private PopupMessageService PopupMessageService { get; }
|
||||
[GenerateProperty] private ConfigurationService ConfigurationService { get; }
|
||||
[GenerateProperty] private DebugService DebugService { get; }
|
||||
[GenerateProperty] private AuthService AuthService { get; } = default!;
|
||||
[GenerateProperty, DesignConstruct] private ViewHelperService ViewHelperService { get; } = default!;
|
||||
[GenerateProperty] private AuthService AuthService { get; }
|
||||
[GenerateProperty, DesignConstruct] private ViewHelperService ViewHelperService { get; }
|
||||
|
||||
public ObservableCollection<ProfileAuthCredentials> Accounts { get; } = new();
|
||||
public ObservableCollection<ProfileEntry> Accounts { get; } = new();
|
||||
public ObservableCollection<AuthServerCredentials> AuthUrls { get; } = new();
|
||||
|
||||
public ComplexConVarBinder<AuthTokenCredentials?> Credentials { get; private set; }
|
||||
@@ -50,10 +50,10 @@ public partial class AccountInfoViewModel : ViewModelBase
|
||||
//Design think
|
||||
protected override void InitialiseInDesignMode()
|
||||
{
|
||||
AuthUrls.Add(new AuthServerCredentials("Test",["example.com"]));
|
||||
AuthUrls.Add(new AuthServerCredentials("Test",["example.com","variant.lab"]));
|
||||
|
||||
AddAccount(new AuthTokenCredentials(Guid.Empty, LoginToken.Empty, "Binka", "example.com"));
|
||||
AddAccount(new AuthTokenCredentials(Guid.Empty, LoginToken.Empty, "Binka", ""));
|
||||
AddAccount(new ProfileAuthCredentials("Binka", "","example.com"));
|
||||
AddAccount(new ProfileAuthCredentials("Vilka","", "variant.lab"));
|
||||
}
|
||||
|
||||
//Real think
|
||||
@@ -197,21 +197,16 @@ public partial class AccountInfoViewModel : ViewModelBase
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTfaEntered(string code)
|
||||
{
|
||||
DoAuth(code);
|
||||
}
|
||||
|
||||
public void Logout()
|
||||
{
|
||||
Credentials.Value = null;
|
||||
CurrentAuthServer = "";
|
||||
}
|
||||
|
||||
public string GetServerAuthName(AuthTokenCredentials? credentials)
|
||||
public string GetServerAuthName(string? url)
|
||||
{
|
||||
if (credentials is null) return "";
|
||||
return AuthUrls.FirstOrDefault(p => p.Servers.Contains(credentials.AuthServer))?.Name ?? "CustomAuth";
|
||||
if (url is null) return "";
|
||||
return AuthUrls.FirstOrDefault(p => p.Servers.Contains(url))?.Name ?? "CustomAuth";
|
||||
}
|
||||
|
||||
private void UpdateAuthMenu()
|
||||
@@ -222,14 +217,20 @@ public partial class AccountInfoViewModel : ViewModelBase
|
||||
AuthViewSpan = 1;
|
||||
}
|
||||
|
||||
private void AddAccount(AuthTokenCredentials credentials)
|
||||
private void AddAccount(ProfileAuthCredentials credentials)
|
||||
{
|
||||
var onDelete = new DelegateCommand<ProfileAuthCredentials>(OnDeleteProfile);
|
||||
var onSelect = new DelegateCommand<ProfileAuthCredentials>((p) => Credentials.Value = p.Credentials);
|
||||
var onDelete = new DelegateCommand<ProfileEntry>(OnDeleteProfile);
|
||||
var onSelect = new DelegateCommand<ProfileEntry>((p) =>
|
||||
{
|
||||
CurrentLogin = p.Credentials.Login;
|
||||
CurrentPassword = p.Credentials.Password;
|
||||
CurrentAuthServer = p.Credentials.AuthServer;
|
||||
DoAuth();
|
||||
});
|
||||
|
||||
var serverName = GetServerAuthName(credentials);
|
||||
var serverName = GetServerAuthName(credentials.AuthServer);
|
||||
|
||||
var alpm = new ProfileAuthCredentials(
|
||||
var alpm = new ProfileEntry(
|
||||
credentials,
|
||||
serverName,
|
||||
onSelect,
|
||||
@@ -255,22 +256,28 @@ public partial class AccountInfoViewModel : ViewModelBase
|
||||
foreach (var url in authUrls) AuthUrls.Add(url);
|
||||
if(authUrls.Length > 0) AuthItemSelect = authUrls[0];
|
||||
|
||||
var profileCandidates = new List<AuthTokenCredentials>();
|
||||
var profileCandidates = new List<string>();
|
||||
|
||||
foreach (var profile in
|
||||
foreach (var profileRaw in
|
||||
ConfigurationService.GetConfigValue(LauncherConVar.AuthProfiles)!)
|
||||
{
|
||||
_logger.Log($"Reading profile {profile.Login}");
|
||||
var checkedCredit = await CheckOrRenewToken(profile);
|
||||
if(checkedCredit is null)
|
||||
_logger.Log($"Decrypting profile...");
|
||||
try
|
||||
{
|
||||
_logger.Error($"Profile {profile.Login} is not available");
|
||||
continue;
|
||||
}
|
||||
var decoded =
|
||||
await CryptographicStore.Decrypt<ProfileAuthCredentials>(profileRaw,
|
||||
CryptographicStore.GetComputerKey());
|
||||
|
||||
_logger.Log($"Profile {profile.Login} is available");
|
||||
profileCandidates.Add(checkedCredit);
|
||||
AddAccount(checkedCredit);
|
||||
_logger.Log($"Decrypted profile: {decoded.Login}");
|
||||
|
||||
profileCandidates.Add(profileRaw);
|
||||
AddAccount(decoded);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error("Error while decrypting profile");
|
||||
_logger.Error(e);
|
||||
}
|
||||
}
|
||||
|
||||
ConfigurationService.SetConfigValue(LauncherConVar.AuthProfiles, profileCandidates.ToArray());
|
||||
@@ -297,14 +304,17 @@ public partial class AccountInfoViewModel : ViewModelBase
|
||||
_logger.Log("Token " + authTokenCredentials.Login + " is active, "+daysLeft+" days left, undo renewing!");
|
||||
return authTokenCredentials;
|
||||
}
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
_logger.Log($"Renewing token for {authTokenCredentials.Login}");
|
||||
return await ExceptionHelper.TryRun(() => AuthService.Refresh(authTokenCredentials),3, (attempt, e) =>
|
||||
{
|
||||
_logger.Error(new Exception("Error while renewing, attempts: " + attempt, e));
|
||||
});
|
||||
return await ExceptionHelper.TryRun(() => AuthService.Refresh(authTokenCredentials), 3,
|
||||
(attempt, e) => { _logger.Error(new Exception("Error while renewing, attempts: " + attempt, e)); });
|
||||
}
|
||||
catch (AuthTokenExpiredException e)
|
||||
{
|
||||
_logger.Error(e);
|
||||
return null;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -316,15 +326,16 @@ public partial class AccountInfoViewModel : ViewModelBase
|
||||
|
||||
public void OnSaveProfile()
|
||||
{
|
||||
if(Credentials.Value is null) return;
|
||||
if(Credentials.Value is null ||
|
||||
string.IsNullOrEmpty(CurrentPassword)) return;
|
||||
|
||||
AddAccount(Credentials.Value);
|
||||
AddAccount(new ProfileAuthCredentials(CurrentLogin, CurrentPassword, Credentials.Value.AuthServer));
|
||||
_isProfilesEmpty = Accounts.Count == 0;
|
||||
UpdateAuthMenu();
|
||||
DirtyProfile();
|
||||
}
|
||||
|
||||
private void OnDeleteProfile(ProfileAuthCredentials account)
|
||||
private void OnDeleteProfile(ProfileEntry account)
|
||||
{
|
||||
Accounts.Remove(account);
|
||||
_isProfilesEmpty = Accounts.Count == 0;
|
||||
@@ -357,7 +368,7 @@ public partial class AccountInfoViewModel : ViewModelBase
|
||||
private void DirtyProfile()
|
||||
{
|
||||
ConfigurationService.SetConfigValue(LauncherConVar.AuthProfiles,
|
||||
Accounts.Select(a => a.Credentials).ToArray());
|
||||
Accounts.Select(a => CryptographicStore.Encrypt(a.Credentials, CryptographicStore.GetComputerKey())).ToArray());
|
||||
}
|
||||
|
||||
public sealed class AuthTokenCredentialsVar(AccountInfoViewModel accountInfoViewModel)
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
ItemsSource="{Binding Accounts}"
|
||||
Padding="0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type auth:ProfileAuthCredentials}">
|
||||
<DataTemplate DataType="{x:Type auth:ProfileEntry}">
|
||||
<Grid ColumnDefinitions="4*,*">
|
||||
<Border
|
||||
BoxShadow="0 1 15 -2 #121212"
|
||||
@@ -209,7 +209,9 @@
|
||||
<customControls:LocalizedLabel LocalId="account-auth-logout"/>
|
||||
</Button>
|
||||
</Border>
|
||||
<Border BoxShadow="{StaticResource DefaultShadow}">
|
||||
<Border BoxShadow="{StaticResource DefaultShadow}"
|
||||
IsVisible="{Binding CurrentPassword,
|
||||
Converter={x:Static converters:TypeConverters.StringIsNotEmpty}}">
|
||||
<Button Command="{Binding OnSaveProfile}">
|
||||
<customControls:LocalizedLabel LocalId="account-auth-save"/>
|
||||
</Button>
|
||||
|
||||
@@ -2,16 +2,17 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
using Nebula.Shared.Configurations.Migrations;
|
||||
using Nebula.Shared.Models;
|
||||
using Nebula.Shared.Services;
|
||||
using Nebula.Shared.Utils;
|
||||
|
||||
namespace Nebula.Shared.ConfigMigrations;
|
||||
|
||||
public class ProfileMigrationV2(string oldName, string newName)
|
||||
: BaseConfigurationMigration<ProfileAuthCredentialsV2[], AuthTokenCredentials[]>(oldName, newName)
|
||||
: BaseConfigurationMigration<ProfileAuthCredentials[], string[]>(oldName, newName)
|
||||
{
|
||||
protected override async Task<AuthTokenCredentials[]> Migrate(IServiceProvider serviceProvider, ProfileAuthCredentialsV2[] oldValue, ILoadingHandler loadingHandler)
|
||||
protected override async Task<string[]> Migrate(IServiceProvider serviceProvider, ProfileAuthCredentials[] oldValue, ILoadingHandler loadingHandler)
|
||||
{
|
||||
loadingHandler.SetLoadingMessage("Migrating Profile V2 -> V3");
|
||||
var list = new List<AuthTokenCredentials>();
|
||||
loadingHandler.SetLoadingMessage("Migrating Profile V2 -> V4");
|
||||
var list = new List<string>();
|
||||
var authService = serviceProvider.GetRequiredService<AuthService>();
|
||||
var logger = serviceProvider.GetRequiredService<DebugService>().GetLogger("ProfileMigrationV2");
|
||||
foreach (var oldCredentials in oldValue)
|
||||
@@ -19,8 +20,8 @@ public class ProfileMigrationV2(string oldName, string newName)
|
||||
try
|
||||
{
|
||||
loadingHandler.SetLoadingMessage($"Migrating {oldCredentials.Login}");
|
||||
var newCred = await authService.Auth(oldCredentials.Login, oldCredentials.Password, oldCredentials.AuthServer);
|
||||
list.Add(newCred);
|
||||
await authService.Auth(oldCredentials.Login, oldCredentials.Password, oldCredentials.AuthServer);
|
||||
list.Add(CryptographicStore.Encrypt(oldCredentials, CryptographicStore.GetComputerKey()));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -34,7 +35,13 @@ public class ProfileMigrationV2(string oldName, string newName)
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record ProfileAuthCredentialsV2(
|
||||
string Login,
|
||||
string Password,
|
||||
string AuthServer);
|
||||
public class ProfileMigrationV3V4(string oldName, string newName)
|
||||
: BaseConfigurationMigration<AuthTokenCredentials[], string[]>(oldName, newName)
|
||||
{
|
||||
protected override Task<string[]> Migrate(IServiceProvider serviceProvider, AuthTokenCredentials[] oldValue, ILoadingHandler loadingHandler)
|
||||
{
|
||||
Console.WriteLine("Removing profile v3 because no password is provided");
|
||||
return Task.FromResult(Array.Empty<string>());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
<LogicalName>Utility.runtime.json</LogicalName>
|
||||
</EmbeddedResource>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0" />
|
||||
<PackageReference Include="Robust.Natives" Version="0.1.1" />
|
||||
<PackageReference Include="Robust.Natives" Version="0.2.3" />
|
||||
<PackageReference Include="SharpZstd.Interop" Version="1.5.6" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ public class AuthService(
|
||||
var err = await e.Content.AsJson<AuthDenyError>();
|
||||
|
||||
if (err is null) throw;
|
||||
e.Dispose();
|
||||
throw new AuthException(err);
|
||||
}
|
||||
}
|
||||
@@ -60,14 +61,36 @@ public class AuthService(
|
||||
public async Task<AuthTokenCredentials> Refresh(AuthTokenCredentials tokenCredentials)
|
||||
{
|
||||
var authUrl = new Uri($"{tokenCredentials.AuthServer}api/auth/refresh");
|
||||
var newToken = await restService.PostAsync<LoginToken, TokenRequest>(
|
||||
TokenRequest.From(tokenCredentials), authUrl, cancellationService.Token);
|
||||
|
||||
return tokenCredentials with { Token = newToken };
|
||||
try
|
||||
{
|
||||
var newToken = await restService.PostAsync<LoginToken, TokenRequest>(
|
||||
TokenRequest.From(tokenCredentials), authUrl, cancellationService.Token);
|
||||
|
||||
return tokenCredentials with { Token = newToken };
|
||||
}
|
||||
catch (RestRequestException e)
|
||||
{
|
||||
if (e.StatusCode == HttpStatusCode.Unauthorized)
|
||||
throw new AuthTokenExpiredException(tokenCredentials);
|
||||
|
||||
e.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class AuthTokenExpiredException : Exception
|
||||
{
|
||||
public AuthTokenExpiredException(AuthTokenCredentials credentials): base("Taken token is expired. Login: " + credentials.Login)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record AuthTokenCredentials(Guid UserId, LoginToken Token, string Login, string AuthServer);
|
||||
public sealed record ProfileAuthCredentials(
|
||||
string Login,
|
||||
string Password,
|
||||
string AuthServer);
|
||||
|
||||
public sealed record AuthDenyError(string[] Errors, AuthenticateDenyCode Code);
|
||||
|
||||
@@ -108,5 +131,4 @@ public sealed record TokenRequest(string Token)
|
||||
}
|
||||
|
||||
public static TokenRequest Empty { get; } = new TokenRequest("");
|
||||
|
||||
}
|
||||
@@ -29,7 +29,12 @@ public class RestService
|
||||
[Pure]
|
||||
public async Task<T> GetAsync<T>(Uri uri, CancellationToken cancellationToken) where T : notnull
|
||||
{
|
||||
var response = await _client.GetAsync(uri, cancellationToken);
|
||||
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri)
|
||||
{
|
||||
Version = HttpVersion.Version10,
|
||||
};
|
||||
|
||||
var response = await _client.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false);
|
||||
return await ReadResult<T>(response, cancellationToken, uri);
|
||||
}
|
||||
|
||||
@@ -85,10 +90,15 @@ public class RestService
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
return await response.Content.AsJson<T>();
|
||||
var data = await response.Content.AsJson<T>();
|
||||
response.Dispose();
|
||||
return data;
|
||||
}
|
||||
|
||||
var ex = new RestRequestException(response.Content, response.StatusCode,
|
||||
$"Error while processing {uri.ToString()}: {response.ReasonPhrase}");
|
||||
|
||||
throw new RestRequestException(response.Content, response.StatusCode, $"Error while processing {uri.ToString()}: {response.ReasonPhrase}");
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,8 +106,13 @@ public sealed class NullResponse
|
||||
{
|
||||
}
|
||||
|
||||
public sealed class RestRequestException(HttpContent content, HttpStatusCode statusCode, string message) : Exception(message)
|
||||
public sealed class RestRequestException(HttpContent content, HttpStatusCode statusCode, string message) : Exception(message), IDisposable
|
||||
{
|
||||
public HttpStatusCode StatusCode { get; } = statusCode;
|
||||
public HttpContent Content { get; } = content;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Content.Dispose();
|
||||
}
|
||||
}
|
||||
82
Nebula.Shared/Utils/CryptographicStore.cs
Normal file
82
Nebula.Shared/Utils/CryptographicStore.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Unicode;
|
||||
|
||||
namespace Nebula.Shared.Utils;
|
||||
|
||||
public static class CryptographicStore
|
||||
{
|
||||
public static string Encrypt(object value, byte[] key)
|
||||
{
|
||||
using var memoryStream = new MemoryStream();
|
||||
using var aes = Aes.Create();
|
||||
aes.Key = key;
|
||||
|
||||
var iv = aes.IV;
|
||||
memoryStream.Write(iv, 0, iv.Length);
|
||||
|
||||
var serializedData = JsonSerializer.Serialize(value);
|
||||
|
||||
using CryptoStream cryptoStream = new(
|
||||
memoryStream,
|
||||
aes.CreateEncryptor(),
|
||||
CryptoStreamMode.Write);
|
||||
|
||||
using(StreamWriter encryptWriter = new(cryptoStream))
|
||||
{
|
||||
encryptWriter.WriteLine(serializedData);
|
||||
}
|
||||
|
||||
return Convert.ToBase64String(memoryStream.ToArray());
|
||||
}
|
||||
|
||||
public static async Task<T> Decrypt<T>(string base64EncryptedValue, byte[] key)
|
||||
{
|
||||
using var memoryStream = new MemoryStream(Convert.FromBase64String(base64EncryptedValue));
|
||||
using var aes = Aes.Create();
|
||||
|
||||
var iv = new byte[aes.IV.Length];
|
||||
var numBytesToRead = aes.IV.Length;
|
||||
var numBytesRead = 0;
|
||||
while (numBytesToRead > 0)
|
||||
{
|
||||
var n = memoryStream.Read(iv, numBytesRead, numBytesToRead);
|
||||
if (n == 0) break;
|
||||
|
||||
numBytesRead += n;
|
||||
numBytesToRead -= n;
|
||||
}
|
||||
|
||||
|
||||
await using CryptoStream cryptoStream = new(
|
||||
memoryStream,
|
||||
aes.CreateDecryptor(key, iv),
|
||||
CryptoStreamMode.Read);
|
||||
|
||||
using StreamReader decryptReader = new(cryptoStream);
|
||||
var decryptedMessage = await decryptReader.ReadToEndAsync();
|
||||
return JsonSerializer.Deserialize<T>(decryptedMessage) ?? throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
public static byte[] GetKey(string input, int keySize = 256)
|
||||
{
|
||||
if (string.IsNullOrEmpty(input))
|
||||
throw new ArgumentException("Input string cannot be null or empty.", nameof(input));
|
||||
|
||||
var salt = Encoding.UTF8.GetBytes(input);
|
||||
|
||||
using (var deriveBytes = new Rfc2898DeriveBytes(input, salt, 100_000, HashAlgorithmName.SHA256))
|
||||
{
|
||||
return deriveBytes.GetBytes(keySize / 8);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] GetComputerKey(int keySize = 256)
|
||||
{
|
||||
var name = Environment.UserName;
|
||||
if (string.IsNullOrEmpty(name))
|
||||
name = "LinuxUser";
|
||||
return GetKey(name, keySize);
|
||||
}
|
||||
}
|
||||
24
Nebula.UnitTest/NebulaSharedTests/CryptographicTest.cs
Normal file
24
Nebula.UnitTest/NebulaSharedTests/CryptographicTest.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Nebula.Shared.Utils;
|
||||
|
||||
namespace Nebula.UnitTest.NebulaSharedTests;
|
||||
|
||||
[TestFixture]
|
||||
[TestOf(typeof(CryptographicStore))]
|
||||
public class CryptographicTest
|
||||
{
|
||||
[Test]
|
||||
public async Task EncryptDecrypt()
|
||||
{
|
||||
var key = CryptographicStore.GetComputerKey();
|
||||
Console.WriteLine($"Key: {key}");
|
||||
var entry = new TestEncryptEntry("Hello", "World");
|
||||
Console.WriteLine($"Raw data: {entry}");
|
||||
var encrypt = CryptographicStore.Encrypt(entry, key);
|
||||
Console.WriteLine($"Encrypted data: {encrypt}");
|
||||
var decrypt = await CryptographicStore.Decrypt<TestEncryptEntry>(encrypt, key);
|
||||
Console.WriteLine($"Decrypted data: {decrypt}");
|
||||
Assert.That(decrypt, Is.EqualTo(entry));
|
||||
}
|
||||
}
|
||||
|
||||
public record struct TestEncryptEntry(string Key, string Value);
|
||||
@@ -17,6 +17,8 @@
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ADispatcher_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003Fe6d04341b5ca8c55e2be617e1b6fc5a12cc8647f7272d94f614ae7fb1c0e8d_003FDispatcher_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ADrawingContext_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003F7f67edd2b798d6c80b015913cde68b729bfe416b62cf075ea3953ffeff639c_003FDrawingContext_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AEnumerable_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fcae7ff14a5884c649c9045d4ef4f987ea0928_003Fa6_003F6011c781_003FEnumerable_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AException_002ECoreCLR_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003F4abeb5fc1a5cb44174bd960c913c975ff24e7df9ad448896bc0a113e5b5cd_003FException_002ECoreCLR_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AException_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003Fb4f8b29071cfcf73e927671b936ba53110f1b613a1cc9bef4fc4f07dd0fbe9_003FException_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AFileShare_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fa6b7f037ba7b44df80b8d3aa7e58eeb2e8e938_003F54_003Fc3f4f140_003FFileShare_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AFile_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003F3f31e7e8aa33de883c2ccfa62a9c81bfc246c36e825b489476f9472032e512_003FFile_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AFrozenDictionary_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003F89dff9063ddb01ff8125b579122b88bf4de94526490d77bcbbef7d0ee662a_003FFrozenDictionary_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
@@ -24,6 +26,7 @@
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AFunc_00601_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fa6b7f037ba7b44df80b8d3aa7e58eeb2e8e938_003Fab_003F4dac48f4_003FFunc_00601_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AFuture_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003Fb3575a2f41d7c2dbfaa36e866b8a361e11dd7223ff82bc574c1d5d4b7522f735_003FFuture_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AHttpClient_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003Fc439425da351c75ac7d966a1cc8324b51a9c471865af79d2f2f3fcb65e392_003FHttpClient_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AHttpCompletionOption_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Ffcc079c54e9940c5ac59f0141dda9ad01b4928_003F28_003Fe60e6194_003FHttpCompletionOption_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AHttpContent_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003F9657cc383c70851dc2bdcf91eff27f21196844abfe552fc9c3243ff36974cd_003FHttpContent_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AHttpListener_002EWindows_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003Ffb21cfde6c1ffa9b6be622d15d56f666ad94ada7dd7d81451418d807b98f2_003FHttpListener_002EWindows_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AHttpMessageHandler_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FUsers_003FCinka_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Ffcc079c54e9940c5ac59f0141dda9ad01b4928_003Fa7_003F885f5fd9_003FHttpMessageHandler_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
@@ -97,5 +100,7 @@
|
||||
<TestId>NUnit3x::735691F8-949C-4476-B9E4-5DF6FF8D3D0B::net9.0::Nebula.UnitTest.NebulaSharedTests.ConfigurationServiceTests.WriteConVarTest</TestId>
|
||||
<TestId>NUnit3x::735691F8-949C-4476-B9E4-5DF6FF8D3D0B::net9.0::Nebula.UnitTest.NebulaSharedTests.ConfigurationServiceTests.WriteArrayConvarTest</TestId>
|
||||
<TestId>NUnit3x::735691F8-949C-4476-B9E4-5DF6FF8D3D0B::net9.0::Nebula.UnitTest.NebulaSharedTests.ConfigurationServiceTests</TestId>
|
||||
<TestId>NUnit3x::735691F8-949C-4476-B9E4-5DF6FF8D3D0B::net9.0::Nebula.UnitTest.NebulaSharedTests.CryptographicTest.EncryptDecrypt</TestId>
|
||||
<TestId>NUnit3x::735691F8-949C-4476-B9E4-5DF6FF8D3D0B::net9.0::Nebula.UnitTest.NebulaSharedTests.CryptographicTest</TestId>
|
||||
</TestAncestor>
|
||||
</SessionState></s:String></wpf:ResourceDictionary>
|
||||
Reference in New Issue
Block a user