From 1e359e3812f7cc6f32355fd2430b3d6aa12b6e67 Mon Sep 17 00:00:00 2001 From: Yassin Lokhat Date: Sun, 14 Dec 2025 19:59:23 +0300 Subject: [PATCH 1/9] Code Cleanup --- Core/Models/Account.cs | 2 +- Core/Models/AutoSave.cs | 2 +- Core/Models/Database.cs | 14 +++++++------- Core/Utils/FileLocker.cs | 2 +- Core/Utils/LogCenter.cs | 4 ++-- UnitTests/UnitTestsHelper.cs | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Core/Models/Account.cs b/Core/Models/Account.cs index aec8c87..f98259b 100644 --- a/Core/Models/Account.cs +++ b/Core/Models/Account.cs @@ -50,7 +50,7 @@ string IAccount.Password Dictionary oldPasswords = Passwords.CloneWith(Database.SerializationCenter); Passwords[DateTime.Now] = Password = value; - if (_service != null) + if (_service is not null) { if (Service.User.NumberOfOldPasswordToKeep != 0) { diff --git a/Core/Models/AutoSave.cs b/Core/Models/AutoSave.cs index 16c9d5d..2578354 100644 --- a/Core/Models/AutoSave.cs +++ b/Core/Models/AutoSave.cs @@ -106,7 +106,7 @@ private void _addChange(string itemId, _mergeChanges(changeKey, currentChange); - if (Database.AutoSaveFileLocker == null) + if (Database.AutoSaveFileLocker is null) { Database.AutoSaveFileLocker = new(Database.CryptographyCenter, Database.SerializationCenter, Database.AutoSaveFile, FileMode.OpenOrCreate); } diff --git a/Core/Models/Database.cs b/Core/Models/Database.cs index f211829..001ff25 100644 --- a/Core/Models/Database.cs +++ b/Core/Models/Database.cs @@ -19,7 +19,7 @@ public sealed class Database : IDatabase ILog[]? IDatabase.Logs => Get(Logs.Logs); - IWarning[]? IDatabase.Warnings => Get(User != null ? Warnings : null); + IWarning[]? IDatabase.Warnings => Get(User is not null ? Warnings : null); public ICryptographyCenter CryptographyCenter { get; private set; } public ISerializationCenter SerializationCenter { get; private set; } @@ -48,7 +48,7 @@ public void Delete() public IUser? Login(string passkey) { - if (DatabaseFileLocker == null) throw new NullReferenceException(nameof(DatabaseFileLocker)); + if (DatabaseFileLocker is null) throw new NullReferenceException(nameof(DatabaseFileLocker)); Passkeys = [.. Passkeys, CryptographyCenter.GetSlowHash(passkey)]; @@ -64,7 +64,7 @@ public void Delete() } } - if (User != null) + if (User is not null) { User.Database = this; @@ -214,7 +214,7 @@ private Database(ICryptographyCenter cryptographicCenter, Username = username; Passkeys = [CryptographyCenter.GetHash(username)]; - if (passkeys != null) + if (passkeys is not null) { Passkeys = [.. Passkeys, .. passkeys.Select(x => CryptographyCenter.GetSlowHash(x))]; } @@ -331,7 +331,7 @@ private void _save(bool logSaveEvent) private void _saveDatabase(bool logSaveEvent) { if (User is null) throw new NullReferenceException(nameof(User)); - if (DatabaseFileLocker == null) throw new NullReferenceException(nameof(DatabaseFileLocker)); + if (DatabaseFileLocker is null) throw new NullReferenceException(nameof(DatabaseFileLocker)); Username = User.Username; Passkeys = [CryptographyCenter.GetHash(User.Username), .. User.Passkeys.Select(CryptographyCenter.GetSlowHash)]; @@ -361,7 +361,7 @@ internal void Close(bool logCloseEvent, bool loginTimeoutReached) { if (logCloseEvent) { - if (User != null) + if (User is not null) { string logoutLog = $"User {Username} logged out"; bool needsReview = AutoSave.Any(); @@ -461,7 +461,7 @@ private void _lookAtWarnings() private Warning[] _lookAtLogWarnings() { if (User is null) throw new NullReferenceException(nameof(User)); - if (Logs.Logs == null) throw new NullReferenceException(nameof(Logs.Logs)); + if (Logs.Logs is null) throw new NullReferenceException(nameof(Logs.Logs)); List logs = [.. Logs.Logs.Cast()]; diff --git a/Core/Utils/FileLocker.cs b/Core/Utils/FileLocker.cs index a6ad8e7..d4eaf78 100644 --- a/Core/Utils/FileLocker.cs +++ b/Core/Utils/FileLocker.cs @@ -31,7 +31,7 @@ internal void Lock() internal void Unlock() { - if (_stream == null) return; + if (_stream is null) return; _stream.Close(); _stream.Dispose(); diff --git a/Core/Utils/LogCenter.cs b/Core/Utils/LogCenter.cs index 22c931a..7ab56d1 100644 --- a/Core/Utils/LogCenter.cs +++ b/Core/Utils/LogCenter.cs @@ -13,7 +13,7 @@ internal Database Database } [JsonIgnore] - public ILog[]? Logs => Database.User == null + public ILog[]? Logs => Database.User is null ? null : LogList.Select(x => Database.CryptographyCenter .DecryptAsymmetrically(x, Database.User.PrivateKey) @@ -42,7 +42,7 @@ public void AddLog(string message, bool needsReview) private void _save() { - if (Database.LogFileLocker == null) throw new NullReferenceException(nameof(Database.LogFileLocker)); + if (Database.LogFileLocker is null) throw new NullReferenceException(nameof(Database.LogFileLocker)); Database.LogFileLocker.Save(this, [Database.CryptographyCenter.GetHash(Username)]); } diff --git a/UnitTests/UnitTestsHelper.cs b/UnitTests/UnitTestsHelper.cs index b9334ee..d38bf59 100644 --- a/UnitTests/UnitTestsHelper.cs +++ b/UnitTests/UnitTestsHelper.cs @@ -163,7 +163,7 @@ public static void LastLogsShouldMatch(IDatabase database, string[] expectedLogs public static void LastLogWarningsShouldMatch(IDatabase database, string[] expectedLogs) { - while (database.Warnings == null) + while (database.Warnings is null) { Thread.Sleep(200); } From 4da74763801e5d42c13d6212421207d6321b5000 Mon Sep 17 00:00:00 2001 From: Yassin Lokhat Date: Mon, 15 Dec 2025 12:39:35 +0300 Subject: [PATCH 2/9] Merging all user files --- Core/Models/AutoSave.cs | 14 +--- Core/Models/Database.cs | 60 ++++---------- Core/Utils/FileLocker.cs | 97 +++++++++++++++-------- Core/Utils/LogCenter.cs | 4 +- Interfaces/IDatabase.cs | 10 --- README.md | 26 +++--- UnitTests/Models/DatabaseUnitTests.cs | 24 ------ UnitTests/Models/ImportExportUnitTests.cs | 36 --------- UnitTests/Models/UserUnitTests.cs | 44 +--------- UnitTests/UnitTestsHelper.cs | 26 +++--- 10 files changed, 111 insertions(+), 230 deletions(-) diff --git a/Core/Models/AutoSave.cs b/Core/Models/AutoSave.cs index 2578354..aafbf94 100644 --- a/Core/Models/AutoSave.cs +++ b/Core/Models/AutoSave.cs @@ -106,12 +106,7 @@ private void _addChange(string itemId, _mergeChanges(changeKey, currentChange); - if (Database.AutoSaveFileLocker is null) - { - Database.AutoSaveFileLocker = new(Database.CryptographyCenter, Database.SerializationCenter, Database.AutoSaveFile, FileMode.OpenOrCreate); - } - - Database.AutoSaveFileLocker.Save(this, Database.Passkeys); + Database.FileLocker.Save(this, Database.AutoSaveFileEntry, Database.Passkeys); string logMessage = action switch { Change.Type.Add => $"{itemName} has been added to {containerName}", @@ -170,13 +165,10 @@ internal void Clear(bool deleteFile) { Changes.Clear(); - Database.AutoSaveFileLocker?.Dispose(); - Database.AutoSaveFileLocker = null; - if (deleteFile - && File.Exists(Database.AutoSaveFile)) + && Database.FileLocker.Exists(Database.AutoSaveFileEntry)) { - File.Delete(Database.AutoSaveFile); + Database.FileLocker.Delete(Database.AutoSaveFileEntry); } } } diff --git a/Core/Models/Database.cs b/Core/Models/Database.cs index 001ff25..c7f8e6b 100644 --- a/Core/Models/Database.cs +++ b/Core/Models/Database.cs @@ -11,8 +11,6 @@ public sealed class Database : IDatabase #region IUser interface explicit Internal public string DatabaseFile { get; set; } - public string AutoSaveFile { get; set; } - public string LogFile { get; set; } IUser? IDatabase.User => Get(User); int? IDatabase.SessionLeftTime => User?.SessionLeftTime; @@ -35,9 +33,7 @@ public void Delete() { if (User is null) throw new NullReferenceException(nameof(User)); - DatabaseFileLocker?.Delete(); - LogFileLocker?.Delete(); - AutoSaveFileLocker?.Delete(); + FileLocker.Delete(); Close(logCloseEvent: false, loginTimeoutReached: false); } @@ -48,13 +44,11 @@ public void Delete() public IUser? Login(string passkey) { - if (DatabaseFileLocker is null) throw new NullReferenceException(nameof(DatabaseFileLocker)); - Passkeys = [.. Passkeys, CryptographyCenter.GetSlowHash(passkey)]; try { - User = DatabaseFileLocker.Open(Passkeys); + User = FileLocker.Open(DatabaseFileEntry, Passkeys); } catch (Exception ex) { @@ -70,11 +64,9 @@ public void Delete() Logs.AddLog($"User {Username} logged in", needsReview: false); - if (File.Exists(AutoSaveFile)) + if (FileLocker.Exists(AutoSaveFileEntry)) { - AutoSaveFileLocker = new(CryptographyCenter, SerializationCenter, AutoSaveFile, FileMode.Open); - - AutoSave = AutoSaveFileLocker.Open(Passkeys); + AutoSave = FileLocker.Open(AutoSaveFileEntry, Passkeys); AutoSave.Database = this; AutoSaveDetectedEventArgs eventArg = new(); @@ -186,25 +178,22 @@ public bool ExportToFile(string filePath) internal string Username { get; private set; } internal string[] Passkeys { get; private set; } - internal FileLocker? DatabaseFileLocker; - internal FileLocker? AutoSaveFileLocker; - internal FileLocker? LogFileLocker; + internal readonly string DatabaseFileEntry = "database"; + internal readonly string AutoSaveFileEntry = "autosave"; + internal readonly string LogFileEntry = "log"; + internal FileLocker FileLocker; private Database(ICryptographyCenter cryptographicCenter, ISerializationCenter serializationCenter, IPasswordFactory passwordFactory, IClipboardManager clipboardManager, string databaseFile, - string autoSaveFile, - string logFile, FileMode fileMode, string username, string publicKey = "", string[]? passkeys = null) { DatabaseFile = databaseFile; - AutoSaveFile = autoSaveFile; - LogFile = logFile; CryptographyCenter = cryptographicCenter; SerializationCenter = serializationCenter; @@ -224,9 +213,7 @@ private Database(ICryptographyCenter cryptographicCenter, Database = this, }; - DatabaseFileLocker = new(cryptographicCenter, serializationCenter, databaseFile, fileMode); - - LogFileLocker = new(cryptographicCenter, serializationCenter, logFile, fileMode); + FileLocker = new(cryptographicCenter, serializationCenter, databaseFile, fileMode); Logs = fileMode == FileMode.Create ? new() @@ -234,7 +221,7 @@ private Database(ICryptographyCenter cryptographicCenter, Username = username, PublicKey = publicKey, } - : LogFileLocker.Open([cryptographicCenter.GetHash(username)]); + : FileLocker.Open(LogFileEntry, [cryptographicCenter.GetHash(username)]); Logs.Database = this; } @@ -244,8 +231,6 @@ public static IDatabase Create(ICryptographyCenter cryptographicCenter, IPasswordFactory passwordFactory, IClipboardManager clipboardManager, string databaseFile, - string autoSaveFile, - string logFile, string username, string[] passkeys) { @@ -268,8 +253,6 @@ public static IDatabase Create(ICryptographyCenter cryptographicCenter, passwordFactory, clipboardManager, databaseFile, - autoSaveFile, - logFile, FileMode.Create, username, publicKey, @@ -296,8 +279,6 @@ public static IDatabase Open(ICryptographyCenter cryptographicCenter, IPasswordFactory passwordFactory, IClipboardManager clipboardManager, string databaseFile, - string autoSaveFile, - string logFile, string username) { Database database = new(cryptographicCenter, @@ -305,8 +286,6 @@ public static IDatabase Open(ICryptographyCenter cryptographicCenter, passwordFactory, clipboardManager, databaseFile, - autoSaveFile, - logFile, FileMode.Open, username); @@ -331,11 +310,10 @@ private void _save(bool logSaveEvent) private void _saveDatabase(bool logSaveEvent) { if (User is null) throw new NullReferenceException(nameof(User)); - if (DatabaseFileLocker is null) throw new NullReferenceException(nameof(DatabaseFileLocker)); Username = User.Username; Passkeys = [CryptographyCenter.GetHash(User.Username), .. User.Passkeys.Select(CryptographyCenter.GetSlowHash)]; - DatabaseFileLocker.Save(User, Passkeys); + FileLocker.Save(User, DatabaseFileEntry, Passkeys); if (logSaveEvent) { @@ -354,7 +332,7 @@ private void _saveLogs() if (User is null) throw new NullReferenceException(nameof(User)); Logs.Username = User.Username; - LogFileLocker?.Save(Logs, [CryptographyCenter.GetHash(User.Username)]); + FileLocker.Save(Logs, LogFileEntry, [CryptographyCenter.GetHash(User.Username)]); } internal void Close(bool logCloseEvent, bool loginTimeoutReached) @@ -386,17 +364,7 @@ internal void Close(bool logCloseEvent, bool loginTimeoutReached) Passkeys = []; Warnings = null; - DatabaseFileLocker?.Dispose(); - DatabaseFileLocker = null; - - LogFileLocker?.Dispose(); - LogFileLocker = null; - - AutoSave.Clear(deleteFile: false); - - DatabaseFile = string.Empty; - AutoSaveFile = string.Empty; - LogFile = string.Empty; + FileLocker.Dispose(); DatabaseClosed?.Invoke(this, new(loginTimeoutReached)); } @@ -405,7 +373,7 @@ private void _handleAutoSave(AutoSaveMergeBehavior mergeAutoSave) { if (User is null) throw new NullReferenceException(nameof(User)); - if (!File.Exists(AutoSaveFile)) + if (!FileLocker.Exists(AutoSaveFileEntry)) { return; } diff --git a/Core/Utils/FileLocker.cs b/Core/Utils/FileLocker.cs index d4eaf78..b5862fa 100644 --- a/Core/Utils/FileLocker.cs +++ b/Core/Utils/FileLocker.cs @@ -38,58 +38,53 @@ internal void Unlock() _stream = null; } - internal string ReadAllText() + internal T Open(string fileEntry, string[] passkeys) where T : notnull { - Unlock(); - - string text = _decompressString(File.ReadAllText(FilePath)); - - Lock(); - - return text; + return _readContent(fileEntry, passkeys).DeserializeTo(_serializationCenter); } - internal string ReadAllText(string[] passkeys) + internal void Save(T obj, string fileEntry, string[] passkeys) where T : notnull { - string text = ReadAllText(); - - return _cryptographicCenter.DecryptSymmetrically(text, passkeys); + _writeContent(obj.SerializeWith(_serializationCenter), fileEntry, passkeys); } - internal T Open(string[] passkeys) where T : notnull - { - return ReadAllText(passkeys).DeserializeTo(_serializationCenter); - } - - internal void WriteAllText(string text) + internal void Delete() { Unlock(); - File.WriteAllText(FilePath, _compressString(text)); - - Lock(); + if (File.Exists(FilePath)) + { + File.Delete(FilePath); + } } - internal void WriteAllText(string text, string[] passkeys) + internal void Delete(string fileEntry) { - text = _cryptographicCenter.EncryptSymmetrically(text, passkeys); + Unlock(); - WriteAllText(text); - } + using (ZipArchive archive = ZipFile.Open(FilePath, ZipArchiveMode.Update, Encoding.UTF8)) + { + ZipArchiveEntry? existingEntry = archive.GetEntry(fileEntry); + existingEntry?.Delete(); + } - internal void Save(T obj, string[] passkeys) where T : notnull - { - WriteAllText(obj.SerializeWith(_serializationCenter), passkeys); + Lock(); } - internal void Delete() + internal bool Exists(string fileEntry) { Unlock(); - if (File.Exists(FilePath)) + bool exists = false; + + using (ZipArchive archive = ZipFile.Open(FilePath, ZipArchiveMode.Update, Encoding.UTF8)) { - File.Delete(FilePath); + exists = archive.GetEntry(fileEntry) is not null; } + + Lock(); + + return exists; } public void Dispose() @@ -129,5 +124,45 @@ private static string _decompressString(string compressedText) } } + private string _readContent(string fileEntry, string[] passkeys) + { + Unlock(); + string content; + + using (ZipArchive archive = ZipFile.OpenRead(FilePath)) + { + ZipArchiveEntry zipEntry = archive.GetEntry(fileEntry) + ?? throw new FileNotFoundException($"The file entry '{fileEntry}' not found in the archive {FilePath}.", $"{FilePath}/{fileEntry}"); + + using Stream stream = zipEntry.Open(); + using StreamReader reader = new(stream, Encoding.UTF8); + + content = _cryptographicCenter.DecryptSymmetrically(_decompressString(reader.ReadToEnd()), passkeys); + } + + Lock(); + + return content; + } + + private void _writeContent(string content, string fileEntry, string[] passkeys) + { + Unlock(); + + using (ZipArchive archive = ZipFile.Open(FilePath, ZipArchiveMode.Update, Encoding.UTF8)) + { + ZipArchiveEntry? existingEntry = archive.GetEntry(fileEntry); + existingEntry?.Delete(); + + ZipArchiveEntry newEntry = archive.CreateEntry(fileEntry); + + using Stream stream = newEntry.Open(); + using StreamWriter writer = new(stream, Encoding.UTF8); + + writer.Write(_compressString(_cryptographicCenter.EncryptSymmetrically(content, passkeys))); + } + + Lock(); + } } } diff --git a/Core/Utils/LogCenter.cs b/Core/Utils/LogCenter.cs index 7ab56d1..abac673 100644 --- a/Core/Utils/LogCenter.cs +++ b/Core/Utils/LogCenter.cs @@ -42,9 +42,7 @@ public void AddLog(string message, bool needsReview) private void _save() { - if (Database.LogFileLocker is null) throw new NullReferenceException(nameof(Database.LogFileLocker)); - - Database.LogFileLocker.Save(this, [Database.CryptographyCenter.GetHash(Username)]); + Database.FileLocker.Save(this, Database.LogFileEntry, [Database.CryptographyCenter.GetHash(Username)]); } } } diff --git a/Interfaces/IDatabase.cs b/Interfaces/IDatabase.cs index e7698d8..ac24aa5 100644 --- a/Interfaces/IDatabase.cs +++ b/Interfaces/IDatabase.cs @@ -12,16 +12,6 @@ public interface IDatabase : IDisposable /// string DatabaseFile { get; set; } - /// - /// The path to the autosave file. - /// - string AutoSaveFile { get; set; } - - /// - /// The path to the log file. - /// - string LogFile { get; set; } - /// /// The user loaded. /// diff --git a/README.md b/README.md index 145c876..0ee519a 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ **Overview** ------------ -This is a C# implementation of a local stored password manager. The application provides a secure way to store and manage passwords locally on the user's device. +This is a C# implementation of a local stored password manager in .Net 10. The application provides a secure way to store and manage passwords locally on the user's device. **Features** ------------ @@ -116,8 +116,6 @@ classDiagram class IDatabase { <> +DatabaseFile : string - +AutoSaveFile : string - +LogFile : string +User : IUser +SessionLeftTime : int +Logs : IEnumerable~ILog~ @@ -231,8 +229,7 @@ To create a new database, use the `Upsilon.Apps.Passkey.Core.Models.Database.Cre This method needs an `ICryptographyCenter` implementation, an `ISerializationCenter` implementation, an `IPasswordFactory` implementation and an `IClipboardManager` implementation. The namespace `Upsilon.Apps.Passkey.Core.Utils` already contains implementations for all of these intefaces except for the `IClipboardManager` which needs an OS specific implementation. -The next parameters are a set of files : the database file itself, the autosave file and the log file. -These files will be created during the process. +The next parameter is the database file itself, which will be created during the process. Finally, the method take the username and the passkeys. Note that the passkeys are used as master passwords to encrypt the database (and the other files). @@ -243,8 +240,6 @@ IDatabase database = Upsilon.Apps.Passkey.Core.Models.Database.Create(new Upsilo new Upsilon.Apps.Passkey.Core.Utils.PasswordFactory(), new OSSpecificClipboardManager(), "./database.pku", - "./autosave.pks", - "./log.pkl", "username", new string[] { "master_password_1", "master_password_2", "master_password_3" }); ``` @@ -258,8 +253,7 @@ To open an existing database, use the `Upsilon.Apps.Passkey.Core.Models.Database This method needs an `ICryptographyCenter` implementation, an `ISerializationCenter` implementation, an `IPasswordFactory` implementation and an `IClipboardManager` implementation as in the creation step. -The next parameters are a set of files : the database file itself, the autosave file and the log file. -The database file must, obviously, exist, the autosave file and log files are optional but must be the same as provided during the creating process. +The next parameter is the database file itself and must, obviously, exist. Finally, the method take the username. @@ -269,8 +263,6 @@ IDatabase database = Upsilon.Apps.Passkey.Core.Models.Database.Open(new Upsilon. new Upsilon.Apps.Passkey.Core.Utils.PasswordFactory(), new OSSpecificClipboardManager(), "./database.pku", - "./autosave.pks", - "./log.pkl", "username"); ``` @@ -292,17 +284,17 @@ Once the IUser retrieved, it allow a full access to all services and accounts, a ### Saving the changes Use the `IDatabase.Save` method to save the user's updates. -Note that any update on the user, its services and/or accounts which is not saved will be keeped in the autosave file. +Note that any update on the user, its services and/or accounts which is not saved will be keeped in a hiden autosave file. ```csharp -user.LogoutTimeout = 5; // Setting the logout timeout to 5 min will create an autosave file -database.Save(); // Will save the new logout timeout in the database file and removed the autosave file +user.LogoutTimeout = 5; // Setting the logout timeout to 5 min will create a hiden autosave file +database.Save(); // Will save the new logout timeout in the database file and remove the autosave file ``` ### Logout/Close a database To logout and close the database, use the `IDatabase.Close` method. -All unsaved updates are stored inside the autosave file. +All unsaved updates are stored inside the hiden autosave file. ```csharp database.Close(); @@ -312,8 +304,8 @@ database.Close(); ------------------- 1. Clone the repository: `git clone https://github.com/YassinLokhat/Upsilon.Apps.Passkey.git` -2. Build the solution: `dotnet build` -3. Run the API: `dotnet run` +2. 1. Build the solution for Windows users: `dotnet build Upsilon.Apps.Passkey.Windows.slnx` +2. 2. Build the solution for Linux users: `dotnet build Upsilon.Apps.Passkey.Linux.slnx` **Contributing** ------------ diff --git a/UnitTests/Models/DatabaseUnitTests.cs b/UnitTests/Models/DatabaseUnitTests.cs index 99098c7..67699fe 100644 --- a/UnitTests/Models/DatabaseUnitTests.cs +++ b/UnitTests/Models/DatabaseUnitTests.cs @@ -75,8 +75,6 @@ public void Case01_DatabaseCreationOpenDelete() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); Stack expectedLogs = new(); UnitTestsHelper.ClearTestEnvironment(); @@ -89,12 +87,6 @@ public void Case01_DatabaseCreationOpenDelete() _ = databaseCreated.DatabaseFile.Should().Be(databaseFile); _ = File.Exists(databaseCreated.DatabaseFile).Should().BeTrue(); - _ = databaseCreated.AutoSaveFile.Should().Be(autoSaveFile); - _ = File.Exists(databaseCreated.AutoSaveFile).Should().BeFalse(); - - _ = databaseCreated.LogFile.Should().Be(logFile); - _ = File.Exists(databaseCreated.LogFile).Should().BeTrue(); - _ = databaseCreated.User.Should().NotBeNull(); _ = databaseCreated.User.Username.Should().Be(username); @@ -109,8 +101,6 @@ public void Case01_DatabaseCreationOpenDelete() // Then _ = databaseCreated.User.Should().BeNull(); _ = File.Exists(databaseFile).Should().BeTrue(); - _ = File.Exists(autoSaveFile).Should().BeFalse(); - _ = File.Exists(logFile).Should().BeTrue(); // When IDatabase databaseLoaded = UnitTestsHelper.OpenTestDatabase(passkeys, out _); @@ -122,12 +112,6 @@ public void Case01_DatabaseCreationOpenDelete() _ = databaseLoaded.DatabaseFile.Should().Be(databaseFile); _ = File.Exists(databaseLoaded.DatabaseFile).Should().BeTrue(); - _ = databaseLoaded.AutoSaveFile.Should().Be(autoSaveFile); - _ = File.Exists(databaseLoaded.AutoSaveFile).Should().BeFalse(); - - _ = databaseLoaded.LogFile.Should().Be(logFile); - _ = File.Exists(databaseLoaded.LogFile).Should().BeTrue(); - _ = databaseLoaded.User.Should().NotBeNull(); _ = databaseLoaded.User.Username.Should().Be(username); @@ -142,8 +126,6 @@ public void Case01_DatabaseCreationOpenDelete() // Then _ = databaseCreated.User.Should().BeNull(); _ = File.Exists(databaseFile).Should().BeFalse(); - _ = File.Exists(autoSaveFile).Should().BeFalse(); - _ = File.Exists(logFile).Should().BeFalse(); // Finaly UnitTestsHelper.ClearTestEnvironment(); @@ -197,8 +179,6 @@ public void Case03_DatabaseOpenButAlreadyOpened() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); UnitTestsHelper.ClearTestEnvironment(); IDatabase databaseCreated = UnitTestsHelper.CreateTestDatabase(passkeys); @@ -305,8 +285,6 @@ public void Case05_DatabaseAutoLogout() { // Given string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); bool closedDueToTimeout = false; @@ -319,8 +297,6 @@ public void Case05_DatabaseAutoLogout() UnitTestsHelper.PasswordFactory, UnitTestsHelper.ClipboardManager, databaseFile, - autoSaveFile, - logFile, username, passkeys); diff --git a/UnitTests/Models/ImportExportUnitTests.cs b/UnitTests/Models/ImportExportUnitTests.cs index b5867a2..e87072f 100644 --- a/UnitTests/Models/ImportExportUnitTests.cs +++ b/UnitTests/Models/ImportExportUnitTests.cs @@ -21,9 +21,6 @@ public void Case01_Import_MissingFile() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath("missing_import.csv"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); Stack expectedLogs = new(); @@ -53,9 +50,6 @@ public void Case02_Import_WrongExtention() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath($"{username}/import.txt", createIfNotExists: true); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); Stack expectedLogs = new(); @@ -85,9 +79,6 @@ public void Case03_Import_NoData() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath($"import_noData.csv"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); Stack expectedLogs = new(); @@ -117,9 +108,6 @@ public void Case04_Import_ServiceAlreadyExists() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath($"import.csv"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); Stack expectedLogs = new(); @@ -151,9 +139,6 @@ public void Case05_ImportBlanckService() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath($"import_blanckService.csv"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); Stack expectedLogs = new(); @@ -183,9 +168,6 @@ public void Case06_ImportCSV_OK() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath("import.csv"); string exportFile = UnitTestsHelper.GetTestFilePath($"{username}/export.csv"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); @@ -299,9 +281,6 @@ public void Case07_ImportCSV_MissingHeader() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath($"import_MissingHearder.csv"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); Stack expectedLogs = new(); @@ -331,9 +310,6 @@ public void Case08_ImportCSV_MissingCollumn() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath($"import_MissingCollumn.csv"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); Stack expectedLogs = new(); @@ -363,9 +339,6 @@ public void Case09_ImportJson_OK() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath("import.json"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); Stack expectedLogs = new(); @@ -469,9 +442,6 @@ public void Case10_ImportJson_WrongFormat() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath($"import_WrongFormat.json"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); Stack expectedLogs = new(); @@ -502,9 +472,6 @@ public void Case11_Export_FileAlreadyExists() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath($"import.json"); string exportFile = UnitTestsHelper.GetTestFilePath($"{username}/export.json", createIfNotExists: true); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); @@ -537,9 +504,6 @@ public void Case12_Export_FileExtensionNotHandled() string username = UnitTestsHelper.GetUsername(); string[] passkeys = UnitTestsHelper.GetRandomStringArray(); - string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string importFile = UnitTestsHelper.GetTestFilePath($"import.json"); string exportFile = UnitTestsHelper.GetTestFilePath($"{username}/export.txt"); IDatabase database = UnitTestsHelper.CreateTestDatabase(passkeys); diff --git a/UnitTests/Models/UserUnitTests.cs b/UnitTests/Models/UserUnitTests.cs index 19bad4e..92e55db 100644 --- a/UnitTests/Models/UserUnitTests.cs +++ b/UnitTests/Models/UserUnitTests.cs @@ -20,7 +20,8 @@ public void Case01_UserUpdateWithoutSaving() string[] passkeys = UnitTestsHelper.GetRandomStringArray(); IDatabase databaseCreated = UnitTestsHelper.CreateTestDatabase(passkeys); databaseCreated.Close(); - string oldDatabaseContent = File.ReadAllText(UnitTestsHelper.ComputeDatabaseFilePath()); + string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); + string oldDatabaseContent = UnitTestsHelper.ReadFileZipEntry(databaseFile, "database"); IDatabase databaseLoaded = UnitTestsHelper.OpenTestDatabase(passkeys, out _); string newUsername = UnitTestsHelper.GetRandomString(); @@ -45,8 +46,7 @@ public void Case01_UserUpdateWithoutSaving() databaseLoaded.Close(); // Then - _ = File.Exists(UnitTestsHelper.ComputeAutoSaveFilePath()).Should().BeTrue(); - _ = File.ReadAllText(UnitTestsHelper.ComputeDatabaseFilePath()).Should().Be(oldDatabaseContent); + _ = UnitTestsHelper.ReadFileZipEntry(databaseFile, "database").Should().Be(oldDatabaseContent); // Finaly UnitTestsHelper.ClearTestEnvironment(); @@ -63,8 +63,6 @@ public void Case02_UserUpdateThenSaved() // Given UnitTestsHelper.ClearTestEnvironment(); string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); string oldUsername = UnitTestsHelper.GetUsername(); IDatabase databaseCreated = UnitTestsHelper.CreateTestDatabase(); string newUsername = "new_" + oldUsername; @@ -93,28 +91,16 @@ public void Case02_UserUpdateThenSaved() databaseCreated.User.WarningsToNotify = WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning; expectedLogs.Push($"Warning : User {oldUsername}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); expectedLogWarnings.Push($"Warning : User {oldUsername}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); - - // Then - _ = File.Exists(autoSaveFile).Should().BeTrue(); - - // When databaseCreated.Save(); expectedLogs.Push($"Information : User {newUsername}'s database saved"); databaseCreated.Close(); expectedLogs.Push($"Information : User {newUsername} logged out"); expectedLogs.Push($"Information : User {newUsername}'s database closed"); - - // Then - _ = File.Exists(autoSaveFile).Should().BeFalse(); - - // When IDatabase databaseLoaded = Database.Open(UnitTestsHelper.CryptographicCenter, UnitTestsHelper.SerializationCenter, UnitTestsHelper.PasswordFactory, UnitTestsHelper.ClipboardManager, databaseFile, - autoSaveFile, - logFile, newUsername); expectedLogs.Push($"Information : User {newUsername}'s database opened"); foreach (string passkey in newPasskeys) @@ -129,8 +115,6 @@ public void Case02_UserUpdateThenSaved() _ = databaseLoaded.User.LogoutTimeout.Should().Be(logoutTimeout); _ = databaseLoaded.User.CleaningClipboardTimeout.Should().Be(cleaningClipboardTimeout); - _ = File.Exists(autoSaveFile).Should().BeFalse(); - UnitTestsHelper.LastLogsShouldMatch(databaseLoaded, [.. expectedLogs]); UnitTestsHelper.LastLogWarningsShouldMatch(databaseLoaded, [.. expectedLogWarnings]); @@ -155,8 +139,6 @@ public void Case03_UserUpdateButNotSaved_CaseMergeAndSave() string oldUsername = UnitTestsHelper.GetUsername(); string[] oldPasskeys = UnitTestsHelper.GetRandomStringArray(); string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); IDatabase databaseCreated = UnitTestsHelper.CreateTestDatabase(oldPasskeys); string newUsername = "new_" + oldUsername; string[] newPasskeys = UnitTestsHelper.GetRandomStringArray(); @@ -189,11 +171,6 @@ public void Case03_UserUpdateButNotSaved_CaseMergeAndSave() expectedLogs.Push($"Warning : User {oldUsername} logged out without saving"); expectedLogWarnings.Push($"Warning : User {oldUsername} logged out without saving"); expectedLogs.Push($"Information : User {oldUsername}'s database closed"); - - // Then - _ = File.Exists(autoSaveFile).Should().BeTrue(); - - // When IDatabase databaseLoaded = UnitTestsHelper.OpenTestDatabase(oldPasskeys, out IWarning[] warnings, AutoSaveMergeBehavior.MergeAndSaveThenRemoveAutoSaveFile); expectedLogs.Push($"Information : User {oldUsername}'s database opened"); expectedLogs.Push($"Information : User {oldUsername} logged in"); @@ -201,7 +178,6 @@ public void Case03_UserUpdateButNotSaved_CaseMergeAndSave() expectedLogWarnings.Push($"Warning : User {oldUsername}'s autosave merged and saved"); // Then - _ = File.Exists(autoSaveFile).Should().BeFalse(); _ = databaseLoaded.User.HasChanged().Should().BeFalse(); _ = databaseLoaded.User.Username.Should().Be(newUsername); _ = databaseLoaded.User.Passkeys.Should().BeEquivalentTo(newPasskeys); @@ -220,8 +196,6 @@ public void Case03_UserUpdateButNotSaved_CaseMergeAndSave() UnitTestsHelper.PasswordFactory, UnitTestsHelper.ClipboardManager, databaseFile, - autoSaveFile, - logFile, newUsername); expectedLogs.Push($"Information : User {newUsername}'s database opened"); foreach (string passkey in newPasskeys) @@ -231,7 +205,6 @@ public void Case03_UserUpdateButNotSaved_CaseMergeAndSave() expectedLogs.Push($"Information : User {newUsername} logged in"); // Then - _ = File.Exists(autoSaveFile).Should().BeFalse(); _ = databaseLoaded.User.Username.Should().Be(newUsername); _ = databaseLoaded.User.Passkeys.Should().BeEquivalentTo(newPasskeys); _ = databaseLoaded.User.LogoutTimeout.Should().Be(logoutTimeout); @@ -261,8 +234,6 @@ public void Case04_UserUpdateButNotSaved_CaseMergeWithoutSaving() string oldUsername = UnitTestsHelper.GetUsername(); string[] oldPasskeys = UnitTestsHelper.GetRandomStringArray(); string databaseFile = UnitTestsHelper.ComputeDatabaseFilePath(); - string autoSaveFile = UnitTestsHelper.ComputeAutoSaveFilePath(); - string logFile = UnitTestsHelper.ComputeLogFilePath(); IDatabase databaseCreated = UnitTestsHelper.CreateTestDatabase(oldPasskeys); string newUsername = "new_" + oldUsername; string[] newPasskeys = UnitTestsHelper.GetRandomStringArray(); @@ -295,11 +266,6 @@ public void Case04_UserUpdateButNotSaved_CaseMergeWithoutSaving() expectedLogs.Push($"Warning : User {oldUsername} logged out without saving"); expectedLogWarnings.Push($"Warning : User {oldUsername} logged out without saving"); expectedLogs.Push($"Information : User {oldUsername}'s database closed"); - - // Then - _ = File.Exists(autoSaveFile).Should().BeTrue(); - - // When IDatabase databaseLoaded = UnitTestsHelper.OpenTestDatabase(oldPasskeys, out IWarning[] warnings, AutoSaveMergeBehavior.MergeWithoutSavingAndKeepAutoSaveFile); expectedLogs.Push($"Information : User {oldUsername}'s database opened"); expectedLogs.Push($"Information : User {oldUsername} logged in"); @@ -307,7 +273,6 @@ public void Case04_UserUpdateButNotSaved_CaseMergeWithoutSaving() expectedLogWarnings.Push($"Warning : User {oldUsername}'s autosave merged without saving"); // Then - _ = File.Exists(autoSaveFile).Should().BeTrue(); _ = databaseLoaded.User.HasChanged().Should().BeTrue(); _ = databaseLoaded.User.HasChanged(nameof(databaseLoaded.User.Username)).Should().BeTrue(); _ = databaseLoaded.User.Username.Should().Be(newUsername); @@ -332,8 +297,6 @@ public void Case04_UserUpdateButNotSaved_CaseMergeWithoutSaving() UnitTestsHelper.PasswordFactory, UnitTestsHelper.ClipboardManager, databaseFile, - autoSaveFile, - logFile, newUsername); expectedLogs.Push($"Information : User {newUsername}'s database opened"); foreach (string passkey in newPasskeys) @@ -343,7 +306,6 @@ public void Case04_UserUpdateButNotSaved_CaseMergeWithoutSaving() expectedLogs.Push($"Information : User {newUsername} logged in"); // Then - _ = File.Exists(autoSaveFile).Should().BeFalse(); _ = databaseLoaded.User.Username.Should().Be(newUsername); _ = databaseLoaded.User.Passkeys.Should().BeEquivalentTo(newPasskeys); _ = databaseLoaded.User.LogoutTimeout.Should().Be(logoutTimeout); diff --git a/UnitTests/UnitTestsHelper.cs b/UnitTests/UnitTestsHelper.cs index d38bf59..94866a2 100644 --- a/UnitTests/UnitTestsHelper.cs +++ b/UnitTests/UnitTestsHelper.cs @@ -1,6 +1,8 @@ using FluentAssertions; +using System.IO.Compression; using System.Runtime.CompilerServices; using System.Security.Cryptography; +using System.Text; using Upsilon.Apps.Passkey.Core.Models; using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces; @@ -10,7 +12,7 @@ namespace Upsilon.Apps.Passkey.UnitTests { internal static class UnitTestsHelper { - public static readonly int RANDOMIZED_TESTS_LOOP = 100; + public static readonly int RANDOMIZED_TESTS_LOOP = 10; public static readonly ICryptographyCenter CryptographicCenter = new CryptographyCenter(); public static readonly ISerializationCenter SerializationCenter = new JsonSerializationCenter(); @@ -20,8 +22,18 @@ internal static class UnitTestsHelper public static string ComputeTestDirectory([CallerMemberName] string username = "") => $"./TestFiles/{username}"; public static string ComputeDatabaseFileDirectory([CallerMemberName] string username = "") => $"{ComputeTestDirectory(username)}/{CryptographicCenter.GetHash(username)}"; public static string ComputeDatabaseFilePath([CallerMemberName] string username = "") => $"{ComputeDatabaseFileDirectory(username)}/{CryptographicCenter.GetHash(username)}.pku"; - public static string ComputeAutoSaveFilePath([CallerMemberName] string username = "") => $"{ComputeDatabaseFileDirectory(username)}/{CryptographicCenter.GetHash(username)}.pka"; - public static string ComputeLogFilePath([CallerMemberName] string username = "") => $"{ComputeDatabaseFileDirectory(username)}/{CryptographicCenter.GetHash(username)}.pkl"; + + public static string ReadFileZipEntry(string zipFile, string fileEntry) + { + using ZipArchive archive = ZipFile.OpenRead(zipFile); + ZipArchiveEntry zipEntry = archive.GetEntry(fileEntry) + ?? throw new FileNotFoundException($"The file entry '{fileEntry}' not found in the archive {zipFile}.", $"{zipFile}/{fileEntry}"); + + using Stream stream = zipEntry.Open(); + using StreamReader reader = new(stream, Encoding.UTF8); + + return reader.ReadToEnd(); + } public static string GetTestFilePath(string fileName, bool createIfNotExists = false) { @@ -45,8 +57,6 @@ public static string GetTestFilePath(string fileName, bool createIfNotExists = f public static IDatabase CreateTestDatabase(string[] passkeys = null, [CallerMemberName] string username = "") { string databaseFile = ComputeDatabaseFilePath(username); - string autoSaveFile = ComputeAutoSaveFilePath(username); - string logFile = ComputeLogFilePath(username); passkeys ??= GetRandomStringArray(); @@ -55,8 +65,6 @@ public static IDatabase CreateTestDatabase(string[] passkeys = null, [CallerMemb PasswordFactory, ClipboardManager, databaseFile, - autoSaveFile, - logFile, username, passkeys); @@ -66,8 +74,6 @@ public static IDatabase CreateTestDatabase(string[] passkeys = null, [CallerMemb public static IDatabase OpenTestDatabase(string[] passkeys, out IWarning[] detectedWarnings, AutoSaveMergeBehavior mergeAutoSave = AutoSaveMergeBehavior.DontMergeAndRemoveAutoSaveFile, [CallerMemberName] string username = "") { string databaseFile = ComputeDatabaseFilePath(username); - string autoSaveFile = ComputeAutoSaveFilePath(username); - string logFile = ComputeLogFilePath(username); IWarning[] warnings = []; @@ -76,8 +82,6 @@ public static IDatabase OpenTestDatabase(string[] passkeys, out IWarning[] detec PasswordFactory, ClipboardManager, databaseFile, - autoSaveFile, - logFile, username); database.AutoSaveDetected += (s, e) => { e.MergeBehavior = mergeAutoSave; }; From 19451143e71914b2a9da5475d80b26f24275456d Mon Sep 17 00:00:00 2001 From: Yassin Lokhat Date: Mon, 15 Dec 2025 13:31:24 +0300 Subject: [PATCH 3/9] Organizing Interfaces --- Core/Models/Account.cs | 2 +- Core/Models/Database.cs | 2 +- Core/Models/Log.cs | 2 +- Core/Models/Service.cs | 2 +- Core/Models/User.cs | 2 +- Core/Models/Warning.cs | 4 +- Core/Utils/CryptographyCenter.cs | 1 - Core/Utils/FileLocker.cs | 1 - Core/Utils/ImportExportHelper.cs | 2 +- Core/Utils/JsonSerializationCenter.cs | 2 +- Core/Utils/LogCenter.cs | 2 +- Core/Utils/PasswordFactory.cs | 2 +- Core/Utils/StaticMethods.cs | 2 +- Interfaces/Events/WarningDetectedEventArgs.cs | 4 +- Interfaces/{ => Models}/IAccount.cs | 2 +- Interfaces/{ => Models}/IDatabase.cs | 3 +- Interfaces/{ => Models}/IItem.cs | 2 +- Interfaces/{ => Models}/ILog.cs | 2 +- Interfaces/{ => Models}/IService.cs | 2 +- Interfaces/{ => Models}/IUser.cs | 2 +- Interfaces/{ => Models}/IWarning.cs | 2 +- Interfaces/{ => Utils}/IClipboardManager.cs | 4 +- Interfaces/{ => Utils}/ICryptographyCenter.cs | 2 +- Interfaces/{ => Utils}/IPasswordFactory.cs | 2 +- .../{ => Utils}/ISerializationCenter.cs | 2 +- Interfaces/Utils/StaticMethods.cs | 4 +- README.md | 307 +++++++++--------- UnitTests/ClipboardManager.cs | 1 + UnitTests/Models/AccountUnitTests.cs | 1 + UnitTests/Models/DatabaseUnitTests.cs | 1 + UnitTests/Models/ImportExportUnitTests.cs | 1 + UnitTests/Models/ServiceUnitTests.cs | 1 + UnitTests/Models/UserUnitTests.cs | 1 + UnitTests/UnitTestsHelper.cs | 2 + 34 files changed, 197 insertions(+), 177 deletions(-) rename Interfaces/{ => Models}/IAccount.cs (95%) rename Interfaces/{ => Models}/IDatabase.cs (97%) rename Interfaces/{ => Models}/IItem.cs (86%) rename Interfaces/{ => Models}/ILog.cs (89%) rename Interfaces/{ => Models}/IService.cs (97%) rename Interfaces/{ => Models}/IUser.cs (97%) rename Interfaces/{ => Models}/IWarning.cs (91%) rename Interfaces/{ => Utils}/IClipboardManager.cs (77%) rename Interfaces/{ => Utils}/ICryptographyCenter.cs (98%) rename Interfaces/{ => Utils}/IPasswordFactory.cs (96%) rename Interfaces/{ => Utils}/ISerializationCenter.cs (94%) diff --git a/Core/Models/Account.cs b/Core/Models/Account.cs index f98259b..cfd22ed 100644 --- a/Core/Models/Account.cs +++ b/Core/Models/Account.cs @@ -1,7 +1,7 @@ using System.ComponentModel; using Upsilon.Apps.Passkey.Core.Utils; -using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Models { diff --git a/Core/Models/Database.cs b/Core/Models/Database.cs index c7f8e6b..b9008ed 100644 --- a/Core/Models/Database.cs +++ b/Core/Models/Database.cs @@ -1,7 +1,7 @@ using Upsilon.Apps.Passkey.Core.Utils; -using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Events; +using Upsilon.Apps.Passkey.Interfaces.Models; using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.Core.Models diff --git a/Core/Models/Log.cs b/Core/Models/Log.cs index 15837fd..43dc12e 100644 --- a/Core/Models/Log.cs +++ b/Core/Models/Log.cs @@ -1,4 +1,4 @@ -using Upsilon.Apps.Passkey.Interfaces; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Models { diff --git a/Core/Models/Service.cs b/Core/Models/Service.cs index 13f1dab..92e8017 100644 --- a/Core/Models/Service.cs +++ b/Core/Models/Service.cs @@ -1,6 +1,6 @@ using System.ComponentModel; using Upsilon.Apps.Passkey.Core.Utils; -using Upsilon.Apps.Passkey.Interfaces; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Models { diff --git a/Core/Models/User.cs b/Core/Models/User.cs index 023aa6d..3719a76 100644 --- a/Core/Models/User.cs +++ b/Core/Models/User.cs @@ -1,7 +1,7 @@ using System.ComponentModel; using Upsilon.Apps.Passkey.Core.Utils; -using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Models { diff --git a/Core/Models/Warning.cs b/Core/Models/Warning.cs index 06ac3d2..3acbe2d 100644 --- a/Core/Models/Warning.cs +++ b/Core/Models/Warning.cs @@ -1,5 +1,5 @@ -using Upsilon.Apps.Passkey.Interfaces; -using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Models { diff --git a/Core/Utils/CryptographyCenter.cs b/Core/Utils/CryptographyCenter.cs index ee83b9d..5047b29 100644 --- a/Core/Utils/CryptographyCenter.cs +++ b/Core/Utils/CryptographyCenter.cs @@ -1,7 +1,6 @@ using System.Security.Cryptography; using System.Text; using System.Text.Json; -using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.Core.Utils diff --git a/Core/Utils/FileLocker.cs b/Core/Utils/FileLocker.cs index b5862fa..a4b5e52 100644 --- a/Core/Utils/FileLocker.cs +++ b/Core/Utils/FileLocker.cs @@ -1,6 +1,5 @@ using System.IO.Compression; using System.Text; -using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.Core.Utils diff --git a/Core/Utils/ImportExportHelper.cs b/Core/Utils/ImportExportHelper.cs index e63bf98..bd28531 100644 --- a/Core/Utils/ImportExportHelper.cs +++ b/Core/Utils/ImportExportHelper.cs @@ -2,8 +2,8 @@ using System.Text.Json; using System.Text.Json.Serialization; using Upsilon.Apps.Passkey.Core.Models; -using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Utils { diff --git a/Core/Utils/JsonSerializationCenter.cs b/Core/Utils/JsonSerializationCenter.cs index 50d2619..b655562 100644 --- a/Core/Utils/JsonSerializationCenter.cs +++ b/Core/Utils/JsonSerializationCenter.cs @@ -1,6 +1,6 @@ using System.Text.Json; using System.Text.Json.Serialization; -using Upsilon.Apps.Passkey.Interfaces; +using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.Core.Utils { diff --git a/Core/Utils/LogCenter.cs b/Core/Utils/LogCenter.cs index abac673..00d9055 100644 --- a/Core/Utils/LogCenter.cs +++ b/Core/Utils/LogCenter.cs @@ -1,6 +1,6 @@ using System.Text.Json.Serialization; using Upsilon.Apps.Passkey.Core.Models; -using Upsilon.Apps.Passkey.Interfaces; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Utils { diff --git a/Core/Utils/PasswordFactory.cs b/Core/Utils/PasswordFactory.cs index f591cc6..91d6b1b 100644 --- a/Core/Utils/PasswordFactory.cs +++ b/Core/Utils/PasswordFactory.cs @@ -1,6 +1,6 @@ using System.Security.Cryptography; using System.Text; -using Upsilon.Apps.Passkey.Interfaces; +using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.Core.Utils { diff --git a/Core/Utils/StaticMethods.cs b/Core/Utils/StaticMethods.cs index f868257..57c814f 100644 --- a/Core/Utils/StaticMethods.cs +++ b/Core/Utils/StaticMethods.cs @@ -1,5 +1,5 @@ using System.Text.RegularExpressions; -using Upsilon.Apps.Passkey.Interfaces; +using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.Core.Utils { diff --git a/Interfaces/Events/WarningDetectedEventArgs.cs b/Interfaces/Events/WarningDetectedEventArgs.cs index 48d06a2..83d9755 100644 --- a/Interfaces/Events/WarningDetectedEventArgs.cs +++ b/Interfaces/Events/WarningDetectedEventArgs.cs @@ -1,4 +1,6 @@ -namespace Upsilon.Apps.Passkey.Interfaces.Events +using Upsilon.Apps.Passkey.Interfaces.Models; + +namespace Upsilon.Apps.Passkey.Interfaces.Events { /// /// Represent a warning detected event argument. diff --git a/Interfaces/IAccount.cs b/Interfaces/Models/IAccount.cs similarity index 95% rename from Interfaces/IAccount.cs rename to Interfaces/Models/IAccount.cs index 9bdafd7..8bad577 100644 --- a/Interfaces/IAccount.cs +++ b/Interfaces/Models/IAccount.cs @@ -1,6 +1,6 @@ using Upsilon.Apps.Passkey.Interfaces.Enums; -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Models { /// /// Represent an account. diff --git a/Interfaces/IDatabase.cs b/Interfaces/Models/IDatabase.cs similarity index 97% rename from Interfaces/IDatabase.cs rename to Interfaces/Models/IDatabase.cs index ac24aa5..7e8d627 100644 --- a/Interfaces/IDatabase.cs +++ b/Interfaces/Models/IDatabase.cs @@ -1,6 +1,7 @@ using Upsilon.Apps.Passkey.Interfaces.Events; +using Upsilon.Apps.Passkey.Interfaces.Utils; -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Models { /// /// Represent a database. diff --git a/Interfaces/IItem.cs b/Interfaces/Models/IItem.cs similarity index 86% rename from Interfaces/IItem.cs rename to Interfaces/Models/IItem.cs index caaa06e..9e03bf9 100644 --- a/Interfaces/IItem.cs +++ b/Interfaces/Models/IItem.cs @@ -1,4 +1,4 @@ -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Models { /// /// Represent an item. diff --git a/Interfaces/ILog.cs b/Interfaces/Models/ILog.cs similarity index 89% rename from Interfaces/ILog.cs rename to Interfaces/Models/ILog.cs index 9e3dd57..5c38158 100644 --- a/Interfaces/ILog.cs +++ b/Interfaces/Models/ILog.cs @@ -1,4 +1,4 @@ -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Models { /// /// Represent an event log. diff --git a/Interfaces/IService.cs b/Interfaces/Models/IService.cs similarity index 97% rename from Interfaces/IService.cs rename to Interfaces/Models/IService.cs index e95535d..82c2ca9 100644 --- a/Interfaces/IService.cs +++ b/Interfaces/Models/IService.cs @@ -1,4 +1,4 @@ -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Models { /// /// Represent a service. diff --git a/Interfaces/IUser.cs b/Interfaces/Models/IUser.cs similarity index 97% rename from Interfaces/IUser.cs rename to Interfaces/Models/IUser.cs index 5b1b3b5..dd4263a 100644 --- a/Interfaces/IUser.cs +++ b/Interfaces/Models/IUser.cs @@ -1,6 +1,6 @@ using Upsilon.Apps.Passkey.Interfaces.Enums; -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Models { /// /// Represent an user. diff --git a/Interfaces/IWarning.cs b/Interfaces/Models/IWarning.cs similarity index 91% rename from Interfaces/IWarning.cs rename to Interfaces/Models/IWarning.cs index aaa584d..0b512bb 100644 --- a/Interfaces/IWarning.cs +++ b/Interfaces/Models/IWarning.cs @@ -1,6 +1,6 @@ using Upsilon.Apps.Passkey.Interfaces.Enums; -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Models { /// /// Represent a warning. diff --git a/Interfaces/IClipboardManager.cs b/Interfaces/Utils/IClipboardManager.cs similarity index 77% rename from Interfaces/IClipboardManager.cs rename to Interfaces/Utils/IClipboardManager.cs index f557d2d..c00506f 100644 --- a/Interfaces/IClipboardManager.cs +++ b/Interfaces/Utils/IClipboardManager.cs @@ -1,4 +1,4 @@ -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Utils { /// /// Represent a OS specific Clipboard manager. @@ -8,7 +8,7 @@ public interface IClipboardManager /// /// Remove any occurence of elements in a the given list from the clipboard history. /// - /// The list of eleemnts to remove. + /// The list of elements to remove. /// The number of item removed. int RemoveAllOccurence(string[] removeList); } diff --git a/Interfaces/ICryptographyCenter.cs b/Interfaces/Utils/ICryptographyCenter.cs similarity index 98% rename from Interfaces/ICryptographyCenter.cs rename to Interfaces/Utils/ICryptographyCenter.cs index 7291e54..9ef4627 100644 --- a/Interfaces/ICryptographyCenter.cs +++ b/Interfaces/Utils/ICryptographyCenter.cs @@ -1,4 +1,4 @@ -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Utils { /// /// Represent a cryptographic center. diff --git a/Interfaces/IPasswordFactory.cs b/Interfaces/Utils/IPasswordFactory.cs similarity index 96% rename from Interfaces/IPasswordFactory.cs rename to Interfaces/Utils/IPasswordFactory.cs index 231333c..03d8b3b 100644 --- a/Interfaces/IPasswordFactory.cs +++ b/Interfaces/Utils/IPasswordFactory.cs @@ -1,4 +1,4 @@ -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Utils { /// /// Represent a Password factory engine. diff --git a/Interfaces/ISerializationCenter.cs b/Interfaces/Utils/ISerializationCenter.cs similarity index 94% rename from Interfaces/ISerializationCenter.cs rename to Interfaces/Utils/ISerializationCenter.cs index 6ead7d2..8dfc998 100644 --- a/Interfaces/ISerializationCenter.cs +++ b/Interfaces/Utils/ISerializationCenter.cs @@ -1,4 +1,4 @@ -namespace Upsilon.Apps.Passkey.Interfaces +namespace Upsilon.Apps.Passkey.Interfaces.Utils { /// /// Represent a serialization center. diff --git a/Interfaces/Utils/StaticMethods.cs b/Interfaces/Utils/StaticMethods.cs index 91aa374..11d4d8c 100644 --- a/Interfaces/Utils/StaticMethods.cs +++ b/Interfaces/Utils/StaticMethods.cs @@ -1,4 +1,6 @@ -namespace Upsilon.Apps.Passkey.Interfaces.Utils +using Upsilon.Apps.Passkey.Interfaces.Models; + +namespace Upsilon.Apps.Passkey.Interfaces.Utils { public static class StaticMethods { diff --git a/README.md b/README.md index 0ee519a..2b68428 100644 --- a/README.md +++ b/README.md @@ -28,167 +28,176 @@ This is a C# implementation of a local stored password manager in .Net 10. The a ### Class diagram ```mermaid classDiagram - direction TB + direction LR %% Main Interfaces - class ISerializationCenter { - <> - +Serialize~T~(in toSerialize T) string - +Deserialize~T~(in toDeserialize string) T - } - - class IClipboardManager { - <> - +RemoveAllOccurence(in removeList IEnumerable~string~) int - } - - class IPasswordFactory { - <> - +Alphabetic : string - +Numeric : string - +SpecialChars : string - - +GeneratePassword(in length int, in alphabet string, in checkIfLeaked bool) string - +PasswordLeaked(in password string) bool - } - - class ICryptographyCenter { - <> - +HashLength : int - - +GetHash(in source string) string - +GetSlowHash(in source string) string - +Sign(inout source string) void - +CheckSign(inout source string) bool - +EncryptSymmetrically(inout source string, in passwords IEnumerable~string~) string - +DecryptSymmetrically(inout source string, in passwords IEnumerable~string~) string - +GenerateRandomKeys(out publicKey string, out privateKey string) void - +EncryptAsymmetrically(inout source string, in key string) string - +DecryptAsymmetrically(inout source string, in key string) string - } - - class IItem { - <> - +ItemId : string - +Database : IDatabase - } - - class IAccount { - <> - +Service : IService - +Label : string - +Notes : string - +Identifiers : IEnumerable~string~ - +Password : string - +Passwords : IDictionary~DateTime, string~ - +PasswordUpdateReminderDelay : int - +Options : AccountOption - } - - class IService { - <> - +User : IUser - +ServiceName : string - +Url : string - +Notes : string - +Accounts : IEnumerable~IAccount~ - +AddAccount(in label string, in identifiers IEnumerable~string~, in password string) IAccount - +AddAccount(in label string, in identifiers IEnumerable~string~) IAccount - +AddAccount(in identifiers IEnumerable~string~, in password string) IAccount - +AddAccount(in identifiers IEnumerable~string~) IAccount - +DeleteAccount(in account IAccount) void - } - class IUser { - <> - +Username : string - +Passkeys : IEnumerable~string~ - +LogoutTimeout : int - +CleaningClipboardTimeout : int - +ShowPasswordDelay : int - +NumberOfOldPasswordToKeep : int - +WarningsToNotify : WarningType - +Services : IEnumerable~IService~ - +AddService(in serviceName string) IService - +DeleteService(in service IService) void + namespace Upsilon.Apps.Passkey.Interfaces.Utils { + class ISerializationCenter { + <> + +Serialize~T~(in toSerialize T) string + +Deserialize~T~(in toDeserialize string) T + } + + class IClipboardManager { + <> + +RemoveAllOccurence(in removeList IEnumerable~string~) int + } + + class IPasswordFactory { + <> + +Alphabetic : string + +Numeric : string + +SpecialChars : string + + +GeneratePassword(in length int, in alphabet string, in checkIfLeaked bool) string + +PasswordLeaked(in password string) bool + } + + class ICryptographyCenter { + <> + +HashLength : int + + +GetHash(in source string) string + +GetSlowHash(in source string) string + +Sign(inout source string) void + +CheckSign(inout source string) bool + +EncryptSymmetrically(inout source string, in passwords IEnumerable~string~) string + +DecryptSymmetrically(inout source string, in passwords IEnumerable~string~) string + +GenerateRandomKeys(out publicKey string, out privateKey string) void + +EncryptAsymmetrically(inout source string, in key string) string + +DecryptAsymmetrically(inout source string, in key string) string + } } - class IDatabase { - <> - +DatabaseFile : string - +User : IUser - +SessionLeftTime : int - +Logs : IEnumerable~ILog~ - +Warnings : IEnumerable~IWarning~ - +SerializationCenter : ISerializationCenter - +CryptographyCenter : ICryptographyCenter - +PasswordFactory : IPasswordFactory - +ClipboardManager : IClipboardManager - +WarningDetected : EventHandler~WarningDetectedEventArgs~ - +AutoSaveDetected : EventHandler~AutoSaveDetectedEventArgs~ - +DatabaseSaved : EventHandler - +DatabaseClosed : EventHandler~LogoutEventArgs~ - +Login(in passkey string) IUser - +Save(void) void - +Delete(void) void - +Close(void) void - +HasChanged(void) bool - +HasChanged(in itemId string) bool - +HasChanged(in itemId string, in fieldName string) bool - +ImportFromFile(in filePath string) bool - +ExportToFile(in filePath string) bool - } - - class ILog { - <> - +DateTime : DateTime - +Message : string - +NeedsReview : bool - } - - class IWarning { - <> - +WarningType : WarningType - +Logs : IEnumerable~ILog~ - +Accounts : IEnumerable~IAccount~ + namespace Upsilon.Apps.Passkey.Interfaces.Models { + class IItem { + <> + +ItemId : string + +Database : IDatabase + } + + class IAccount { + <> + +Service : IService + +Label : string + +Notes : string + +Identifiers : IEnumerable~string~ + +Password : string + +Passwords : IDictionary~DateTime, string~ + +PasswordUpdateReminderDelay : int + +Options : AccountOption + } + + class IService { + <> + +User : IUser + +ServiceName : string + +Url : string + +Notes : string + +Accounts : IEnumerable~IAccount~ + +AddAccount(in label string, in identifiers IEnumerable~string~, in password string) IAccount + +AddAccount(in label string, in identifiers IEnumerable~string~) IAccount + +AddAccount(in identifiers IEnumerable~string~, in password string) IAccount + +AddAccount(in identifiers IEnumerable~string~) IAccount + +DeleteAccount(in account IAccount) void + } + + class IUser { + <> + +Username : string + +Passkeys : IEnumerable~string~ + +LogoutTimeout : int + +CleaningClipboardTimeout : int + +ShowPasswordDelay : int + +NumberOfOldPasswordToKeep : int + +WarningsToNotify : WarningType + +Services : IEnumerable~IService~ + +AddService(in serviceName string) IService + +DeleteService(in service IService) void + } + + class IDatabase { + <> + +DatabaseFile : string + +User : IUser + +SessionLeftTime : int + +Logs : IEnumerable~ILog~ + +Warnings : IEnumerable~IWarning~ + +SerializationCenter : ISerializationCenter + +CryptographyCenter : ICryptographyCenter + +PasswordFactory : IPasswordFactory + +ClipboardManager : IClipboardManager + +WarningDetected : EventHandler~WarningDetectedEventArgs~ + +AutoSaveDetected : EventHandler~AutoSaveDetectedEventArgs~ + +DatabaseSaved : EventHandler + +DatabaseClosed : EventHandler~LogoutEventArgs~ + +Login(in passkey string) IUser + +Save(void) void + +Delete(void) void + +Close(void) void + +HasChanged(void) bool + +HasChanged(in itemId string) bool + +HasChanged(in itemId string, in fieldName string) bool + +ImportFromFile(in filePath string) bool + +ExportToFile(in filePath string) bool + } + + class ILog { + <> + +DateTime : DateTime + +Message : string + +NeedsReview : bool + } + + class IWarning { + <> + +WarningType : WarningType + +Logs : IEnumerable~ILog~ + +Accounts : IEnumerable~IAccount~ + } } %% Enums - class AccountOption { - <> - None - WarnIfPasswordLeaked - } - - class WarningType { - <> - LogReviewWarning - PasswordUpdateReminderWarning - DuplicatedPasswordsWarning - PasswordLeakedWarning - } - - class AutoSaveMergeBehavior { - <> - MergeAndSaveThenRemoveAutoSaveFile - MergeWithoutSavingAndKeepAutoSaveFile - DontMergeAndRemoveAutoSaveFile - DontMergeAndKeepAutoSaveFile + namespace Upsilon.Apps.Passkey.Interfaces.Enums { + class AccountOption { + <> + None + WarnIfPasswordLeaked + } + + class WarningType { + <> + LogReviewWarning + PasswordUpdateReminderWarning + DuplicatedPasswordsWarning + PasswordLeakedWarning + } + + class AutoSaveMergeBehavior { + <> + MergeAndSaveThenRemoveAutoSaveFile + MergeWithoutSavingAndKeepAutoSaveFile + DontMergeAndRemoveAutoSaveFile + DontMergeAndKeepAutoSaveFile + } } %% Event Args Classes - class AutoSaveDetectedEventArgs { - +MergeBehavior : AutoSaveMergeBehavior - } - - class WarningDetectedEventArgs { - +Warnings : IEnumerable~IWarning~ + namespace Upsilon.Apps.Passkey.Interfaces.Events { + class AutoSaveDetectedEventArgs { + +MergeBehavior : AutoSaveMergeBehavior + } + + class WarningDetectedEventArgs { + +Warnings : IEnumerable~IWarning~ + } + + class LogoutEventArgs { + +LoginTimeoutReached : bool + } } - - class LogoutEventArgs { - +LoginTimeoutReached : bool - } - + %% Inheritance Relations IUser --|> IItem IService --|> IItem diff --git a/UnitTests/ClipboardManager.cs b/UnitTests/ClipboardManager.cs index 46d1d92..a8603be 100644 --- a/UnitTests/ClipboardManager.cs +++ b/UnitTests/ClipboardManager.cs @@ -1,4 +1,5 @@ using Upsilon.Apps.Passkey.Interfaces; +using Upsilon.Apps.Passkey.Interfaces.Utils; using Windows.ApplicationModel.DataTransfer; namespace Upsilon.Apps.Passkey.Core.Utils diff --git a/UnitTests/Models/AccountUnitTests.cs b/UnitTests/Models/AccountUnitTests.cs index b725bec..963299b 100644 --- a/UnitTests/Models/AccountUnitTests.cs +++ b/UnitTests/Models/AccountUnitTests.cs @@ -1,6 +1,7 @@ using FluentAssertions; using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.UnitTests.Models diff --git a/UnitTests/Models/DatabaseUnitTests.cs b/UnitTests/Models/DatabaseUnitTests.cs index 67699fe..c00cd5f 100644 --- a/UnitTests/Models/DatabaseUnitTests.cs +++ b/UnitTests/Models/DatabaseUnitTests.cs @@ -2,6 +2,7 @@ using Upsilon.Apps.Passkey.Core.Models; using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.UnitTests.Models { diff --git a/UnitTests/Models/ImportExportUnitTests.cs b/UnitTests/Models/ImportExportUnitTests.cs index e87072f..fd3b981 100644 --- a/UnitTests/Models/ImportExportUnitTests.cs +++ b/UnitTests/Models/ImportExportUnitTests.cs @@ -5,6 +5,7 @@ using System.Text; using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; using Upsilon.Apps.Passkey.UnitTests; using static Microsoft.ApplicationInsights.MetricDimensionNames.TelemetryContext; diff --git a/UnitTests/Models/ServiceUnitTests.cs b/UnitTests/Models/ServiceUnitTests.cs index 7bc631d..cbc46e2 100644 --- a/UnitTests/Models/ServiceUnitTests.cs +++ b/UnitTests/Models/ServiceUnitTests.cs @@ -1,6 +1,7 @@ using FluentAssertions; using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.UnitTests.Models diff --git a/UnitTests/Models/UserUnitTests.cs b/UnitTests/Models/UserUnitTests.cs index 92e55db..3249a20 100644 --- a/UnitTests/Models/UserUnitTests.cs +++ b/UnitTests/Models/UserUnitTests.cs @@ -2,6 +2,7 @@ using Upsilon.Apps.Passkey.Core.Models; using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.UnitTests.Models diff --git a/UnitTests/UnitTestsHelper.cs b/UnitTests/UnitTestsHelper.cs index 94866a2..457427d 100644 --- a/UnitTests/UnitTestsHelper.cs +++ b/UnitTests/UnitTestsHelper.cs @@ -7,6 +7,8 @@ using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; +using Upsilon.Apps.Passkey.Interfaces.Utils; namespace Upsilon.Apps.Passkey.UnitTests { From 249ac1962c4a21e1179188b70eac6f69da4d4fe8 Mon Sep 17 00:00:00 2001 From: Yassin Lokhat Date: Wed, 17 Dec 2025 10:48:41 +0300 Subject: [PATCH 4/9] Working on Logs - Part 1 --- Core/Models/AutoSave.cs | 13 ++- Core/Models/Database.cs | 103 +++++++++++++----- Core/Models/Log.cs | 126 +++++++++++++++++++++- Core/Models/User.cs | 24 ++--- Core/Utils/FileLocker.cs | 14 ++- Core/Utils/LogCenter.cs | 39 ++++--- Interfaces/Enums/AutoSaveMergeBehavior.cs | 8 +- Interfaces/Enums/LogEventType.cs | 34 ++++++ Interfaces/Models/ILog.cs | 28 ++++- 9 files changed, 313 insertions(+), 76 deletions(-) create mode 100644 Interfaces/Enums/LogEventType.cs diff --git a/Core/Models/AutoSave.cs b/Core/Models/AutoSave.cs index aafbf94..867fd7a 100644 --- a/Core/Models/AutoSave.cs +++ b/Core/Models/AutoSave.cs @@ -1,4 +1,5 @@ using Upsilon.Apps.Passkey.Core.Utils; +using Upsilon.Apps.Passkey.Interfaces.Enums; namespace Upsilon.Apps.Passkey.Core.Models { @@ -107,13 +108,11 @@ private void _addChange(string itemId, _mergeChanges(changeKey, currentChange); Database.FileLocker.Save(this, Database.AutoSaveFileEntry, Database.Passkeys); - string logMessage = action switch - { - Change.Type.Add => $"{itemName} has been added to {containerName}", - Change.Type.Delete => $"{itemName} has been removed from {containerName}", - _ => $"{itemName}'s {fieldName.ToSentenceCase().ToLower()} has been {(string.IsNullOrWhiteSpace(readableValue) ? $"updated" : $"set to {readableValue}")}", - }; - Database.Logs.AddLog(logMessage, needsReview); + Database.Logs.AddLog(source: itemId, + target: fieldName, + data: readableValue, + eventType: (LogEventType)action, + needsReview); } private void _mergeChanges(string changeKey, Change currentChange) diff --git a/Core/Models/Database.cs b/Core/Models/Database.cs index b9008ed..b6371a1 100644 --- a/Core/Models/Database.cs +++ b/Core/Models/Database.cs @@ -1,4 +1,5 @@ -using Upsilon.Apps.Passkey.Core.Utils; +using System; +using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Events; using Upsilon.Apps.Passkey.Interfaces.Models; @@ -15,7 +16,7 @@ public sealed class Database : IDatabase IUser? IDatabase.User => Get(User); int? IDatabase.SessionLeftTime => User?.SessionLeftTime; - ILog[]? IDatabase.Logs => Get(Logs.Logs); + ILog[]? IDatabase.Logs => Get(Logs.Logs.ToArray()); IWarning[]? IDatabase.Warnings => Get(User is not null ? Warnings : null); @@ -54,7 +55,11 @@ public void Delete() { if (ex is WrongPasswordException passwordException) { - Logs.AddLog($"User {Username} login failed at level {passwordException.PasswordLevel}", needsReview: true); + Logs.AddLog(source: Username, + target: string.Empty, + data: passwordException.PasswordLevel.ToString(), + eventType: LogEventType.LoginFailed, + needsReview: true); } } @@ -62,7 +67,12 @@ public void Delete() { User.Database = this; - Logs.AddLog($"User {Username} logged in", needsReview: false); + Logs.LoadStringLogs(); + Logs.AddLog(source: Username, + target: string.Empty, + data: string.Empty, + eventType: LogEventType.UserLoggedIn, + needsReview: false); if (FileLocker.Exists(AutoSaveFileEntry)) { @@ -93,7 +103,11 @@ public void Delete() public bool ImportFromFile(string filePath) { _save(logSaveEvent: true); - Logs.AddLog($"Importing data from file : '{filePath}'", needsReview: true); + Logs.AddLog(source: Username, + target: string.Empty, + data: filePath, + eventType: LogEventType.ImportingDataStarted, + needsReview: true); string importContent = string.Empty; string errorLog = string.Empty; @@ -121,12 +135,20 @@ public bool ImportFromFile(string filePath) if (string.IsNullOrWhiteSpace(errorLog)) { - Logs.AddLog($"Import completed successfully", needsReview: true); + Logs.AddLog(source: Username, + target: string.Empty, + data: string.Empty, + eventType: LogEventType.ImportingDataSucceded, + needsReview: true); _save(logSaveEvent: true); } else { - Logs.AddLog($"Import failed because {errorLog}", needsReview: true); + Logs.AddLog(source: Username, + target: string.Empty, + data: errorLog, + eventType: LogEventType.ImportingDataFailed, + needsReview: true); } return string.IsNullOrWhiteSpace(errorLog); @@ -135,7 +157,11 @@ public bool ImportFromFile(string filePath) public bool ExportToFile(string filePath) { _save(logSaveEvent: true); - Logs.AddLog($"Exporting data to file : '{filePath}'", needsReview: true); + Logs.AddLog(source: Username, + target: string.Empty, + data: filePath, + eventType: LogEventType.ExportingDataStarted, + needsReview: true); string errorLog = string.Empty; @@ -158,11 +184,19 @@ public bool ExportToFile(string filePath) if (string.IsNullOrWhiteSpace(errorLog)) { - Logs.AddLog($"Export completed successfully", needsReview: true); + Logs.AddLog(source: Username, + target: string.Empty, + data: string.Empty, + eventType: LogEventType.ExportingDataSucceded, + needsReview: true); } else { - Logs.AddLog($"Export failed because {errorLog}", needsReview: true); + Logs.AddLog(source: Username, + target: string.Empty, + data: errorLog, + eventType: LogEventType.ExportingDataFailed, + needsReview: true); } return string.IsNullOrWhiteSpace(errorLog); @@ -221,7 +255,7 @@ private Database(ICryptographyCenter cryptographicCenter, Username = username, PublicKey = publicKey, } - : FileLocker.Open(LogFileEntry, [cryptographicCenter.GetHash(username)]); + : FileLocker.Open(LogFileEntry); Logs.Database = this; } @@ -267,7 +301,11 @@ public static IDatabase Create(ICryptographyCenter cryptographicCenter, Passkeys = [.. passkeys], }; - database.Logs.AddLog($"User {username}'s database created", needsReview: false); + database.Logs.AddLog(source: username, + target: string.Empty, + data: string.Empty, + eventType: LogEventType.DatabaseCreated, + needsReview: false); database._save(logSaveEvent: false); @@ -289,7 +327,11 @@ public static IDatabase Open(ICryptographyCenter cryptographicCenter, FileMode.Open, username); - database.Logs.AddLog($"User {username}'s database opened", needsReview: false); + database.Logs.AddLog(source: username, + target: string.Empty, + data: string.Empty, + eventType: LogEventType.DatabaseOpened, + needsReview: false); return database; } @@ -317,7 +359,11 @@ private void _saveDatabase(bool logSaveEvent) if (logSaveEvent) { - Logs.AddLog($"User {Username}'s database saved", needsReview: false); + Logs.AddLog(source: Username, + target: string.Empty, + data: string.Empty, + eventType: LogEventType.DatabaseSaved, + needsReview: false); } AutoSave.Clear(deleteFile: true); @@ -341,22 +387,25 @@ internal void Close(bool logCloseEvent, bool loginTimeoutReached) { if (User is not null) { - string logoutLog = $"User {Username} logged out"; bool needsReview = AutoSave.Any(); - if (needsReview) - { - logoutLog += " without saving"; - } - else + if (!needsReview) { AutoSave.Clear(deleteFile: true); } - Logs.AddLog(logoutLog, needsReview); + Logs.AddLog(source: Username, + target: string.Empty, + data: needsReview ? "1" : string.Empty, + eventType: LogEventType.UserLoggedOut, + needsReview); } - Logs.AddLog($"User {Username}'s database closed", needsReview: false); + Logs.AddLog(source: Username, + target: string.Empty, + data: string.Empty, + eventType: LogEventType.DatabaseClosed, + needsReview: false); } User = null; @@ -382,23 +431,25 @@ private void _handleAutoSave(AutoSaveMergeBehavior mergeAutoSave) { case AutoSaveMergeBehavior.MergeAndSaveThenRemoveAutoSaveFile: AutoSave.ApplyChanges(deleteFile: true); - Logs.AddLog($"User {Username}'s autosave merged and saved", needsReview: true); _save(logSaveEvent: false); break; case AutoSaveMergeBehavior.MergeWithoutSavingAndKeepAutoSaveFile: AutoSave.ApplyChanges(deleteFile: false); - Logs.AddLog($"User {Username}'s autosave merged without saving", needsReview: true); _saveLogs(); break; case AutoSaveMergeBehavior.DontMergeAndRemoveAutoSaveFile: AutoSave.Clear(deleteFile: true); - Logs.AddLog($"User {Username}'s autosave not merged and removed", needsReview: true); break; case AutoSaveMergeBehavior.DontMergeAndKeepAutoSaveFile: default: - Logs.AddLog($"User {Username}'s autosave not merged and keeped.", needsReview: true); break; } + + Logs.AddLog(source: Username, + target: string.Empty, + data: string.Empty, + eventType: (LogEventType)mergeAutoSave, + needsReview: true); } private void _lookAtWarnings() diff --git a/Core/Models/Log.cs b/Core/Models/Log.cs index 43dc12e..27143d2 100644 --- a/Core/Models/Log.cs +++ b/Core/Models/Log.cs @@ -1,13 +1,131 @@ -using Upsilon.Apps.Passkey.Interfaces.Models; +using System.Security.AccessControl; +using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Models { internal class Log : ILog { - public DateTime DateTime { get; set; } + #region ILog interface - public string Message { get; set; } = string.Empty; + public DateTime DateTime => new(DateTimeTicks); - public bool NeedsReview { get; set; } + public string Source { get; set; } = string.Empty; + + public string Target { get; set; } = string.Empty; + + public string Data { get; set; } = string.Empty; + + public LogEventType EventType { get; set; } = LogEventType.None; + + public bool NeedsReview { get; set; } = true; + + public string Message => _buildMessage(); + + #endregion + + public long DateTimeTicks { get; set; } + + public Log() { } + + public Log(string log) + { + string[] info = log.Split('|'); + + if (info.Length > 0 + && long.TryParse(info[0], out long ticks)) + { + DateTimeTicks = ticks; + } + + if (info.Length > 1) + { + Source = info[1].Trim(); + } + + if (info.Length > 2) + { + Target = info[2].Trim(); + } + + if (info.Length > 3) + { + Target = info[3].Trim(); + } + + if (info.Length > 4 + && byte.TryParse(info[4], out byte eventType)) + { + EventType = (LogEventType)eventType; + } + + if (info.Length > 5) + { + NeedsReview = !string.IsNullOrEmpty(info[5]); + } + } + + public override string ToString() + { + return $"{DateTimeTicks}|{Source}|{Target}|{Data}|{((int)EventType)}|{(NeedsReview ? "1" : "")}"; + } + + private string _buildMessage() + { + /* + string logMessage = action switch + { + Change.Type.Add => $"{itemName} has been added to {containerName}", + Change.Type.Delete => $"{itemName} has been removed from {containerName}", + _ => $"{itemName}'s {fieldName.ToSentenceCase().ToLower()} has been {(string.IsNullOrWhiteSpace(readableValue) ? $"updated" : $"set to {readableValue}")}", + }; + Database.Logs.AddLog($"User {Username}'s login session timeout reached", needsReview: true); + Logs.AddLog($"User {Username} login failed at level {passwordException.PasswordLevel}", needsReview: true); + Logs.AddLog($"User {Username} logged in", needsReview: false); + Logs.AddLog($"Importing data from file : '{filePath}'", needsReview: true); + Logs.AddLog($"Import completed successfully", needsReview: true); + Logs.AddLog($"Import failed because {errorLog}", needsReview: true); + Logs.AddLog($"Exporting data to file : '{filePath}'", needsReview: true); + Logs.AddLog($"Export completed successfully", needsReview: true); + Logs.AddLog($"Export failed because {errorLog}", needsReview: true); + database.Logs.AddLog($"User {username}'s database created", needsReview: false); + database.Logs.AddLog($"User {username}'s database opened", needsReview: false); + Logs.AddLog($"User {Username}'s database saved", needsReview: false); + string logoutLog = $"User {Username} logged out"; + bool needsReview = AutoSave.Any(); + if (needsReview) + { + logoutLog += " without saving"; + } + else + { + AutoSave.Clear(deleteFile: true); + } + Logs.AddLog(logoutLog, needsReview); + } + Logs.AddLog($"User {Username}'s database closed", needsReview: false); + + case AutoSaveMergeBehavior.MergeAndSaveThenRemoveAutoSaveFile: + AutoSave.ApplyChanges(deleteFile: true); + Logs.AddLog($"User {Username}'s autosave merged and saved", needsReview: true); + _save(logSaveEvent: false); + break; + case AutoSaveMergeBehavior.MergeWithoutSavingAndKeepAutoSaveFile: + AutoSave.ApplyChanges(deleteFile: false); + Logs.AddLog($"User {Username}'s autosave merged without saving", needsReview: true); + _saveLogs(); + break; + case AutoSaveMergeBehavior.DontMergeAndRemoveAutoSaveFile: + AutoSave.Clear(deleteFile: true); + Logs.AddLog($"User {Username}'s autosave not merged and removed", needsReview: true); + break; + case AutoSaveMergeBehavior.DontMergeAndKeepAutoSaveFile: + default: + Logs.AddLog($"User {Username}'s autosave not merged and keeped.", needsReview: true); + break; + + */ + return ToString(); + } } } diff --git a/Core/Models/User.cs b/Core/Models/User.cs index 3719a76..e2cba8f 100644 --- a/Core/Models/User.cs +++ b/Core/Models/User.cs @@ -1,4 +1,5 @@ -using System.ComponentModel; +using System; +using System.ComponentModel; using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Models; @@ -207,7 +208,11 @@ private void _timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e) if (SessionLeftTime == 0) { - Database.Logs.AddLog($"User {Username}'s login session timeout reached", needsReview: true); + Database.Logs.AddLog(source: ItemId, + target: string.Empty, + data: string.Empty, + eventType: LogEventType.LoginSessionTimeoutReached, + needsReview: true); Database.Close(logCloseEvent: true, loginTimeoutReached: true); _timer.Stop(); @@ -221,25 +226,12 @@ private void _timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e) if (_clipboardLeftTime == 0) { - _cleanClipboard(); - + Database.ClipboardManager.RemoveAllOccurence([.. Services.SelectMany(x => x.Accounts).SelectMany(x => x.Passwords.Values)]); _clipboardLeftTime = CleaningClipboardTimeout; } } } - private void _cleanClipboard() - { - string[] passwords = [.. Services.SelectMany(x => x.Accounts).SelectMany(x => x.Passwords.Values)]; - - int cleanedPasswordsCount = Database.ClipboardManager.RemoveAllOccurence(passwords); - - if (cleanedPasswordsCount != 0) - { - Database.Logs.AddLog($"{cleanedPasswordsCount} passwords was cleaned from User {Username}'s clipboard", needsReview: false); - } - } - public void ResetTimer() { SessionLeftTime = LogoutTimeout * 60; diff --git a/Core/Utils/FileLocker.cs b/Core/Utils/FileLocker.cs index a4b5e52..89ed1da 100644 --- a/Core/Utils/FileLocker.cs +++ b/Core/Utils/FileLocker.cs @@ -42,11 +42,15 @@ internal T Open(string fileEntry, string[] passkeys) where T : notnull return _readContent(fileEntry, passkeys).DeserializeTo(_serializationCenter); } + internal T Open(string fileEntry) where T : notnull => Open(fileEntry, []); + internal void Save(T obj, string fileEntry, string[] passkeys) where T : notnull { _writeContent(obj.SerializeWith(_serializationCenter), fileEntry, passkeys); } + internal void Save(T obj, string fileEntry) where T : notnull => Save(obj, fileEntry, []); + internal void Delete() { Unlock(); @@ -136,7 +140,10 @@ private string _readContent(string fileEntry, string[] passkeys) using Stream stream = zipEntry.Open(); using StreamReader reader = new(stream, Encoding.UTF8); - content = _cryptographicCenter.DecryptSymmetrically(_decompressString(reader.ReadToEnd()), passkeys); + if (passkeys.Length != 0) + content = _cryptographicCenter.DecryptSymmetrically(_decompressString(reader.ReadToEnd()), passkeys); + else + content = _decompressString(reader.ReadToEnd()); } Lock(); @@ -158,7 +165,10 @@ private void _writeContent(string content, string fileEntry, string[] passkeys) using Stream stream = newEntry.Open(); using StreamWriter writer = new(stream, Encoding.UTF8); - writer.Write(_compressString(_cryptographicCenter.EncryptSymmetrically(content, passkeys))); + if (passkeys.Length != 0) + writer.Write(_compressString(_cryptographicCenter.EncryptSymmetrically(content, passkeys))); + else + writer.Write(_compressString(content)); } Lock(); diff --git a/Core/Utils/LogCenter.cs b/Core/Utils/LogCenter.cs index 00d9055..1345788 100644 --- a/Core/Utils/LogCenter.cs +++ b/Core/Utils/LogCenter.cs @@ -1,5 +1,6 @@ using System.Text.Json.Serialization; using Upsilon.Apps.Passkey.Core.Models; +using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Utils @@ -12,37 +13,47 @@ internal Database Database set; } - [JsonIgnore] - public ILog[]? Logs => Database.User is null - ? null - : LogList.Select(x => Database.CryptographyCenter - .DecryptAsymmetrically(x, Database.User.PrivateKey) - .DeserializeTo(Database.SerializationCenter)) - .OrderByDescending(x => x.DateTime) - .ToArray(); + internal List Logs = []; public List LogList { get; set; } = []; + public string Username { get; set; } = string.Empty; + public string PublicKey { get; set; } = string.Empty; - public void AddLog(string message, bool needsReview) + public void AddLog(string source, string target, string data, LogEventType eventType, bool needsReview) { Log log = new() { - DateTime = DateTime.Now, - Message = message, + DateTimeTicks = DateTime.Now.Ticks, + Source = source, + Target = target, + Data = data, + EventType = eventType, NeedsReview = needsReview, }; - string textLog = log.SerializeWith(Database.SerializationCenter); - LogList.Add(Database.CryptographyCenter.EncryptAsymmetrically(textLog, PublicKey)); + Logs.Add(log); + LogList.Add(Database.CryptographyCenter.EncryptAsymmetrically(log.ToString(), PublicKey)); _save(); } + internal void LoadStringLogs() + { + Logs.Clear(); + + if (Database.User is null) return; + + foreach (string log in LogList) + { + Logs.Add(new Log(Database.CryptographyCenter.DecryptAsymmetrically(log, Database.User.PrivateKey))); + } + } + private void _save() { - Database.FileLocker.Save(this, Database.LogFileEntry, [Database.CryptographyCenter.GetHash(Username)]); + Database.FileLocker.Save(this, Database.LogFileEntry); } } } diff --git a/Interfaces/Enums/AutoSaveMergeBehavior.cs b/Interfaces/Enums/AutoSaveMergeBehavior.cs index b4d32a9..d1f96e5 100644 --- a/Interfaces/Enums/AutoSaveMergeBehavior.cs +++ b/Interfaces/Enums/AutoSaveMergeBehavior.cs @@ -8,18 +8,18 @@ public enum AutoSaveMergeBehavior /// /// The auto-save will be merged into the database and saved then the auto-save file will be removed. /// - MergeAndSaveThenRemoveAutoSaveFile, + MergeAndSaveThenRemoveAutoSaveFile = 10, /// /// The auto-save will be merged into the database without saving and the auto-save file will be keeped. /// - MergeWithoutSavingAndKeepAutoSaveFile, + MergeWithoutSavingAndKeepAutoSaveFile = 11, /// /// The auto-save will not be merged into the database but the auto-save file will be removed. /// - DontMergeAndRemoveAutoSaveFile, + DontMergeAndRemoveAutoSaveFile = 12, /// /// The auto-save will not be merged into the database and the auto-save file will be keeped. /// - DontMergeAndKeepAutoSaveFile, + DontMergeAndKeepAutoSaveFile = 13, } } diff --git a/Interfaces/Enums/LogEventType.cs b/Interfaces/Enums/LogEventType.cs new file mode 100644 index 0000000..1fceb1f --- /dev/null +++ b/Interfaces/Enums/LogEventType.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Upsilon.Apps.Passkey.Interfaces.Enums +{ + public enum LogEventType + { + None = 0, + Update = 1, + Add = 2, + Delete = 3, + + MergeAndSaveThenRemoveAutoSaveFile = 10, + MergeWithoutSavingAndKeepAutoSaveFile = 11, + DontMergeAndRemoveAutoSaveFile = 12, + DontMergeAndKeepAutoSaveFile = 13, + + DatabaseCreated = 90, + DatabaseOpened, + DatabaseSaved, + DatabaseClosed, + LoginSessionTimeoutReached, + LoginFailed, + UserLoggedIn, + UserLoggedOut, + ImportingDataStarted, + ImportingDataSucceded, + ImportingDataFailed, + ExportingDataStarted, + ExportingDataSucceded, + ExportingDataFailed, + } +} diff --git a/Interfaces/Models/ILog.cs b/Interfaces/Models/ILog.cs index 5c38158..a6b2e15 100644 --- a/Interfaces/Models/ILog.cs +++ b/Interfaces/Models/ILog.cs @@ -1,4 +1,6 @@ -namespace Upsilon.Apps.Passkey.Interfaces.Models +using Upsilon.Apps.Passkey.Interfaces.Enums; + +namespace Upsilon.Apps.Passkey.Interfaces.Models { /// /// Represent an event log. @@ -11,13 +13,33 @@ public interface ILog DateTime DateTime { get; } /// - /// The event message. + /// The source of the event. /// - string Message { get; } + string Source { get; } + + /// + /// The target of the event. + /// + string Target { get; } + + /// + /// The raw event data. + /// + string Data { get; } + + /// + /// The event type. + /// + LogEventType EventType { get; } /// /// Indicate if the current log needs review. /// bool NeedsReview { get; set; } + + /// + /// The event message. + /// + string Message { get; } } } From 02b224e156674bd4b3c114e9b3fd08006433b672 Mon Sep 17 00:00:00 2001 From: Yassin Lokhat Date: Thu, 18 Dec 2025 17:35:35 +0300 Subject: [PATCH 5/9] Working on Logs - Part 2 --- Core/Models/Account.cs | 10 +- Core/Models/AutoSave.cs | 62 +++++++----- Core/Models/Change.cs | 14 +-- Core/Models/Database.cs | 79 +++++---------- Core/Models/Log.cs | 118 ++++++++-------------- Core/Models/Service.cs | 20 ++-- Core/Models/User.cs | 25 ++--- Core/Utils/LogCenter.cs | 6 +- Interfaces/Enums/AutoSaveMergeBehavior.cs | 8 +- Interfaces/Enums/LogEventType.cs | 95 ++++++++++++++--- Interfaces/Models/ILog.cs | 20 +--- 11 files changed, 220 insertions(+), 237 deletions(-) diff --git a/Core/Models/Account.cs b/Core/Models/Account.cs index cfd22ed..72b1dec 100644 --- a/Core/Models/Account.cs +++ b/Core/Models/Account.cs @@ -19,7 +19,6 @@ string IAccount.Label { get => Database.Get(Label); set => Label = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(Label), needsReview: false, oldValue: Label, @@ -31,7 +30,6 @@ string[] IAccount.Identifiers { get => Database.Get(Identifiers); set => Identifiers = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(Identifiers), needsReview: true, oldValue: Identifiers, @@ -67,7 +65,6 @@ string IAccount.Password } _ = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(Password), needsReview: true, oldValue: oldPasswords, @@ -84,7 +81,6 @@ string IAccount.Notes { get => Database.Get(Notes); set => Notes = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(Notes), needsReview: false, oldValue: Notes, @@ -96,7 +92,6 @@ int IAccount.PasswordUpdateReminderDelay { get => Database.Get(PasswordUpdateReminderDelay); set => PasswordUpdateReminderDelay = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(PasswordUpdateReminderDelay), needsReview: false, oldValue: PasswordUpdateReminderDelay, @@ -108,7 +103,6 @@ AccountOption IAccount.Options { get => Database.Get(Options); set => Options = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(Options), needsReview: false, oldValue: Options, @@ -157,7 +151,7 @@ public void Apply(Change change) { switch (change.ActionType) { - case Change.Type.Update: + case LogEventType.ItemUpdated: switch (change.FieldName) { case nameof(Label): @@ -184,7 +178,7 @@ public void Apply(Change change) } break; default: - throw new InvalidEnumArgumentException(nameof(change.ActionType), (int)change.ActionType, typeof(Change.Type)); + throw new InvalidEnumArgumentException(nameof(change.ActionType), (int)change.ActionType, typeof(LogEventType)); } } diff --git a/Core/Models/AutoSave.cs b/Core/Models/AutoSave.cs index 867fd7a..29b6a5f 100644 --- a/Core/Models/AutoSave.cs +++ b/Core/Models/AutoSave.cs @@ -1,5 +1,6 @@ using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces.Enums; +using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Models { @@ -14,7 +15,6 @@ internal Database Database public Dictionary> Changes { get; set; } = []; internal T UpdateValue(string itemId, - string itemName, string fieldName, bool needsReview, T oldValue, @@ -24,53 +24,45 @@ internal T UpdateValue(string itemId, if (Database.SerializationCenter.AreDifferent(oldValue, newValue)) { _addChange(itemId, - itemName, - string.Empty, fieldName, oldValue.SerializeWith(Database.SerializationCenter), newValue.SerializeWith(Database.SerializationCenter), readableValue, needsReview, - Change.Type.Update); + LogEventType.ItemUpdated); } return newValue; } internal T AddValue(string itemId, - string itemName, - string containerName, + string readableValue, bool needsReview, T value) where T : notnull { - _addChange(itemId, itemName, containerName, string.Empty, value.SerializeWith(Database.SerializationCenter), string.Empty, needsReview, Change.Type.Add); + _addChange(itemId, string.Empty, value.SerializeWith(Database.SerializationCenter), readableValue, needsReview, LogEventType.ItemAdded); return value; } internal T DeleteValue(string itemId, - string itemName, - string containerName, + string readableValue, bool needsReview, T value) where T : notnull { - _addChange(itemId, itemName, containerName, string.Empty, value.SerializeWith(Database.SerializationCenter), string.Empty, needsReview, Change.Type.Delete); + _addChange(itemId, string.Empty, value.SerializeWith(Database.SerializationCenter), readableValue, needsReview, LogEventType.ItemDeleted); return value; } private void _addChange(string itemId, - string itemName, - string containerName, string fieldName, string newValue, string readableValue, bool needsReview, - Change.Type action) + LogEventType action) { _addChange(itemId, - itemName, - containerName, fieldName, null, newValue, @@ -80,14 +72,12 @@ private void _addChange(string itemId, } private void _addChange(string itemId, - string itemName, - string containerName, string fieldName, string? oldValue, string newValue, string readableValue, bool needsReview, - Change.Type action) + LogEventType action) { string changeKey = $"{itemId}\t{fieldName}"; if (!Changes.ContainsKey(changeKey)) @@ -108,18 +98,40 @@ private void _addChange(string itemId, _mergeChanges(changeKey, currentChange); Database.FileLocker.Save(this, Database.AutoSaveFileEntry, Database.Passkeys); - Database.Logs.AddLog(source: itemId, - target: fieldName, - data: readableValue, - eventType: (LogEventType)action, + + if (itemId == Database.User?.ItemId) + { + itemId = $"User {Database.Username}"; + } + else if (itemId.StartsWith('S')) + { + Service? s = Database.User?.Services.FirstOrDefault(x => x.ItemId == itemId); + + if (s is not null) + { + itemId = $"Service {s}"; + } + } + else if (itemId.StartsWith('A')) + { + Account? a = Database.User?.Services.SelectMany(x => x.Accounts).FirstOrDefault(x => x.ItemId == itemId); + + if (a is not null) + { + itemId = $"Account {a}"; + } + } + + Database.Logs.AddLog(data: [itemId, fieldName, readableValue], + eventType: action, needsReview); } private void _mergeChanges(string changeKey, Change currentChange) { - Change? lastUpdate = Changes[changeKey].LastOrDefault(x => x.ActionType == Change.Type.Update); + Change? lastUpdate = Changes[changeKey].LastOrDefault(x => x.ActionType == LogEventType.ItemUpdated); - if (currentChange.ActionType != Change.Type.Update + if (currentChange.ActionType != LogEventType.ItemUpdated || lastUpdate is null) { Changes[changeKey].Add(currentChange); @@ -141,7 +153,7 @@ private void _mergeChanges(string changeKey, Change currentChange) internal void ApplyChanges(bool deleteFile) { - List changes = Changes.Values.SelectMany(x => x).OrderBy(x => x.Index).ToList(); + List changes = [.. Changes.Values.SelectMany(x => x).OrderBy(x => x.Index)]; foreach (Change change in changes) { diff --git a/Core/Models/Change.cs b/Core/Models/Change.cs index 67ba50c..429a3dc 100644 --- a/Core/Models/Change.cs +++ b/Core/Models/Change.cs @@ -1,17 +1,11 @@ -namespace Upsilon.Apps.Passkey.Core.Models +using Upsilon.Apps.Passkey.Interfaces.Enums; + +namespace Upsilon.Apps.Passkey.Core.Models { internal sealed class Change { - public enum Type - { - None = 0, - Update = 1, - Add = 2, - Delete = 3, - } - public long Index { get; set; } = long.MaxValue; - public Type ActionType { get; set; } = Type.None; + public LogEventType ActionType { get; set; } = LogEventType.None; public string ItemId { get; set; } = string.Empty; public string FieldName { get; set; } = string.Empty; public string? OldValue { get; set; } = null; diff --git a/Core/Models/Database.cs b/Core/Models/Database.cs index b6371a1..1325198 100644 --- a/Core/Models/Database.cs +++ b/Core/Models/Database.cs @@ -16,7 +16,7 @@ public sealed class Database : IDatabase IUser? IDatabase.User => Get(User); int? IDatabase.SessionLeftTime => User?.SessionLeftTime; - ILog[]? IDatabase.Logs => Get(Logs.Logs.ToArray()); + ILog[]? IDatabase.Logs => Get(Logs.Logs.OrderByDescending(x => x.DateTime).ToArray()); IWarning[]? IDatabase.Warnings => Get(User is not null ? Warnings : null); @@ -55,9 +55,7 @@ public void Delete() { if (ex is WrongPasswordException passwordException) { - Logs.AddLog(source: Username, - target: string.Empty, - data: passwordException.PasswordLevel.ToString(), + Logs.AddLog(data: [Username, passwordException.PasswordLevel.ToString()], eventType: LogEventType.LoginFailed, needsReview: true); } @@ -68,9 +66,7 @@ public void Delete() User.Database = this; Logs.LoadStringLogs(); - Logs.AddLog(source: Username, - target: string.Empty, - data: string.Empty, + Logs.AddLog(data: [Username], eventType: LogEventType.UserLoggedIn, needsReview: false); @@ -103,9 +99,7 @@ public void Delete() public bool ImportFromFile(string filePath) { _save(logSaveEvent: true); - Logs.AddLog(source: Username, - target: string.Empty, - data: filePath, + Logs.AddLog(data: [filePath], eventType: LogEventType.ImportingDataStarted, needsReview: true); @@ -135,18 +129,14 @@ public bool ImportFromFile(string filePath) if (string.IsNullOrWhiteSpace(errorLog)) { - Logs.AddLog(source: Username, - target: string.Empty, - data: string.Empty, + Logs.AddLog(data: [], eventType: LogEventType.ImportingDataSucceded, needsReview: true); _save(logSaveEvent: true); } else { - Logs.AddLog(source: Username, - target: string.Empty, - data: errorLog, + Logs.AddLog(data: [errorLog], eventType: LogEventType.ImportingDataFailed, needsReview: true); } @@ -157,9 +147,7 @@ public bool ImportFromFile(string filePath) public bool ExportToFile(string filePath) { _save(logSaveEvent: true); - Logs.AddLog(source: Username, - target: string.Empty, - data: filePath, + Logs.AddLog(data: [filePath], eventType: LogEventType.ExportingDataStarted, needsReview: true); @@ -184,17 +172,13 @@ public bool ExportToFile(string filePath) if (string.IsNullOrWhiteSpace(errorLog)) { - Logs.AddLog(source: Username, - target: string.Empty, - data: string.Empty, + Logs.AddLog(data: [], eventType: LogEventType.ExportingDataSucceded, needsReview: true); } else { - Logs.AddLog(source: Username, - target: string.Empty, - data: errorLog, + Logs.AddLog(data: [errorLog], eventType: LogEventType.ExportingDataFailed, needsReview: true); } @@ -301,9 +285,7 @@ public static IDatabase Create(ICryptographyCenter cryptographicCenter, Passkeys = [.. passkeys], }; - database.Logs.AddLog(source: username, - target: string.Empty, - data: string.Empty, + database.Logs.AddLog(data: [username], eventType: LogEventType.DatabaseCreated, needsReview: false); @@ -327,9 +309,7 @@ public static IDatabase Open(ICryptographyCenter cryptographicCenter, FileMode.Open, username); - database.Logs.AddLog(source: username, - target: string.Empty, - data: string.Empty, + database.Logs.AddLog(data: [username], eventType: LogEventType.DatabaseOpened, needsReview: false); @@ -359,9 +339,7 @@ private void _saveDatabase(bool logSaveEvent) if (logSaveEvent) { - Logs.AddLog(source: Username, - target: string.Empty, - data: string.Empty, + Logs.AddLog(data: [Username], eventType: LogEventType.DatabaseSaved, needsReview: false); } @@ -394,16 +372,12 @@ internal void Close(bool logCloseEvent, bool loginTimeoutReached) AutoSave.Clear(deleteFile: true); } - Logs.AddLog(source: Username, - target: string.Empty, - data: needsReview ? "1" : string.Empty, + Logs.AddLog(data: [Username, needsReview ? "1" : string.Empty], eventType: LogEventType.UserLoggedOut, needsReview); } - Logs.AddLog(source: Username, - target: string.Empty, - data: string.Empty, + Logs.AddLog(data: [Username], eventType: LogEventType.DatabaseClosed, needsReview: false); } @@ -445,9 +419,7 @@ private void _handleAutoSave(AutoSaveMergeBehavior mergeAutoSave) break; } - Logs.AddLog(source: Username, - target: string.Empty, - data: string.Empty, + Logs.AddLog(data: [Username], eventType: (LogEventType)mergeAutoSave, needsReview: true); } @@ -484,15 +456,18 @@ private Warning[] _lookAtLogWarnings() List logs = [.. Logs.Logs.Cast()]; - for (int i = 0; i < logs.Count && logs[i].Message != $"User {Username} logged in"; i++) - { - if (!logs[i].NeedsReview - || !logs[i].Message.StartsWith($"User {Username}'s autosave ")) - { - logs.RemoveAt(i); - i--; - } - } + //for (int i = 0; i < logs.Count && logs[i].EventType != LogEventType.UserLoggedIn; i++) + //{ + // if (!logs[i].NeedsReview + // || (logs[i].EventType != LogEventType.MergeAndSaveThenRemoveAutoSaveFile + // && logs[i].EventType != LogEventType.MergeWithoutSavingAndKeepAutoSaveFile + // && logs[i].EventType != LogEventType.DontMergeAndRemoveAutoSaveFile + // && logs[i].EventType != LogEventType.DontMergeAndKeepAutoSaveFile)) + // { + // logs.RemoveAt(i); + // i--; + // } + //} return [new Warning([.. logs.Where(x => x.NeedsReview)])]; } diff --git a/Core/Models/Log.cs b/Core/Models/Log.cs index 27143d2..8b8fc25 100644 --- a/Core/Models/Log.cs +++ b/Core/Models/Log.cs @@ -1,4 +1,5 @@ using System.Security.AccessControl; +using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Models; @@ -10,26 +11,26 @@ internal class Log : ILog public DateTime DateTime => new(DateTimeTicks); - public string Source { get; set; } = string.Empty; - - public string Target { get; set; } = string.Empty; - - public string Data { get; set; } = string.Empty; - public LogEventType EventType { get; set; } = LogEventType.None; public bool NeedsReview { get; set; } = true; + public string[] Data { get; set; } = []; + public string Message => _buildMessage(); #endregion public long DateTimeTicks { get; set; } + private readonly Database? _database; + public Log() { } - public Log(string log) + public Log(Database database, string log) { + _database = database; + string[] info = log.Split('|'); if (info.Length > 0 @@ -38,94 +39,57 @@ public Log(string log) DateTimeTicks = ticks; } - if (info.Length > 1) + if (info.Length > 1 + && byte.TryParse(info[1], out byte eventType)) { - Source = info[1].Trim(); + EventType = (LogEventType)eventType; } if (info.Length > 2) { - Target = info[2].Trim(); + NeedsReview = !string.IsNullOrEmpty(info[2]); } if (info.Length > 3) { - Target = info[3].Trim(); - } - - if (info.Length > 4 - && byte.TryParse(info[4], out byte eventType)) - { - EventType = (LogEventType)eventType; - } - - if (info.Length > 5) - { - NeedsReview = !string.IsNullOrEmpty(info[5]); + Data = info[3..]; } } public override string ToString() { - return $"{DateTimeTicks}|{Source}|{Target}|{Data}|{((int)EventType)}|{(NeedsReview ? "1" : "")}"; + return $"{DateTimeTicks}|{((int)EventType)}|{(NeedsReview ? "1" : "")}|{string.Join("|", Data)}"; } private string _buildMessage() { - /* - string logMessage = action switch - { - Change.Type.Add => $"{itemName} has been added to {containerName}", - Change.Type.Delete => $"{itemName} has been removed from {containerName}", - _ => $"{itemName}'s {fieldName.ToSentenceCase().ToLower()} has been {(string.IsNullOrWhiteSpace(readableValue) ? $"updated" : $"set to {readableValue}")}", - }; - Database.Logs.AddLog($"User {Username}'s login session timeout reached", needsReview: true); - Logs.AddLog($"User {Username} login failed at level {passwordException.PasswordLevel}", needsReview: true); - Logs.AddLog($"User {Username} logged in", needsReview: false); - Logs.AddLog($"Importing data from file : '{filePath}'", needsReview: true); - Logs.AddLog($"Import completed successfully", needsReview: true); - Logs.AddLog($"Import failed because {errorLog}", needsReview: true); - Logs.AddLog($"Exporting data to file : '{filePath}'", needsReview: true); - Logs.AddLog($"Export completed successfully", needsReview: true); - Logs.AddLog($"Export failed because {errorLog}", needsReview: true); - database.Logs.AddLog($"User {username}'s database created", needsReview: false); - database.Logs.AddLog($"User {username}'s database opened", needsReview: false); - Logs.AddLog($"User {Username}'s database saved", needsReview: false); - string logoutLog = $"User {Username} logged out"; - bool needsReview = AutoSave.Any(); - if (needsReview) - { - logoutLog += " without saving"; - } - else - { - AutoSave.Clear(deleteFile: true); - } - Logs.AddLog(logoutLog, needsReview); - } - Logs.AddLog($"User {Username}'s database closed", needsReview: false); - - case AutoSaveMergeBehavior.MergeAndSaveThenRemoveAutoSaveFile: - AutoSave.ApplyChanges(deleteFile: true); - Logs.AddLog($"User {Username}'s autosave merged and saved", needsReview: true); - _save(logSaveEvent: false); - break; - case AutoSaveMergeBehavior.MergeWithoutSavingAndKeepAutoSaveFile: - AutoSave.ApplyChanges(deleteFile: false); - Logs.AddLog($"User {Username}'s autosave merged without saving", needsReview: true); - _saveLogs(); - break; - case AutoSaveMergeBehavior.DontMergeAndRemoveAutoSaveFile: - AutoSave.Clear(deleteFile: true); - Logs.AddLog($"User {Username}'s autosave not merged and removed", needsReview: true); - break; - case AutoSaveMergeBehavior.DontMergeAndKeepAutoSaveFile: - default: - Logs.AddLog($"User {Username}'s autosave not merged and keeped.", needsReview: true); - break; - - */ - return ToString(); + string message = EventType switch + { + LogEventType.MergeAndSaveThenRemoveAutoSaveFile => $"User {Data[0]}'s autosave merged and saved", + LogEventType.MergeWithoutSavingAndKeepAutoSaveFile => $"User {Data[0]}'s autosave merged without saving", + LogEventType.DontMergeAndRemoveAutoSaveFile => $"User {Data[0]}'s autosave not merged and removed", + LogEventType.DontMergeAndKeepAutoSaveFile => $"User {Data[0]}'s autosave not merged and keeped", + LogEventType.DatabaseCreated => $"User {Data[0]}'s database created", + LogEventType.DatabaseOpened => $"User {Data[0]}'s database opened", + LogEventType.DatabaseSaved => $"User {Data[0]}'s database saved", + LogEventType.DatabaseClosed => $"User {Data[0]}'s database closed", + LogEventType.LoginSessionTimeoutReached => $"User {Data[0]}'s login session timeout reached", + LogEventType.LoginFailed => $"User {Data[0]} login failed at level {Data[1]}", + LogEventType.UserLoggedIn => $"User {Data[0]} logged in", + LogEventType.UserLoggedOut => $"User {Data[0]} logged out {(!string.IsNullOrEmpty(Data[1]) ? "without saving" : "")}", + LogEventType.ImportingDataStarted => $"Importing data from file : '{Data[0]}'", + LogEventType.ImportingDataSucceded => $"Import completed successfully", + LogEventType.ImportingDataFailed => $"Import failed because {Data[0]}", + LogEventType.ExportingDataStarted => $"Exporting data to file : '{Data[0]}'", + LogEventType.ExportingDataSucceded => $"Export completed successfully", + LogEventType.ExportingDataFailed => $"Export failed because {Data[0]}", + LogEventType.ItemUpdated => $"{Data[0]}'s {Data[1].ToSentenceCase().ToLower()} has been {(string.IsNullOrWhiteSpace(Data[2]) ? $"updated" : $"set to {Data[2]}")}", + LogEventType.ItemAdded => $"{Data[2]} has been added to {Data[0]}", + LogEventType.ItemDeleted => $"{Data[2]} has been removed from {Data[0]}", + _ => ToString(), + }; + + return message.Trim(); } } } diff --git a/Core/Models/Service.cs b/Core/Models/Service.cs index 92e8017..6fa6c90 100644 --- a/Core/Models/Service.cs +++ b/Core/Models/Service.cs @@ -1,5 +1,6 @@ using System.ComponentModel; using Upsilon.Apps.Passkey.Core.Utils; +using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Models @@ -19,7 +20,6 @@ string IService.ServiceName { get => Database.Get(ServiceName); set => ServiceName = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(ServiceName), needsReview: true, oldValue: ServiceName, @@ -31,7 +31,6 @@ string IService.Url { get => Database.Get(Url); set => Url = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(Url), needsReview: false, oldValue: Url, @@ -43,7 +42,6 @@ string IService.Notes { get => Database.Get(Notes); set => Notes = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(Notes), needsReview: false, oldValue: Notes, @@ -56,16 +54,15 @@ public IAccount AddAccount(string label, IEnumerable identifiers, string Account account = new() { Service = this, - ItemId = ItemId + Database.CryptographyCenter.GetHash(label + string.Join(string.Empty, identifiers)), + ItemId = "A" + Database.CryptographyCenter.GetHash(label + string.Join(string.Empty, identifiers)), Label = label, Identifiers = [.. identifiers], Password = password, }; - Accounts.Add(Database.AutoSave.AddValue(ItemId, itemName: account.ToString(), containerName: ToString(), needsReview: false, account)); + Accounts.Add(Database.AutoSave.AddValue(ItemId, readableValue: account.ToString(), needsReview: false, account)); account.Passwords[DateTime.Now] = Database.AutoSave.UpdateValue(account.ItemId, - itemName: account.ToString(), fieldName: nameof(account.Password), needsReview: true, oldValue: string.Empty, @@ -95,8 +92,7 @@ void IService.DeleteAccount(IAccount account) Account accountToRemove = Accounts.FirstOrDefault(x => x.ItemId == account.ItemId) ?? throw new KeyNotFoundException($"The '{account.ItemId}' account was not found into the '{ItemId}' service"); - _ = Accounts.Remove(Database.AutoSave.DeleteValue(ItemId, itemName: accountToRemove.ToString(), containerName: ToString(), needsReview: true, accountToRemove)); - + _ = Accounts.Remove(Database.AutoSave.DeleteValue(ItemId, readableValue: accountToRemove.ToString(), needsReview: true, accountToRemove)); } #endregion @@ -147,7 +143,7 @@ private void _apply(Change change) { switch (change.ActionType) { - case Change.Type.Update: + case LogEventType.ItemUpdated: switch (change.FieldName) { case nameof(ServiceName): @@ -163,17 +159,17 @@ private void _apply(Change change) throw new InvalidDataException("FieldName not valid"); } break; - case Change.Type.Add: + case LogEventType.ItemAdded: Account accountToAdd = change.NewValue.DeserializeTo(Database.SerializationCenter); accountToAdd.Service = this; Accounts.Add(accountToAdd); break; - case Change.Type.Delete: + case LogEventType.ItemDeleted: Account accountToDelete = change.NewValue.DeserializeTo(Database.SerializationCenter); _ = Accounts.RemoveAll(x => x.ItemId == accountToDelete.ItemId); break; default: - throw new InvalidEnumArgumentException(nameof(change.ActionType), (int)change.ActionType, typeof(Change.Type)); + throw new InvalidEnumArgumentException(nameof(change.ActionType), (int)change.ActionType, typeof(LogEventType)); } } diff --git a/Core/Models/User.cs b/Core/Models/User.cs index e2cba8f..08ae9fc 100644 --- a/Core/Models/User.cs +++ b/Core/Models/User.cs @@ -24,7 +24,6 @@ string IUser.Username CredentialChanged |= Username != value; Username = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(Username), needsReview: true, oldValue: Username, @@ -41,7 +40,6 @@ string[] IUser.Passkeys CredentialChanged |= Database.SerializationCenter.AreDifferent(Passkeys, value); Passkeys = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(Passkeys), needsReview: true, oldValue: Passkeys, @@ -54,7 +52,6 @@ int IUser.LogoutTimeout { get => Database.Get(LogoutTimeout); set => LogoutTimeout = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(LogoutTimeout), needsReview: false, oldValue: LogoutTimeout, @@ -66,7 +63,6 @@ int IUser.CleaningClipboardTimeout { get => Database.Get(CleaningClipboardTimeout); set => CleaningClipboardTimeout = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(CleaningClipboardTimeout), needsReview: false, oldValue: CleaningClipboardTimeout, @@ -78,7 +74,6 @@ int IUser.ShowPasswordDelay { get => Database.Get(ShowPasswordDelay); set => ShowPasswordDelay = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(ShowPasswordDelay), needsReview: false, oldValue: ShowPasswordDelay, @@ -92,7 +87,6 @@ int IUser.NumberOfOldPasswordToKeep set { NumberOfOldPasswordToKeep = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(NumberOfOldPasswordToKeep), needsReview: true, oldValue: NumberOfOldPasswordToKeep, @@ -121,7 +115,6 @@ WarningType IUser.WarningsToNotify { get => Database.Get(WarningsToNotify); set => WarningsToNotify = Database.AutoSave.UpdateValue(ItemId, - itemName: ToString(), fieldName: nameof(WarningsToNotify), needsReview: true, oldValue: WarningsToNotify, @@ -134,11 +127,11 @@ IService IUser.AddService(string serviceName) Service service = new() { User = this, - ItemId = ItemId + Database.CryptographyCenter.GetHash(serviceName), + ItemId = "S" + Database.CryptographyCenter.GetHash(serviceName), ServiceName = serviceName }; - Services.Add(Database.AutoSave.AddValue(ItemId, itemName: service.ToString(), containerName: ToString(), needsReview: false, value: service)); + Services.Add(Database.AutoSave.AddValue(ItemId, readableValue: service.ToString(), needsReview: false, value: service)); return service; } @@ -148,7 +141,7 @@ void IUser.DeleteService(IService service) Service serviceToRemove = Services.FirstOrDefault(x => x.ItemId == service.ItemId) ?? throw new KeyNotFoundException($"The '{service.ItemId}' service was not found into the '{ItemId}' user"); - _ = Services.Remove(Database.AutoSave.DeleteValue(ItemId, itemName: serviceToRemove.ToString(), containerName: ToString(), needsReview: true, value: serviceToRemove)); + _ = Services.Remove(Database.AutoSave.DeleteValue(ItemId, readableValue: serviceToRemove.ToString(), needsReview: true, value: serviceToRemove)); } #endregion @@ -208,9 +201,7 @@ private void _timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e) if (SessionLeftTime == 0) { - Database.Logs.AddLog(source: ItemId, - target: string.Empty, - data: string.Empty, + Database.Logs.AddLog(data: [Username], eventType: LogEventType.LoginSessionTimeoutReached, needsReview: true); Database.Close(logCloseEvent: true, loginTimeoutReached: true); @@ -261,7 +252,7 @@ private void _apply(Change change) { switch (change.ActionType) { - case Change.Type.Update: + case LogEventType.ItemUpdated: switch (change.FieldName) { case nameof(Username): @@ -285,17 +276,17 @@ private void _apply(Change change) throw new InvalidDataException("FieldName not valid"); } break; - case Change.Type.Add: + case LogEventType.ItemAdded: Service serviceToAdd = change.NewValue.DeserializeTo(Database.SerializationCenter); serviceToAdd.User = this; Services.Add(serviceToAdd); break; - case Change.Type.Delete: + case LogEventType.ItemDeleted: Service serviceToDelete = change.NewValue.DeserializeTo(Database.SerializationCenter); _ = Services.RemoveAll(x => x.ItemId == serviceToDelete.ItemId); break; default: - throw new InvalidEnumArgumentException(nameof(change.ActionType), (int)change.ActionType, typeof(Change.Type)); + throw new InvalidEnumArgumentException(nameof(change.ActionType), (int)change.ActionType, typeof(LogEventType)); } } diff --git a/Core/Utils/LogCenter.cs b/Core/Utils/LogCenter.cs index 1345788..38aa2ee 100644 --- a/Core/Utils/LogCenter.cs +++ b/Core/Utils/LogCenter.cs @@ -21,13 +21,11 @@ internal Database Database public string PublicKey { get; set; } = string.Empty; - public void AddLog(string source, string target, string data, LogEventType eventType, bool needsReview) + public void AddLog(string[] data, LogEventType eventType, bool needsReview) { Log log = new() { DateTimeTicks = DateTime.Now.Ticks, - Source = source, - Target = target, Data = data, EventType = eventType, NeedsReview = needsReview, @@ -47,7 +45,7 @@ internal void LoadStringLogs() foreach (string log in LogList) { - Logs.Add(new Log(Database.CryptographyCenter.DecryptAsymmetrically(log, Database.User.PrivateKey))); + Logs.Add(new Log(Database, Database.CryptographyCenter.DecryptAsymmetrically(log, Database.User.PrivateKey))); } } diff --git a/Interfaces/Enums/AutoSaveMergeBehavior.cs b/Interfaces/Enums/AutoSaveMergeBehavior.cs index d1f96e5..ebfb2f8 100644 --- a/Interfaces/Enums/AutoSaveMergeBehavior.cs +++ b/Interfaces/Enums/AutoSaveMergeBehavior.cs @@ -8,18 +8,18 @@ public enum AutoSaveMergeBehavior /// /// The auto-save will be merged into the database and saved then the auto-save file will be removed. /// - MergeAndSaveThenRemoveAutoSaveFile = 10, + MergeAndSaveThenRemoveAutoSaveFile = 1, /// /// The auto-save will be merged into the database without saving and the auto-save file will be keeped. /// - MergeWithoutSavingAndKeepAutoSaveFile = 11, + MergeWithoutSavingAndKeepAutoSaveFile = 2, /// /// The auto-save will not be merged into the database but the auto-save file will be removed. /// - DontMergeAndRemoveAutoSaveFile = 12, + DontMergeAndRemoveAutoSaveFile = 3, /// /// The auto-save will not be merged into the database and the auto-save file will be keeped. /// - DontMergeAndKeepAutoSaveFile = 13, + DontMergeAndKeepAutoSaveFile = 4, } } diff --git a/Interfaces/Enums/LogEventType.cs b/Interfaces/Enums/LogEventType.cs index 1fceb1f..4f0f4df 100644 --- a/Interfaces/Enums/LogEventType.cs +++ b/Interfaces/Enums/LogEventType.cs @@ -1,34 +1,103 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Upsilon.Apps.Passkey.Interfaces.Enums +namespace Upsilon.Apps.Passkey.Interfaces.Enums { + /// + /// Represent the event type. + /// public enum LogEventType { + /// + /// No event type. + /// None = 0, - Update = 1, - Add = 2, - Delete = 3, - MergeAndSaveThenRemoveAutoSaveFile = 10, - MergeWithoutSavingAndKeepAutoSaveFile = 11, - DontMergeAndRemoveAutoSaveFile = 12, - DontMergeAndKeepAutoSaveFile = 13, + /// + /// The auto-save merged and saved then removed. + /// Should match with the AutoSaveMergeBehavior value. + /// + MergeAndSaveThenRemoveAutoSaveFile = 1, + /// + /// The auto-save merged but not saved. + /// Should match with the AutoSaveMergeBehavior value. + /// + MergeWithoutSavingAndKeepAutoSaveFile = 2, + /// + /// The auto-save not merged then removed. + /// Should match with the AutoSaveMergeBehavior value. + /// + DontMergeAndRemoveAutoSaveFile = 3, + /// + /// The auto-save not merged. + /// Should match with the AutoSaveMergeBehavior value. + /// + DontMergeAndKeepAutoSaveFile = 4, - DatabaseCreated = 90, + /// + /// Database created. + /// + DatabaseCreated = 10, + /// + /// Database opened. + /// DatabaseOpened, + /// + /// Database saved. + /// DatabaseSaved, + /// + /// Database closed. + /// DatabaseClosed, + /// + /// Login session timeout reached. + /// LoginSessionTimeoutReached, + /// + /// Login failed. + /// LoginFailed, + /// + /// User logged in. + /// UserLoggedIn, + /// + /// User logged out. + /// UserLoggedOut, + /// + /// Importing data started. + /// ImportingDataStarted, + /// + /// Importing data succeded. + /// ImportingDataSucceded, + /// + /// Importing data failed. + /// ImportingDataFailed, + /// + /// Exporting data started. + /// ExportingDataStarted, + /// + /// Exporting data succeded. + /// ExportingDataSucceded, + /// + /// Exporting data failed. + /// ExportingDataFailed, + /// + /// Item updated. + /// + ItemUpdated, + /// + /// Item added. + /// + ItemAdded, + /// + /// Item deleted. + /// + ItemDeleted, } } diff --git a/Interfaces/Models/ILog.cs b/Interfaces/Models/ILog.cs index a6b2e15..99ec7e1 100644 --- a/Interfaces/Models/ILog.cs +++ b/Interfaces/Models/ILog.cs @@ -12,21 +12,6 @@ public interface ILog /// DateTime DateTime { get; } - /// - /// The source of the event. - /// - string Source { get; } - - /// - /// The target of the event. - /// - string Target { get; } - - /// - /// The raw event data. - /// - string Data { get; } - /// /// The event type. /// @@ -37,6 +22,11 @@ public interface ILog /// bool NeedsReview { get; set; } + /// + /// The raw event data. + /// + string[] Data { get; } + /// /// The event message. /// From bff1c75fa8581c6c7b8883695f09bc1083431357 Mon Sep 17 00:00:00 2001 From: Yassin Lokhat Date: Thu, 18 Dec 2025 20:31:12 +0300 Subject: [PATCH 6/9] Working on Logs - Part 3 --- Core/Models/AutoSave.cs | 9 ++++-- UnitTests/Models/AccountUnitTests.cs | 44 ++++++++++++++-------------- 2 files changed, 28 insertions(+), 25 deletions(-) diff --git a/Core/Models/AutoSave.cs b/Core/Models/AutoSave.cs index 29b6a5f..1a7443d 100644 --- a/Core/Models/AutoSave.cs +++ b/Core/Models/AutoSave.cs @@ -101,7 +101,10 @@ private void _addChange(string itemId, if (itemId == Database.User?.ItemId) { - itemId = $"User {Database.Username}"; + if (Database.User is not null) + { + itemId = Database.User.ToString(); + } } else if (itemId.StartsWith('S')) { @@ -109,7 +112,7 @@ private void _addChange(string itemId, if (s is not null) { - itemId = $"Service {s}"; + itemId = s.ToString(); } } else if (itemId.StartsWith('A')) @@ -118,7 +121,7 @@ private void _addChange(string itemId, if (a is not null) { - itemId = $"Account {a}"; + itemId = a.ToString(); } } diff --git a/UnitTests/Models/AccountUnitTests.cs b/UnitTests/Models/AccountUnitTests.cs index 963299b..a8ffe6d 100644 --- a/UnitTests/Models/AccountUnitTests.cs +++ b/UnitTests/Models/AccountUnitTests.cs @@ -37,9 +37,9 @@ public void Case01_AddAccountUpdateSaved() // When IAccount account = service.AddAccount(oldAccountLabel, oldIdentifiers, oldPassword); - expectedLogs.Push($"Information : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)}) has been added to Service {service.ServiceName}"); - expectedLogs.Push($"Warning : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)})'s password has been updated"); - expectedLogWarnings.Push($"Warning : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)})'s password has been updated"); + expectedLogs.Push($"Information : {account} has been added to Service {service.ServiceName}"); + expectedLogs.Push($"Warning : {account}'s password has been updated"); + expectedLogWarnings.Push($"Warning : {account}'s password has been updated"); // Then databaseCreated.User.HasChanged().Should().BeTrue(); @@ -54,23 +54,23 @@ public void Case01_AddAccountUpdateSaved() // When account.Label = newAccountLabel; account.Label = newAccountLabel; - expectedLogs.Push($"Information : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)})'s label has been set to {newAccountLabel}"); + expectedLogs.Push($"Information : {account}'s label has been set to {newAccountLabel}"); account.Identifiers = newIdentifiers; account.Identifiers = newIdentifiers; - expectedLogs.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", oldIdentifiers)})'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); - expectedLogWarnings.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", oldIdentifiers)})'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); + expectedLogs.Push($"Warning : Account {account}'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); + expectedLogWarnings.Push($"Warning : Account {account}'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); account.Password = newPassword; account.Password = newPassword; - expectedLogs.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s password has been updated"); - expectedLogWarnings.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s password has been updated"); + expectedLogs.Push($"Warning : Account {account}'s password has been updated"); + expectedLogWarnings.Push($"Warning : Account {account}'s password has been updated"); account.Notes = notes; account.Notes = notes; - expectedLogs.Push($"Information : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s notes has been set to {notes}"); + expectedLogs.Push($"Information : Account {account}'s notes has been set to {notes}"); account.PasswordUpdateReminderDelay = passwordUpdateReminderDelay; - expectedLogs.Push($"Information : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s password update reminder delay has been set to {passwordUpdateReminderDelay}"); + expectedLogs.Push($"Information : Account {account}'s password update reminder delay has been set to {passwordUpdateReminderDelay}"); account.Options = options; account.Options = options; - expectedLogs.Push($"Information : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s options has been set to {options}"); + expectedLogs.Push($"Information : Account {account}'s options has been set to {options}"); // Then databaseCreated.User.HasChanged().Should().BeTrue(); @@ -147,9 +147,9 @@ public void Case02_AddAccountUpdateAutoSave() // When IAccount account = service.AddAccount(oldAccountLabel, oldIdentifiers, oldPassword); - expectedLogs.Push($"Information : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)}) has been added to Service {service.ServiceName}"); - expectedLogs.Push($"Warning : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)})'s password has been updated"); - expectedLogWarnings.Push($"Warning : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)})'s password has been updated"); + expectedLogs.Push($"Information : {account} has been added to Service {service.ServiceName}"); + expectedLogs.Push($"Warning : {account}'s password has been updated"); + expectedLogWarnings.Push($"Warning : {account}'s password has been updated"); // Then _ = service.Accounts.Length.Should().Be(1); @@ -161,23 +161,23 @@ public void Case02_AddAccountUpdateAutoSave() // When account.Label = newAccountLabel; account.Label = newAccountLabel; - expectedLogs.Push($"Information : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)})'s label has been set to {newAccountLabel}"); + expectedLogs.Push($"Information : {account}'s label has been set to {newAccountLabel}"); account.Identifiers = newIdentifiers; account.Identifiers = newIdentifiers; - expectedLogs.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", oldIdentifiers)})'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); - expectedLogWarnings.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", oldIdentifiers)})'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); + expectedLogs.Push($"Warning : Account {account}'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); + expectedLogWarnings.Push($"Warning : Account {account}'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); account.Password = newPassword; account.Password = newPassword; - expectedLogs.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s password has been updated"); - expectedLogWarnings.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s password has been updated"); + expectedLogs.Push($"Warning : Account {account}'s password has been updated"); + expectedLogWarnings.Push($"Warning : Account {account}'s password has been updated"); account.Notes = notes; account.Notes = notes; - expectedLogs.Push($"Information : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s notes has been set to {notes}"); + expectedLogs.Push($"Information : Account {account}'s notes has been set to {notes}"); account.PasswordUpdateReminderDelay = passwordUpdateReminderDelay; - expectedLogs.Push($"Information : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s password update reminder delay has been set to {passwordUpdateReminderDelay}"); + expectedLogs.Push($"Information : Account {account}'s password update reminder delay has been set to {passwordUpdateReminderDelay}"); account.Options = options; account.Options = options; - expectedLogs.Push($"Information : Account {newAccountLabel} ({string.Join(", ", newIdentifiers)})'s options has been set to {options}"); + expectedLogs.Push($"Information : Account {account}'s options has been set to {options}"); databaseCreated.Close(); expectedLogs.Push($"Warning : User {username} logged out without saving"); From 7101668272fb63b591d5cd3107efdb41fc43d74c Mon Sep 17 00:00:00 2001 From: Yassin Lokhat Date: Fri, 19 Dec 2025 06:40:07 +0300 Subject: [PATCH 7/9] Code Cleanup --- Core/Models/AutoSave.cs | 1 - Core/Models/Database.cs | 3 +-- Core/Models/Log.cs | 5 ++--- Core/Models/User.cs | 5 ++--- Core/Utils/FileLocker.cs | 7 +++---- Core/Utils/LogCenter.cs | 3 +-- 6 files changed, 9 insertions(+), 15 deletions(-) diff --git a/Core/Models/AutoSave.cs b/Core/Models/AutoSave.cs index 1a7443d..646844a 100644 --- a/Core/Models/AutoSave.cs +++ b/Core/Models/AutoSave.cs @@ -1,6 +1,5 @@ using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces.Enums; -using Upsilon.Apps.Passkey.Interfaces.Models; namespace Upsilon.Apps.Passkey.Core.Models { diff --git a/Core/Models/Database.cs b/Core/Models/Database.cs index 1325198..8029855 100644 --- a/Core/Models/Database.cs +++ b/Core/Models/Database.cs @@ -1,5 +1,4 @@ -using System; -using Upsilon.Apps.Passkey.Core.Utils; +using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Events; using Upsilon.Apps.Passkey.Interfaces.Models; diff --git a/Core/Models/Log.cs b/Core/Models/Log.cs index 8b8fc25..773e6ba 100644 --- a/Core/Models/Log.cs +++ b/Core/Models/Log.cs @@ -1,5 +1,4 @@ -using System.Security.AccessControl; -using Upsilon.Apps.Passkey.Core.Utils; +using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Models; @@ -58,7 +57,7 @@ public Log(Database database, string log) public override string ToString() { - return $"{DateTimeTicks}|{((int)EventType)}|{(NeedsReview ? "1" : "")}|{string.Join("|", Data)}"; + return $"{DateTimeTicks}|{(int)EventType}|{(NeedsReview ? "1" : "")}|{string.Join("|", Data)}"; } private string _buildMessage() diff --git a/Core/Models/User.cs b/Core/Models/User.cs index 08ae9fc..0aee6a9 100644 --- a/Core/Models/User.cs +++ b/Core/Models/User.cs @@ -1,5 +1,4 @@ -using System; -using System.ComponentModel; +using System.ComponentModel; using Upsilon.Apps.Passkey.Core.Utils; using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Models; @@ -217,7 +216,7 @@ private void _timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e) if (_clipboardLeftTime == 0) { - Database.ClipboardManager.RemoveAllOccurence([.. Services.SelectMany(x => x.Accounts).SelectMany(x => x.Passwords.Values)]); + _ = Database.ClipboardManager.RemoveAllOccurence([.. Services.SelectMany(x => x.Accounts).SelectMany(x => x.Passwords.Values)]); _clipboardLeftTime = CleaningClipboardTimeout; } } diff --git a/Core/Utils/FileLocker.cs b/Core/Utils/FileLocker.cs index 89ed1da..d31768e 100644 --- a/Core/Utils/FileLocker.cs +++ b/Core/Utils/FileLocker.cs @@ -140,10 +140,9 @@ private string _readContent(string fileEntry, string[] passkeys) using Stream stream = zipEntry.Open(); using StreamReader reader = new(stream, Encoding.UTF8); - if (passkeys.Length != 0) - content = _cryptographicCenter.DecryptSymmetrically(_decompressString(reader.ReadToEnd()), passkeys); - else - content = _decompressString(reader.ReadToEnd()); + content = passkeys.Length != 0 + ? _cryptographicCenter.DecryptSymmetrically(_decompressString(reader.ReadToEnd()), passkeys) + : _decompressString(reader.ReadToEnd()); } Lock(); diff --git a/Core/Utils/LogCenter.cs b/Core/Utils/LogCenter.cs index 38aa2ee..6990bd0 100644 --- a/Core/Utils/LogCenter.cs +++ b/Core/Utils/LogCenter.cs @@ -1,5 +1,4 @@ -using System.Text.Json.Serialization; -using Upsilon.Apps.Passkey.Core.Models; +using Upsilon.Apps.Passkey.Core.Models; using Upsilon.Apps.Passkey.Interfaces.Enums; using Upsilon.Apps.Passkey.Interfaces.Models; From 652d26760de0ece5bedef6dbdd90779ad44fcad5 Mon Sep 17 00:00:00 2001 From: Yassin Lokhat Date: Fri, 19 Dec 2025 10:12:59 +0300 Subject: [PATCH 8/9] Working on Logs - Part 4 --- Core/Models/Database.cs | 19 +------- Core/Models/Service.cs | 20 +------- Core/Models/User.cs | 19 +++++--- UnitTests/Models/AccountUnitTests.cs | 32 ++++++------- UnitTests/Models/DatabaseUnitTests.cs | 6 +-- UnitTests/Models/ServiceUnitTests.cs | 12 ++--- UnitTests/Models/UserUnitTests.cs | 66 +++++++++++++-------------- 7 files changed, 73 insertions(+), 101 deletions(-) diff --git a/Core/Models/Database.cs b/Core/Models/Database.cs index 8029855..a11dcf7 100644 --- a/Core/Models/Database.cs +++ b/Core/Models/Database.cs @@ -279,7 +279,7 @@ public static IDatabase Create(ICryptographyCenter cryptographicCenter, { Database = database, PrivateKey = privateKey, - ItemId = cryptographicCenter.GetHash(username), + ItemId = "U" + cryptographicCenter.GetHash(username), Username = username, Passkeys = [.. passkeys], }; @@ -453,22 +453,7 @@ private Warning[] _lookAtLogWarnings() if (User is null) throw new NullReferenceException(nameof(User)); if (Logs.Logs is null) throw new NullReferenceException(nameof(Logs.Logs)); - List logs = [.. Logs.Logs.Cast()]; - - //for (int i = 0; i < logs.Count && logs[i].EventType != LogEventType.UserLoggedIn; i++) - //{ - // if (!logs[i].NeedsReview - // || (logs[i].EventType != LogEventType.MergeAndSaveThenRemoveAutoSaveFile - // && logs[i].EventType != LogEventType.MergeWithoutSavingAndKeepAutoSaveFile - // && logs[i].EventType != LogEventType.DontMergeAndRemoveAutoSaveFile - // && logs[i].EventType != LogEventType.DontMergeAndKeepAutoSaveFile)) - // { - // logs.RemoveAt(i); - // i--; - // } - //} - - return [new Warning([.. logs.Where(x => x.NeedsReview)])]; + return [new Warning([.. Logs.Logs.Where(x => x.NeedsReview).Cast()])]; } private Warning[] _lookAtPasswordUpdateReminderWarnings() diff --git a/Core/Models/Service.cs b/Core/Models/Service.cs index 6fa6c90..02b86ef 100644 --- a/Core/Models/Service.cs +++ b/Core/Models/Service.cs @@ -90,7 +90,7 @@ public IAccount AddAccount(IEnumerable identifiers) void IService.DeleteAccount(IAccount account) { Account accountToRemove = Accounts.FirstOrDefault(x => x.ItemId == account.ItemId) - ?? throw new KeyNotFoundException($"The '{account.ItemId}' account was not found into the '{ItemId}' service"); + ?? throw new KeyNotFoundException($"The {account}' was not found into the {this}'s accounts list"); _ = Accounts.Remove(Database.AutoSave.DeleteValue(ItemId, readableValue: accountToRemove.ToString(), needsReview: true, accountToRemove)); } @@ -122,24 +122,6 @@ internal User User public string Notes { get; set; } = string.Empty; public void Apply(Change change) - { - switch (change.ItemId.Length / Database.CryptographyCenter.HashLength) - { - case 2: - _apply(change); - break; - case 3: - Account account = Accounts.FirstOrDefault(x => change.ItemId.StartsWith(x.ItemId)) - ?? throw new KeyNotFoundException($"The '{change.ItemId}' account was not found into the '{ItemId}' service"); - - account.Apply(change); - break; - default: - throw new InvalidDataException("ItemId not valid"); - } - } - - private void _apply(Change change) { switch (change.ActionType) { diff --git a/Core/Models/User.cs b/Core/Models/User.cs index 0aee6a9..109ea17 100644 --- a/Core/Models/User.cs +++ b/Core/Models/User.cs @@ -138,7 +138,7 @@ IService IUser.AddService(string serviceName) void IUser.DeleteService(IService service) { Service serviceToRemove = Services.FirstOrDefault(x => x.ItemId == service.ItemId) - ?? throw new KeyNotFoundException($"The '{service.ItemId}' service was not found into the '{ItemId}' user"); + ?? throw new KeyNotFoundException($"The {service} was not found into the {this}'s services list"); _ = Services.Remove(Database.AutoSave.DeleteValue(ItemId, readableValue: serviceToRemove.ToString(), needsReview: true, value: serviceToRemove)); } @@ -230,18 +230,23 @@ public void ResetTimer() public void Apply(Change change) { - switch (change.ItemId.Length / Database.CryptographyCenter.HashLength) + switch (change.ItemId[0]) { - case 1: + case 'U': _apply(change); break; - case 2: - case 3: - Service service = Services.FirstOrDefault(x => change.ItemId.StartsWith(x.ItemId)) - ?? throw new KeyNotFoundException($"The '{change.ItemId[..(2 * Database.CryptographyCenter.HashLength)]}' service was not found into the '{ItemId}' user"); + case 'S': + Service service = Services.FirstOrDefault(x => change.ItemId == x.ItemId) + ?? throw new KeyNotFoundException($"The Service '{change.ItemId}' was not found into the {this}'s services list"); service.Apply(change); break; + case 'A': + Account account = Services.SelectMany(x => x.Accounts).FirstOrDefault(x => change.ItemId == x.ItemId) + ?? throw new KeyNotFoundException($"The Account {change.ItemId}' was not found into the {this}'s accounts list"); + + account.Apply(change); + break; default: throw new InvalidDataException("ItemId not valid"); } diff --git a/UnitTests/Models/AccountUnitTests.cs b/UnitTests/Models/AccountUnitTests.cs index a8ffe6d..6fed204 100644 --- a/UnitTests/Models/AccountUnitTests.cs +++ b/UnitTests/Models/AccountUnitTests.cs @@ -54,23 +54,23 @@ public void Case01_AddAccountUpdateSaved() // When account.Label = newAccountLabel; account.Label = newAccountLabel; - expectedLogs.Push($"Information : {account}'s label has been set to {newAccountLabel}"); + expectedLogs.Push($"Information : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)})'s label has been set to {newAccountLabel}"); account.Identifiers = newIdentifiers; account.Identifiers = newIdentifiers; - expectedLogs.Push($"Warning : Account {account}'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); - expectedLogWarnings.Push($"Warning : Account {account}'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); + expectedLogs.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", oldIdentifiers)})'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); + expectedLogWarnings.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", oldIdentifiers)})'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); account.Password = newPassword; account.Password = newPassword; - expectedLogs.Push($"Warning : Account {account}'s password has been updated"); - expectedLogWarnings.Push($"Warning : Account {account}'s password has been updated"); + expectedLogs.Push($"Warning : {account}'s password has been updated"); + expectedLogWarnings.Push($"Warning : {account}'s password has been updated"); account.Notes = notes; account.Notes = notes; - expectedLogs.Push($"Information : Account {account}'s notes has been set to {notes}"); + expectedLogs.Push($"Information : {account}'s notes has been set to {notes}"); account.PasswordUpdateReminderDelay = passwordUpdateReminderDelay; - expectedLogs.Push($"Information : Account {account}'s password update reminder delay has been set to {passwordUpdateReminderDelay}"); + expectedLogs.Push($"Information : {account}'s password update reminder delay has been set to {passwordUpdateReminderDelay}"); account.Options = options; account.Options = options; - expectedLogs.Push($"Information : Account {account}'s options has been set to {options}"); + expectedLogs.Push($"Information : {account}'s options has been set to {options}"); // Then databaseCreated.User.HasChanged().Should().BeTrue(); @@ -161,23 +161,23 @@ public void Case02_AddAccountUpdateAutoSave() // When account.Label = newAccountLabel; account.Label = newAccountLabel; - expectedLogs.Push($"Information : {account}'s label has been set to {newAccountLabel}"); + expectedLogs.Push($"Information : Account {oldAccountLabel} ({string.Join(", ", oldIdentifiers)})'s label has been set to {newAccountLabel}"); account.Identifiers = newIdentifiers; account.Identifiers = newIdentifiers; - expectedLogs.Push($"Warning : Account {account}'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); - expectedLogWarnings.Push($"Warning : Account {account}'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); + expectedLogs.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", oldIdentifiers)})'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); + expectedLogWarnings.Push($"Warning : Account {newAccountLabel} ({string.Join(", ", oldIdentifiers)})'s identifiers has been set to ({string.Join(", ", newIdentifiers)})"); account.Password = newPassword; account.Password = newPassword; - expectedLogs.Push($"Warning : Account {account}'s password has been updated"); - expectedLogWarnings.Push($"Warning : Account {account}'s password has been updated"); + expectedLogs.Push($"Warning : {account}'s password has been updated"); + expectedLogWarnings.Push($"Warning : {account}'s password has been updated"); account.Notes = notes; account.Notes = notes; - expectedLogs.Push($"Information : Account {account}'s notes has been set to {notes}"); + expectedLogs.Push($"Information : {account}'s notes has been set to {notes}"); account.PasswordUpdateReminderDelay = passwordUpdateReminderDelay; - expectedLogs.Push($"Information : Account {account}'s password update reminder delay has been set to {passwordUpdateReminderDelay}"); + expectedLogs.Push($"Information : {account}'s password update reminder delay has been set to {passwordUpdateReminderDelay}"); account.Options = options; account.Options = options; - expectedLogs.Push($"Information : Account {account}'s options has been set to {options}"); + expectedLogs.Push($"Information : {account}'s options has been set to {options}"); databaseCreated.Close(); expectedLogs.Push($"Warning : User {username} logged out without saving"); diff --git a/UnitTests/Models/DatabaseUnitTests.cs b/UnitTests/Models/DatabaseUnitTests.cs index c00cd5f..2946eb8 100644 --- a/UnitTests/Models/DatabaseUnitTests.cs +++ b/UnitTests/Models/DatabaseUnitTests.cs @@ -82,7 +82,7 @@ public void Case01_DatabaseCreationOpenDelete() // When IDatabase databaseCreated = UnitTestsHelper.CreateTestDatabase(passkeys); - expectedLogs.Push($"Information : User {username}'s database created"); + expectedLogs.Push($"Information : {databaseCreated.User}'s database created"); // Then _ = databaseCreated.DatabaseFile.Should().Be(databaseFile); @@ -105,8 +105,8 @@ public void Case01_DatabaseCreationOpenDelete() // When IDatabase databaseLoaded = UnitTestsHelper.OpenTestDatabase(passkeys, out _); - expectedLogs.Push($"Information : User {username}'s database opened"); - expectedLogs.Push($"Information : User {username} logged in"); + expectedLogs.Push($"Information : {databaseLoaded.User}'s database opened"); + expectedLogs.Push($"Information : {databaseLoaded.User} logged in"); // Then _ = databaseLoaded.Should().NotBeNull(); diff --git a/UnitTests/Models/ServiceUnitTests.cs b/UnitTests/Models/ServiceUnitTests.cs index cbc46e2..2f6f6dc 100644 --- a/UnitTests/Models/ServiceUnitTests.cs +++ b/UnitTests/Models/ServiceUnitTests.cs @@ -31,7 +31,7 @@ public void Case01_AddServiceUpdateSaved() // When IService service = databaseCreated.User.AddService(oldServiceName); - expectedLogs.Push($"Information : Service {oldServiceName} has been added to User {username}"); + expectedLogs.Push($"Information : {service} has been added to User {username}"); // Then databaseCreated.User.HasChanged().Should().BeTrue(); @@ -45,10 +45,10 @@ public void Case01_AddServiceUpdateSaved() expectedLogWarnings.Push($"Warning : Service {oldServiceName}'s service name has been set to {newServiceName}"); service.Url = url; service.Url = url; - expectedLogs.Push($"Information : Service {newServiceName}'s url has been set to {url}"); + expectedLogs.Push($"Information : {service}'s url has been set to {url}"); service.Notes = notes; service.Notes = notes; - expectedLogs.Push($"Information : Service {newServiceName}'s notes has been set to {notes}"); + expectedLogs.Push($"Information : {service}'s notes has been set to {notes}"); // Then databaseCreated.User.HasChanged().Should().BeTrue(); @@ -109,7 +109,7 @@ public void Case02_AddServiceUpdateAutoSave() // When IService service = databaseCreated.User.AddService(oldServiceName); - expectedLogs.Push($"Information : Service {oldServiceName} has been added to User {username}"); + expectedLogs.Push($"Information : {service} has been added to User {username}"); // Then _ = databaseCreated.User.Services.Length.Should().Be(1); @@ -121,10 +121,10 @@ public void Case02_AddServiceUpdateAutoSave() expectedLogWarnings.Push($"Warning : Service {oldServiceName}'s service name has been set to {newServiceName}"); service.Url = url; service.Url = url; - expectedLogs.Push($"Information : Service {newServiceName}'s url has been set to {url}"); + expectedLogs.Push($"Information : {service}'s url has been set to {url}"); service.Notes = notes; service.Notes = notes; - expectedLogs.Push($"Information : Service {newServiceName}'s notes has been set to {notes}"); + expectedLogs.Push($"Information : {service}'s notes has been set to {notes}"); databaseCreated.Close(); expectedLogs.Push($"Warning : User {username} logged out without saving"); diff --git a/UnitTests/Models/UserUnitTests.cs b/UnitTests/Models/UserUnitTests.cs index 3249a20..7563e4e 100644 --- a/UnitTests/Models/UserUnitTests.cs +++ b/UnitTests/Models/UserUnitTests.cs @@ -76,24 +76,24 @@ public void Case02_UserUpdateThenSaved() // When databaseCreated.User.Username = newUsername; databaseCreated.User.Username = newUsername; - expectedLogs.Push($"Warning : User {oldUsername}'s username has been set to {newUsername}"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s username has been set to {newUsername}"); + expectedLogs.Push($"Warning : {databaseCreated.User}'s username has been set to {newUsername}"); + expectedLogWarnings.Push($"Warning : {databaseCreated.User}'s username has been set to {newUsername}"); databaseCreated.User.Passkeys = newPasskeys; databaseCreated.User.Passkeys = newPasskeys; - expectedLogs.Push($"Warning : User {oldUsername}'s passkeys has been updated"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s passkeys has been updated"); + expectedLogs.Push($"Warning : {databaseCreated.User}'s passkeys has been updated"); + expectedLogWarnings.Push($"Warning : {databaseCreated.User}'s passkeys has been updated"); databaseCreated.User.LogoutTimeout = logoutTimeout; databaseCreated.User.LogoutTimeout = logoutTimeout; - expectedLogs.Push($"Information : User {oldUsername}'s logout timeout has been set to {logoutTimeout}"); + expectedLogs.Push($"Information : {databaseCreated.User}'s logout timeout has been set to {logoutTimeout}"); databaseCreated.User.CleaningClipboardTimeout = cleaningClipboardTimeout; databaseCreated.User.CleaningClipboardTimeout = cleaningClipboardTimeout; - expectedLogs.Push($"Information : User {oldUsername}'s cleaning clipboard timeout has been set to {cleaningClipboardTimeout}"); + expectedLogs.Push($"Information : {databaseCreated.User}'s cleaning clipboard timeout has been set to {cleaningClipboardTimeout}"); databaseCreated.User.WarningsToNotify = WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning; databaseCreated.User.WarningsToNotify = WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning; - expectedLogs.Push($"Warning : User {oldUsername}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); + expectedLogs.Push($"Warning : {databaseCreated.User}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); + expectedLogWarnings.Push($"Warning : {databaseCreated.User}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); databaseCreated.Save(); - expectedLogs.Push($"Information : User {newUsername}'s database saved"); + expectedLogs.Push($"Information : {databaseCreated.User}'s database saved"); databaseCreated.Close(); expectedLogs.Push($"Information : User {newUsername} logged out"); expectedLogs.Push($"Information : User {newUsername}'s database closed"); @@ -108,7 +108,7 @@ public void Case02_UserUpdateThenSaved() { _ = databaseLoaded.Login(passkey); } - expectedLogs.Push($"Information : User {newUsername} logged in"); + expectedLogs.Push($"Information : {databaseLoaded.User} logged in"); // Then _ = databaseLoaded.User.Should().NotBeNull(); @@ -151,22 +151,22 @@ public void Case03_UserUpdateButNotSaved_CaseMergeAndSave() // When databaseCreated.User.Username = newUsername; databaseCreated.User.Username = newUsername; - expectedLogs.Push($"Warning : User {oldUsername}'s username has been set to {newUsername}"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s username has been set to {newUsername}"); + expectedLogs.Push($"Warning : {databaseCreated.User}'s username has been set to {newUsername}"); + expectedLogWarnings.Push($"Warning : {databaseCreated.User}'s username has been set to {newUsername}"); databaseCreated.User.Passkeys = newPasskeys; databaseCreated.User.Passkeys = newPasskeys; - expectedLogs.Push($"Warning : User {oldUsername}'s passkeys has been updated"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s passkeys has been updated"); + expectedLogs.Push($"Warning : {databaseCreated.User}'s passkeys has been updated"); + expectedLogWarnings.Push($"Warning : {databaseCreated.User}'s passkeys has been updated"); databaseCreated.User.LogoutTimeout = logoutTimeout; databaseCreated.User.LogoutTimeout = logoutTimeout; - expectedLogs.Push($"Information : User {oldUsername}'s logout timeout has been set to {logoutTimeout}"); + expectedLogs.Push($"Information : {databaseCreated.User}'s logout timeout has been set to {logoutTimeout}"); databaseCreated.User.CleaningClipboardTimeout = cleaningClipboardTimeout; databaseCreated.User.CleaningClipboardTimeout = cleaningClipboardTimeout; - expectedLogs.Push($"Information : User {oldUsername}'s cleaning clipboard timeout has been set to {cleaningClipboardTimeout}"); + expectedLogs.Push($"Information : {databaseCreated.User}'s cleaning clipboard timeout has been set to {cleaningClipboardTimeout}"); databaseCreated.User.WarningsToNotify = WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning; databaseCreated.User.WarningsToNotify = WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning; - expectedLogs.Push($"Warning : User {oldUsername}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); + expectedLogs.Push($"Warning : {databaseCreated.User}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); + expectedLogWarnings.Push($"Warning : {databaseCreated.User}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); databaseCreated.Close(); expectedLogs.Push($"Warning : User {oldUsername} logged out without saving"); @@ -175,8 +175,8 @@ public void Case03_UserUpdateButNotSaved_CaseMergeAndSave() IDatabase databaseLoaded = UnitTestsHelper.OpenTestDatabase(oldPasskeys, out IWarning[] warnings, AutoSaveMergeBehavior.MergeAndSaveThenRemoveAutoSaveFile); expectedLogs.Push($"Information : User {oldUsername}'s database opened"); expectedLogs.Push($"Information : User {oldUsername} logged in"); - expectedLogs.Push($"Warning : User {oldUsername}'s autosave merged and saved"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s autosave merged and saved"); + expectedLogs.Push($"Warning : {databaseLoaded.User}'s autosave merged and saved"); + expectedLogWarnings.Push($"Warning : {databaseLoaded.User}'s autosave merged and saved"); // Then _ = databaseLoaded.User.HasChanged().Should().BeFalse(); @@ -203,7 +203,7 @@ public void Case03_UserUpdateButNotSaved_CaseMergeAndSave() { _ = databaseLoaded.Login(passkey); } - expectedLogs.Push($"Information : User {newUsername} logged in"); + expectedLogs.Push($"Information : {databaseLoaded.User} logged in"); // Then _ = databaseLoaded.User.Username.Should().Be(newUsername); @@ -246,22 +246,22 @@ public void Case04_UserUpdateButNotSaved_CaseMergeWithoutSaving() // When databaseCreated.User.Username = newUsername; databaseCreated.User.Username = newUsername; - expectedLogs.Push($"Warning : User {oldUsername}'s username has been set to {newUsername}"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s username has been set to {newUsername}"); + expectedLogs.Push($"Warning : {databaseCreated.User}'s username has been set to {newUsername}"); + expectedLogWarnings.Push($"Warning : {databaseCreated.User}'s username has been set to {newUsername}"); databaseCreated.User.Passkeys = newPasskeys; databaseCreated.User.Passkeys = newPasskeys; - expectedLogs.Push($"Warning : User {oldUsername}'s passkeys has been updated"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s passkeys has been updated"); + expectedLogs.Push($"Warning : {databaseCreated.User}'s passkeys has been updated"); + expectedLogWarnings.Push($"Warning : {databaseCreated.User}'s passkeys has been updated"); databaseCreated.User.LogoutTimeout = logoutTimeout; databaseCreated.User.LogoutTimeout = logoutTimeout; - expectedLogs.Push($"Information : User {oldUsername}'s logout timeout has been set to {logoutTimeout}"); + expectedLogs.Push($"Information : {databaseCreated.User}'s logout timeout has been set to {logoutTimeout}"); databaseCreated.User.CleaningClipboardTimeout = cleaningClipboardTimeout; databaseCreated.User.CleaningClipboardTimeout = cleaningClipboardTimeout; - expectedLogs.Push($"Information : User {oldUsername}'s cleaning clipboard timeout has been set to {cleaningClipboardTimeout}"); + expectedLogs.Push($"Information : {databaseCreated.User}'s cleaning clipboard timeout has been set to {cleaningClipboardTimeout}"); databaseCreated.User.WarningsToNotify = WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning; databaseCreated.User.WarningsToNotify = WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning; - expectedLogs.Push($"Warning : User {oldUsername}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); + expectedLogs.Push($"Warning : {databaseCreated.User}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); + expectedLogWarnings.Push($"Warning : {databaseCreated.User}'s warnings to notify has been set to {WarningType.DuplicatedPasswordsWarning | WarningType.PasswordUpdateReminderWarning}"); databaseCreated.Close(); expectedLogs.Push($"Warning : User {oldUsername} logged out without saving"); @@ -270,8 +270,8 @@ public void Case04_UserUpdateButNotSaved_CaseMergeWithoutSaving() IDatabase databaseLoaded = UnitTestsHelper.OpenTestDatabase(oldPasskeys, out IWarning[] warnings, AutoSaveMergeBehavior.MergeWithoutSavingAndKeepAutoSaveFile); expectedLogs.Push($"Information : User {oldUsername}'s database opened"); expectedLogs.Push($"Information : User {oldUsername} logged in"); - expectedLogs.Push($"Warning : User {oldUsername}'s autosave merged without saving"); - expectedLogWarnings.Push($"Warning : User {oldUsername}'s autosave merged without saving"); + expectedLogs.Push($"Warning : {databaseLoaded.User}'s autosave merged without saving"); + expectedLogWarnings.Push($"Warning : {databaseLoaded.User}'s autosave merged without saving"); // Then _ = databaseLoaded.User.HasChanged().Should().BeTrue(); @@ -288,7 +288,7 @@ public void Case04_UserUpdateButNotSaved_CaseMergeWithoutSaving() // When databaseLoaded.Save(); - expectedLogs.Push($"Information : User {newUsername}'s database saved"); + expectedLogs.Push($"Information : {databaseLoaded.User}'s database saved"); databaseLoaded.Close(); expectedLogs.Push($"Information : User {newUsername} logged out"); expectedLogs.Push($"Information : User {newUsername}'s database closed"); @@ -304,7 +304,7 @@ public void Case04_UserUpdateButNotSaved_CaseMergeWithoutSaving() { _ = databaseLoaded.Login(passkey); } - expectedLogs.Push($"Information : User {newUsername} logged in"); + expectedLogs.Push($"Information : {databaseLoaded.User} logged in"); // Then _ = databaseLoaded.User.Username.Should().Be(newUsername); From dbbe15039643ebbfe9e98cd520d907896780099c Mon Sep 17 00:00:00 2001 From: Yassin Lokhat Date: Fri, 19 Dec 2025 10:31:55 +0300 Subject: [PATCH 9/9] Removing GPL V3 Licence --- LICENCE | 674 -------------------------------------------------------- 1 file changed, 674 deletions(-) delete mode 100644 LICENCE diff --git a/LICENCE b/LICENCE deleted file mode 100644 index f288702..0000000 --- a/LICENCE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -.