mirror of
https://github.com/wismna/ModernKeePass.git
synced 2025-10-03 15:40:18 -04:00
WIP Clean Architecture
Windows 8.1 App Uses keepasslib v2.44 (temporarily)
This commit is contained in:
25
ModernKeePass.Infrastructure/DependencyInjection.cs
Normal file
25
ModernKeePass.Infrastructure/DependencyInjection.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
using Autofac;
|
||||
using AutoMapper;
|
||||
using ModernKeePass.Application.Common.Interfaces;
|
||||
using ModernKeePass.Infrastructure.KeePass;
|
||||
using ModernKeePass.Infrastructure.UWP;
|
||||
|
||||
namespace ModernKeePass.Infrastructure
|
||||
{
|
||||
public class DependencyInjection: Module
|
||||
{
|
||||
protected override void Load(ContainerBuilder builder)
|
||||
{
|
||||
builder.RegisterType<KeePassDatabaseClient>().As<IDatabaseProxy>().SingleInstance();
|
||||
builder.RegisterType<KeePassPasswordClient>().As<IPasswordProxy>().SingleInstance();
|
||||
builder.RegisterType<KeePassCryptographyClient>().As<ICryptographyClient>();
|
||||
builder.RegisterType<UwpSettingsClient>().As<ISettingsProxy>();
|
||||
builder.RegisterType<UwpResourceClient>().As<IResourceProxy>();
|
||||
builder.RegisterType<UwpRecentFilesClient>().As<IRecentProxy>();
|
||||
builder.RegisterType<StorageFileClient>().As<IFileProxy>();
|
||||
|
||||
// Register Automapper profiles
|
||||
builder.RegisterType<EntryMappingProfile>().As<Profile>();
|
||||
}
|
||||
}
|
||||
}
|
39
ModernKeePass.Infrastructure/File/CsvImportFormat.cs
Normal file
39
ModernKeePass.Infrastructure/File/CsvImportFormat.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ModernKeePass.Application.Common.Interfaces;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.File
|
||||
{
|
||||
public class CsvImportFormat: IImportFormat
|
||||
{
|
||||
private readonly IFileProxy _fileService;
|
||||
private const bool HasHeaderRow = true;
|
||||
private const char Delimiter = ';';
|
||||
private const char LineDelimiter = '\n';
|
||||
|
||||
public CsvImportFormat(IFileProxy fileService)
|
||||
{
|
||||
_fileService = fileService;
|
||||
}
|
||||
|
||||
public async Task<List<Dictionary<string, string>>> Import(string path)
|
||||
{
|
||||
var parsedResult = new List<Dictionary<string, string>>();
|
||||
var content = await _fileService.OpenTextFile(path);
|
||||
foreach (var line in content)
|
||||
{
|
||||
var fields = line.Split(Delimiter);
|
||||
var recordItem = new Dictionary<string, string>();
|
||||
var i = 0;
|
||||
foreach (var field in fields)
|
||||
{
|
||||
recordItem.Add(i.ToString(), field);
|
||||
i++;
|
||||
}
|
||||
parsedResult.Add(recordItem);
|
||||
}
|
||||
|
||||
return parsedResult;
|
||||
}
|
||||
}
|
||||
}
|
76
ModernKeePass.Infrastructure/KeePass/EntryMappingProfile.cs
Normal file
76
ModernKeePass.Infrastructure/KeePass/EntryMappingProfile.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using AutoMapper;
|
||||
using ModernKeePass.Domain.Entities;
|
||||
using ModernKeePassLib;
|
||||
using ModernKeePassLib.Security;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.KeePass
|
||||
{
|
||||
public class EntryMappingProfile: Profile
|
||||
{
|
||||
public EntryMappingProfile()
|
||||
{
|
||||
FromModelToDto();
|
||||
FromDtoToModel();
|
||||
}
|
||||
|
||||
private void FromDtoToModel()
|
||||
{
|
||||
CreateMap<PwEntry, EntryEntity>()
|
||||
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Uuid.ToHexString()))
|
||||
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => GetEntryValue(src, PwDefs.TitleField)))
|
||||
.ForMember(dest => dest.UserName, opt => opt.MapFrom(src => GetEntryValue(src, PwDefs.UserNameField)))
|
||||
.ForMember(dest => dest.Password, opt => opt.MapFrom(src => GetEntryValue(src, PwDefs.PasswordField)))
|
||||
.ForMember(dest => dest.Url, opt =>
|
||||
{
|
||||
opt.PreCondition(src => Uri.TryCreate(GetEntryValue(src, PwDefs.UrlField), UriKind.Absolute, out _));
|
||||
opt.MapFrom(src => new Uri(GetEntryValue(src, PwDefs.UrlField)));
|
||||
})
|
||||
.ForMember(dest => dest.Notes, opt => opt.MapFrom(src => GetEntryValue(src, PwDefs.NotesField)))
|
||||
.ForMember(dest => dest.ForegroundColor, opt => opt.MapFrom(src => src.ForegroundColor))
|
||||
.ForMember(dest => dest.BackgroundColor, opt => opt.MapFrom(src => src.BackgroundColor))
|
||||
.ForMember(dest => dest.ExpirationDate, opt => opt.MapFrom(src => new DateTimeOffset(src.ExpiryTime)))
|
||||
.ForMember(dest => dest.HasExpirationDate, opt => opt.MapFrom(src => src.Expires))
|
||||
.ForMember(dest => dest.Icon, opt => opt.MapFrom(src => IconMapper.MapPwIconToIcon(src.IconId)))
|
||||
.ForMember(dest => dest.AdditionalFields, opt => opt.MapFrom(src =>
|
||||
src.Strings.Where(s => !PwDefs.GetStandardFields().Contains(s.Key)).ToDictionary(s => s.Key, s => GetEntryValue(src, s.Key))))
|
||||
.ForMember(dest => dest.LastModificationDate, opt => opt.MapFrom(src => new DateTimeOffset(src.LastModificationTime)));
|
||||
}
|
||||
|
||||
private void FromModelToDto()
|
||||
{
|
||||
CreateMap<EntryEntity, PwEntry>().ConvertUsing<EntryToPwEntryDictionaryConverter>();
|
||||
}
|
||||
|
||||
private string GetEntryValue(PwEntry entry, string key) => entry.Strings.GetSafe(key).ReadString();
|
||||
}
|
||||
|
||||
public class EntryToPwEntryDictionaryConverter : ITypeConverter<EntryEntity, PwEntry>
|
||||
{
|
||||
public PwEntry Convert(EntryEntity source, PwEntry destination, ResolutionContext context)
|
||||
{
|
||||
//destination.Uuid = new PwUuid(System.Convert.FromBase64String(source.Id));
|
||||
destination.ExpiryTime = source.ExpirationDate.DateTime;
|
||||
destination.Expires = source.HasExpirationDate;
|
||||
destination.LastModificationTime = source.LastModificationDate.DateTime;
|
||||
destination.BackgroundColor = source.BackgroundColor;
|
||||
destination.ForegroundColor = source.ForegroundColor;
|
||||
destination.IconId = IconMapper.MapIconToPwIcon(source.Icon);
|
||||
SetEntryValue(destination, PwDefs.TitleField, source.Name);
|
||||
SetEntryValue(destination, PwDefs.UserNameField, source.UserName);
|
||||
SetEntryValue(destination, PwDefs.PasswordField, source.Password);
|
||||
SetEntryValue(destination, PwDefs.UrlField, source.Url?.ToString());
|
||||
SetEntryValue(destination, PwDefs.NotesField, source.Notes);
|
||||
foreach (var additionalField in source.AdditionalFields)
|
||||
{
|
||||
SetEntryValue(destination, additionalField.Key, additionalField.Value);
|
||||
}
|
||||
return destination;
|
||||
}
|
||||
private void SetEntryValue(PwEntry entry, string key, string newValue)
|
||||
{
|
||||
if (newValue != null) entry.Strings.Set(key, new ProtectedString(true, newValue));
|
||||
}
|
||||
}
|
||||
}
|
126
ModernKeePass.Infrastructure/KeePass/IconMapper.cs
Normal file
126
ModernKeePass.Infrastructure/KeePass/IconMapper.cs
Normal file
@@ -0,0 +1,126 @@
|
||||
using ModernKeePass.Domain.Enums;
|
||||
using ModernKeePassLib;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.KeePass
|
||||
{
|
||||
public static class IconMapper
|
||||
{
|
||||
public static Icon MapPwIconToIcon(PwIcon value)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case PwIcon.Key: return Icon.Permissions;
|
||||
case PwIcon.WorldSocket:
|
||||
case PwIcon.World: return Icon.World;
|
||||
case PwIcon.Warning: return Icon.Important;
|
||||
case PwIcon.WorldComputer:
|
||||
case PwIcon.Drive:
|
||||
case PwIcon.DriveWindows:
|
||||
case PwIcon.NetworkServer: return Icon.MapDrive;
|
||||
case PwIcon.MarkedDirectory: return Icon.Map;
|
||||
case PwIcon.UserCommunication: return Icon.ContactInfo;
|
||||
case PwIcon.Parts: return Icon.ViewAll;
|
||||
case PwIcon.Notepad: return Icon.Document;
|
||||
case PwIcon.Identity: return Icon.Contact;
|
||||
case PwIcon.PaperReady: return Icon.SyncFolder;
|
||||
case PwIcon.Digicam: return Icon.Camera;
|
||||
case PwIcon.IRCommunication: return Icon.View;
|
||||
case PwIcon.Energy: return Icon.ZeroBars;
|
||||
case PwIcon.Scanner: return Icon.Scan;
|
||||
case PwIcon.CDRom: return Icon.Rotate;
|
||||
case PwIcon.Monitor: return Icon.Caption;
|
||||
case PwIcon.EMailBox:
|
||||
case PwIcon.EMail: return Icon.Mail;
|
||||
case PwIcon.Configuration: return Icon.Setting;
|
||||
case PwIcon.ClipboardReady: return Icon.Paste;
|
||||
case PwIcon.PaperNew: return Icon.Page;
|
||||
case PwIcon.Screen: return Icon.GoToStart;
|
||||
case PwIcon.EnergyCareful: return Icon.FourBars;
|
||||
case PwIcon.Disk: return Icon.Save;
|
||||
case PwIcon.Console: return Icon.SlideShow;
|
||||
case PwIcon.Printer: return Icon.Scan;
|
||||
case PwIcon.ProgramIcons: return Icon.GoToStart;
|
||||
case PwIcon.Settings:
|
||||
case PwIcon.Tool: return Icon.Repair;
|
||||
case PwIcon.Archive: return Icon.Crop;
|
||||
case PwIcon.Count: return Icon.Calculator;
|
||||
case PwIcon.Clock: return Icon.Clock;
|
||||
case PwIcon.EMailSearch: return Icon.Find;
|
||||
case PwIcon.PaperFlag: return Icon.Flag;
|
||||
case PwIcon.TrashBin: return Icon.Delete;
|
||||
case PwIcon.Expired: return Icon.ReportHacked;
|
||||
case PwIcon.Info: return Icon.Help;
|
||||
case PwIcon.Folder:
|
||||
case PwIcon.FolderOpen:
|
||||
case PwIcon.FolderPackage: return Icon.Folder;
|
||||
case PwIcon.PaperLocked: return Icon.ProtectedDocument;
|
||||
case PwIcon.Checked: return Icon.Accept;
|
||||
case PwIcon.Pen: return Icon.Edit;
|
||||
case PwIcon.Thumbnail: return Icon.BrowsePhotos;
|
||||
case PwIcon.Book: return Icon.Library;
|
||||
case PwIcon.List: return Icon.List;
|
||||
case PwIcon.UserKey: return Icon.ContactPresence;
|
||||
case PwIcon.Home: return Icon.Home;
|
||||
case PwIcon.Star: return Icon.OutlineStar;
|
||||
case PwIcon.Money: return Icon.Shop;
|
||||
case PwIcon.Certificate: return Icon.PreviewLink;
|
||||
case PwIcon.BlackBerry: return Icon.CellPhone;
|
||||
default: return Icon.Stop;
|
||||
}
|
||||
}
|
||||
|
||||
public static PwIcon MapIconToPwIcon(Icon value)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case Icon.Delete: return PwIcon.TrashBin;
|
||||
case Icon.Edit: return PwIcon.Pen;
|
||||
case Icon.Save: return PwIcon.Disk;
|
||||
case Icon.Cancel: return PwIcon.Expired;
|
||||
case Icon.Accept: return PwIcon.Checked;
|
||||
case Icon.Home: return PwIcon.Home;
|
||||
case Icon.Camera: return PwIcon.Digicam;
|
||||
case Icon.Setting: return PwIcon.Configuration;
|
||||
case Icon.Mail: return PwIcon.EMail;
|
||||
case Icon.Find: return PwIcon.EMailSearch;
|
||||
case Icon.Help: return PwIcon.Info;
|
||||
case Icon.Clock: return PwIcon.Clock;
|
||||
case Icon.Crop: return PwIcon.Archive;
|
||||
case Icon.World: return PwIcon.World;
|
||||
case Icon.Flag: return PwIcon.PaperFlag;
|
||||
case Icon.PreviewLink: return PwIcon.Certificate;
|
||||
case Icon.Document: return PwIcon.Notepad;
|
||||
case Icon.ProtectedDocument: return PwIcon.PaperLocked;
|
||||
case Icon.ContactInfo: return PwIcon.UserCommunication;
|
||||
case Icon.ViewAll: return PwIcon.Parts;
|
||||
case Icon.Rotate: return PwIcon.CDRom;
|
||||
case Icon.List: return PwIcon.List;
|
||||
case Icon.Shop: return PwIcon.Money;
|
||||
case Icon.BrowsePhotos: return PwIcon.Thumbnail;
|
||||
case Icon.Caption: return PwIcon.Monitor;
|
||||
case Icon.Repair: return PwIcon.Tool;
|
||||
case Icon.Page: return PwIcon.PaperNew;
|
||||
case Icon.Paste: return PwIcon.ClipboardReady;
|
||||
case Icon.Important: return PwIcon.Warning;
|
||||
case Icon.SlideShow: return PwIcon.Console;
|
||||
case Icon.MapDrive: return PwIcon.NetworkServer;
|
||||
case Icon.ContactPresence: return PwIcon.UserKey;
|
||||
case Icon.Contact: return PwIcon.Identity;
|
||||
case Icon.Folder: return PwIcon.Folder;
|
||||
case Icon.View: return PwIcon.IRCommunication;
|
||||
case Icon.Permissions: return PwIcon.Key;
|
||||
case Icon.Map: return PwIcon.MarkedDirectory;
|
||||
case Icon.CellPhone: return PwIcon.BlackBerry;
|
||||
case Icon.OutlineStar: return PwIcon.Star;
|
||||
case Icon.Calculator: return PwIcon.Count;
|
||||
case Icon.Library: return PwIcon.Book;
|
||||
case Icon.SyncFolder: return PwIcon.PaperReady;
|
||||
case Icon.GoToStart: return PwIcon.Screen;
|
||||
case Icon.ZeroBars: return PwIcon.Energy;
|
||||
case Icon.FourBars: return PwIcon.EnergyCareful;
|
||||
case Icon.Scan: return PwIcon.Scanner;
|
||||
default: return PwIcon.Key;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ModernKeePass.Application.Common.Interfaces;
|
||||
using ModernKeePass.Domain.Entities;
|
||||
using ModernKeePassLib;
|
||||
using ModernKeePassLib.Cryptography.Cipher;
|
||||
using ModernKeePassLib.Cryptography.KeyDerivation;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.KeePass
|
||||
{
|
||||
public class KeePassCryptographyClient: ICryptographyClient
|
||||
{
|
||||
public IEnumerable<BaseEntity> Ciphers
|
||||
{
|
||||
get
|
||||
{
|
||||
for (var inx = 0; inx < CipherPool.GlobalPool.EngineCount; inx++)
|
||||
{
|
||||
var cipher = CipherPool.GlobalPool[inx];
|
||||
yield return new BaseEntity
|
||||
{
|
||||
Id = cipher.CipherUuid.ToHexString(),
|
||||
Name = cipher.DisplayName
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<BaseEntity> KeyDerivations => KdfPool.Engines.Select(e => new BaseEntity
|
||||
{
|
||||
Id = e.Uuid.ToHexString(),
|
||||
Name = e.Name
|
||||
});
|
||||
|
||||
public IEnumerable<string> CompressionAlgorithms => Enum.GetNames(typeof(PwCompressionAlgorithm)).Take((int) PwCompressionAlgorithm.Count);
|
||||
}
|
||||
}
|
266
ModernKeePass.Infrastructure/KeePass/KeePassDatabaseClient.cs
Normal file
266
ModernKeePass.Infrastructure/KeePass/KeePassDatabaseClient.cs
Normal file
@@ -0,0 +1,266 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using AutoMapper;
|
||||
using ModernKeePass.Application.Common.Interfaces;
|
||||
using ModernKeePass.Domain.Dtos;
|
||||
using ModernKeePass.Domain.Entities;
|
||||
using ModernKeePass.Domain.Exceptions;
|
||||
using ModernKeePassLib;
|
||||
using ModernKeePassLib.Cryptography.Cipher;
|
||||
using ModernKeePassLib.Cryptography.KeyDerivation;
|
||||
using ModernKeePassLib.Interfaces;
|
||||
using ModernKeePassLib.Keys;
|
||||
using ModernKeePassLib.Serialization;
|
||||
using ModernKeePassLib.Utility;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.KeePass
|
||||
{
|
||||
public class KeePassDatabaseClient: IDatabaseProxy
|
||||
{
|
||||
private readonly ISettingsProxy _settings;
|
||||
private readonly IFileProxy _fileService;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly PwDatabase _pwDatabase = new PwDatabase();
|
||||
private string _fileAccessToken;
|
||||
private CompositeKey _compositeKey;
|
||||
|
||||
public bool IsOpen => (_pwDatabase?.IsOpen).GetValueOrDefault();
|
||||
|
||||
public GroupEntity RecycleBin { get; set; }
|
||||
|
||||
public BaseEntity Cipher
|
||||
{
|
||||
get
|
||||
{
|
||||
var cipher = CipherPool.GlobalPool.GetCipher(_pwDatabase.DataCipherUuid);
|
||||
return new BaseEntity
|
||||
{
|
||||
Id = cipher.CipherUuid.ToHexString(),
|
||||
Name = cipher.DisplayName
|
||||
};
|
||||
}
|
||||
set => _pwDatabase.DataCipherUuid = BuildIdFromString(value.Id);
|
||||
}
|
||||
|
||||
public BaseEntity KeyDerivation
|
||||
{
|
||||
get
|
||||
{
|
||||
var keyDerivation = KdfPool.Engines.First(e => e.Uuid.Equals(_pwDatabase.KdfParameters.KdfUuid));
|
||||
return new BaseEntity
|
||||
{
|
||||
Id = keyDerivation.Uuid.ToHexString(),
|
||||
Name = keyDerivation.Name
|
||||
};
|
||||
}
|
||||
set => _pwDatabase.KdfParameters = KdfPool.Engines
|
||||
.FirstOrDefault(e => e.Uuid.Equals(BuildIdFromString(value.Name)))?.GetDefaultParameters();
|
||||
}
|
||||
|
||||
public string Compression
|
||||
{
|
||||
get => _pwDatabase.Compression.ToString("G");
|
||||
set => _pwDatabase.Compression = (PwCompressionAlgorithm)Enum.Parse(typeof(PwCompressionAlgorithm), value);
|
||||
}
|
||||
|
||||
public KeePassDatabaseClient(ISettingsProxy settings, IFileProxy fileService, IMapper mapper)
|
||||
{
|
||||
_settings = settings;
|
||||
_fileService = fileService;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<DatabaseEntity> Open(FileInfo fileInfo, Credentials credentials)
|
||||
{
|
||||
try
|
||||
{
|
||||
_compositeKey = await CreateCompositeKey(credentials);
|
||||
var ioConnection = await BuildConnectionInfo(fileInfo);
|
||||
|
||||
_pwDatabase.Open(ioConnection, _compositeKey, new NullStatusLogger());
|
||||
|
||||
_fileAccessToken = fileInfo.Path;
|
||||
|
||||
return new DatabaseEntity
|
||||
{
|
||||
RootGroupEntity = BuildHierarchy(_pwDatabase.RootGroup)
|
||||
};
|
||||
}
|
||||
catch (InvalidCompositeKeyException ex)
|
||||
{
|
||||
throw new ArgumentException(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<DatabaseEntity> Create(FileInfo fileInfo, Credentials credentials)
|
||||
{
|
||||
_compositeKey = await CreateCompositeKey(credentials);
|
||||
var ioConnection = await BuildConnectionInfo(fileInfo);
|
||||
|
||||
_pwDatabase.New(ioConnection, _compositeKey);
|
||||
|
||||
var fileFormat = _settings.GetSetting<string>("DefaultFileFormat");
|
||||
switch (fileFormat)
|
||||
{
|
||||
case "4":
|
||||
_pwDatabase.KdfParameters = KdfPool.Get("Argon2").GetDefaultParameters();
|
||||
break;
|
||||
}
|
||||
|
||||
_fileAccessToken = fileInfo.Path;
|
||||
|
||||
// TODO: create sample data depending on settings
|
||||
return new DatabaseEntity
|
||||
{
|
||||
RootGroupEntity = BuildHierarchy(_pwDatabase.RootGroup)
|
||||
};
|
||||
}
|
||||
|
||||
public async Task SaveDatabase()
|
||||
{
|
||||
if (!_pwDatabase.IsOpen) return;
|
||||
try
|
||||
{
|
||||
_pwDatabase.Save(new NullStatusLogger());
|
||||
await _fileService.WriteBinaryContentsToFile(_fileAccessToken, _pwDatabase.IOConnectionInfo.Bytes);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new SaveException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SaveDatabase(FileInfo fileInfo)
|
||||
{
|
||||
try
|
||||
{
|
||||
var newFileContents = await _fileService.OpenBinaryFile(fileInfo.Path);
|
||||
_pwDatabase.SaveAs(IOConnectionInfo.FromByteArray(newFileContents), true, new NullStatusLogger());
|
||||
await _fileService.WriteBinaryContentsToFile(fileInfo.Path, _pwDatabase.IOConnectionInfo.Bytes);
|
||||
|
||||
_fileService.ReleaseFile(_fileAccessToken);
|
||||
_fileAccessToken = fileInfo.Path;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new SaveException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void CloseDatabase()
|
||||
{
|
||||
_pwDatabase?.Close();
|
||||
_fileService.ReleaseFile(_fileAccessToken);
|
||||
}
|
||||
|
||||
public async Task AddEntry(GroupEntity parentGroupEntity, EntryEntity entry)
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
var parentPwGroup = _pwDatabase.RootGroup.FindGroup(BuildIdFromString(parentGroupEntity.Id), true);
|
||||
|
||||
var pwEntry = new PwEntry(true, true);
|
||||
_mapper.Map(entry, pwEntry);
|
||||
parentPwGroup.AddEntry(pwEntry, true);
|
||||
entry.Id = pwEntry.Uuid.ToHexString();
|
||||
});
|
||||
}
|
||||
public async Task AddGroup(GroupEntity parentGroupEntity, GroupEntity group)
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
var parentPwGroup = _pwDatabase.RootGroup.FindGroup(BuildIdFromString(parentGroupEntity.Id), true);
|
||||
|
||||
var pwGroup = new PwGroup(true, true)
|
||||
{
|
||||
Name = group.Name
|
||||
};
|
||||
parentPwGroup.AddGroup(pwGroup, true);
|
||||
group.Id = pwGroup.Uuid.ToHexString();
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public Task UpdateEntry(EntryEntity entry)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task UpdateGroup(GroupEntity group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task DeleteEntry(EntryEntity entry)
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
var pwEntry = _pwDatabase.RootGroup.FindEntry(BuildIdFromString(entry.Id), true);
|
||||
var id = pwEntry.Uuid;
|
||||
pwEntry.ParentGroup.Entries.Remove(pwEntry);
|
||||
|
||||
if (_pwDatabase.RecycleBinEnabled)
|
||||
{
|
||||
_pwDatabase.DeletedObjects.Add(new PwDeletedObject(id, DateTime.UtcNow));
|
||||
}
|
||||
});
|
||||
}
|
||||
public async Task DeleteGroup(GroupEntity group)
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
var pwGroup = _pwDatabase.RootGroup.FindGroup(BuildIdFromString(group.Id), true);
|
||||
var id = pwGroup.Uuid;
|
||||
pwGroup.ParentGroup.Groups.Remove(pwGroup);
|
||||
|
||||
if (_pwDatabase.RecycleBinEnabled)
|
||||
{
|
||||
_pwDatabase.DeletedObjects.Add(new PwDeletedObject(id, DateTime.UtcNow));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public async Task UpdateCredentials(Credentials credentials)
|
||||
{
|
||||
_pwDatabase.MasterKey = await CreateCompositeKey(credentials);
|
||||
}
|
||||
|
||||
private async Task<CompositeKey> CreateCompositeKey(Credentials credentials)
|
||||
{
|
||||
var compositeKey = new CompositeKey();
|
||||
if (!string.IsNullOrEmpty(credentials.Password)) compositeKey.AddUserKey(new KcpPassword(credentials.Password));
|
||||
if (!string.IsNullOrEmpty(credentials.KeyFilePath))
|
||||
{
|
||||
var kcpFileContents = await _fileService.OpenBinaryFile(credentials.KeyFilePath);
|
||||
compositeKey.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromByteArray(kcpFileContents)));
|
||||
}
|
||||
return compositeKey;
|
||||
}
|
||||
|
||||
private async Task<IOConnectionInfo> BuildConnectionInfo(FileInfo fileInfo)
|
||||
{
|
||||
var fileContents = await _fileService.OpenBinaryFile(fileInfo.Path);
|
||||
return IOConnectionInfo.FromByteArray(fileContents);
|
||||
}
|
||||
|
||||
private GroupEntity BuildHierarchy(PwGroup pwGroup)
|
||||
{
|
||||
// TODO: build entity hierarchy in an iterative way or implement lazy loading
|
||||
var group = new GroupEntity
|
||||
{
|
||||
Id = pwGroup.Uuid.ToHexString(),
|
||||
Name = pwGroup.Name,
|
||||
Icon = IconMapper.MapPwIconToIcon(pwGroup.IconId),
|
||||
Entries = pwGroup.Entries.Select(e => _mapper.Map<EntryEntity>(e)).ToList(),
|
||||
SubGroups = pwGroup.Groups.Select(BuildHierarchy).ToList()
|
||||
};
|
||||
return group;
|
||||
}
|
||||
|
||||
private PwUuid BuildIdFromString(string id)
|
||||
{
|
||||
return new PwUuid(MemUtil.HexStringToByteArray(id));
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,46 @@
|
||||
using ModernKeePass.Application.Common.Interfaces;
|
||||
using ModernKeePass.Domain.Dtos;
|
||||
using ModernKeePassLib.Cryptography;
|
||||
using ModernKeePassLib.Cryptography.PasswordGenerator;
|
||||
using ModernKeePassLib.Keys;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.KeePass
|
||||
{
|
||||
public class KeePassPasswordClient: IPasswordProxy
|
||||
{
|
||||
public string GeneratePassword(PasswordGenerationOptions options)
|
||||
{
|
||||
var pwProfile = new PwProfile
|
||||
{
|
||||
GeneratorType = PasswordGeneratorType.CharSet,
|
||||
Length = (uint)options.PasswordLength,
|
||||
CharSet = new PwCharSet()
|
||||
};
|
||||
|
||||
if (options.UpperCasePatternSelected) pwProfile.CharSet.Add(PwCharSet.UpperCase);
|
||||
if (options.LowerCasePatternSelected) pwProfile.CharSet.Add(PwCharSet.LowerCase);
|
||||
if (options.DigitsPatternSelected) pwProfile.CharSet.Add(PwCharSet.Digits);
|
||||
if (options.SpecialPatternSelected) pwProfile.CharSet.Add(PwCharSet.Special);
|
||||
if (options.MinusPatternSelected) pwProfile.CharSet.Add('-');
|
||||
if (options.UnderscorePatternSelected) pwProfile.CharSet.Add('_');
|
||||
if (options.SpacePatternSelected) pwProfile.CharSet.Add(' ');
|
||||
if (options.BracketsPatternSelected) pwProfile.CharSet.Add(PwCharSet.Brackets);
|
||||
|
||||
pwProfile.CharSet.Add(options.CustomChars);
|
||||
|
||||
PwGenerator.Generate(out var password, pwProfile, null, new CustomPwGeneratorPool());
|
||||
|
||||
return password.ReadString();
|
||||
}
|
||||
|
||||
public uint EstimatePasswordComplexity(string password)
|
||||
{
|
||||
return QualityEstimation.EstimatePasswordBits(password?.ToCharArray());
|
||||
}
|
||||
|
||||
public byte[] GenerateKeyFile(byte[] additionalEntropy)
|
||||
{
|
||||
return KcpKeyFile.Create(additionalEntropy);
|
||||
}
|
||||
}
|
||||
}
|
BIN
ModernKeePass.Infrastructure/Libs/Windows.winmd
Normal file
BIN
ModernKeePass.Infrastructure/Libs/Windows.winmd
Normal file
Binary file not shown.
@@ -0,0 +1,80 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{09577E4C-4899-45B9-BF80-1803D617CCAE}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>ModernKeePass.Infrastructure</RootNamespace>
|
||||
<AssemblyName>ModernKeePass.Infrastructure</AssemblyName>
|
||||
<DefaultLanguage>en-US</DefaultLanguage>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<TargetFrameworkProfile>
|
||||
</TargetFrameworkProfile>
|
||||
<TargetFrameworkVersion>v5.0</TargetFrameworkVersion>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- A reference to the entire .NET Framework is automatically included -->
|
||||
<None Include="Libs\Windows.winmd" />
|
||||
<None Include="project.json" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="DependencyInjection.cs" />
|
||||
<Compile Include="File\CsvImportFormat.cs" />
|
||||
<Compile Include="KeePass\EntryMappingProfile.cs" />
|
||||
<Compile Include="KeePass\IconMapper.cs" />
|
||||
<Compile Include="KeePass\KeePassCryptographyClient.cs" />
|
||||
<Compile Include="KeePass\KeePassDatabaseClient.cs" />
|
||||
<Compile Include="KeePass\KeePassPasswordClient.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="UWP\StorageFileClient.cs" />
|
||||
<Compile Include="UWP\UwpRecentFilesClient.cs" />
|
||||
<Compile Include="UWP\UwpResourceClient.cs" />
|
||||
<Compile Include="UWP\UwpSettingsClient.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ModernKeePass.Application\ModernKeePass.Application.csproj">
|
||||
<Project>{42353562-5e43-459c-8e3e-2f21e575261d}</Project>
|
||||
<Name>ModernKeePass.Application</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\ModernKeePass.Domain\ModernKeePass.Domain.csproj">
|
||||
<Project>{9a0759f1-9069-4841-99e3-3bec44e17356}</Project>
|
||||
<Name>ModernKeePass.Domain</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Windows, Version=255.255.255.255, Culture=neutral, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>Libs\Windows.winmd</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
30
ModernKeePass.Infrastructure/Properties/AssemblyInfo.cs
Normal file
30
ModernKeePass.Infrastructure/Properties/AssemblyInfo.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using System.Resources;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("ModernKeePass.Infrastructure")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("ModernKeePass.Infrastructure")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2020")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
[assembly: NeutralResourcesLanguage("en")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
38
ModernKeePass.Infrastructure/UWP/StorageFileClient.cs
Normal file
38
ModernKeePass.Infrastructure/UWP/StorageFileClient.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices.WindowsRuntime;
|
||||
using System.Threading.Tasks;
|
||||
using Windows.Storage;
|
||||
using Windows.Storage.AccessCache;
|
||||
using ModernKeePass.Application.Common.Interfaces;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.UWP
|
||||
{
|
||||
public class StorageFileClient: IFileProxy
|
||||
{
|
||||
public async Task<byte[]> OpenBinaryFile(string path)
|
||||
{
|
||||
var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(path);
|
||||
var result = await FileIO.ReadBufferAsync(file);
|
||||
return result.ToArray();
|
||||
}
|
||||
|
||||
public async Task<IList<string>> OpenTextFile(string path)
|
||||
{
|
||||
var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(path);
|
||||
var result = await FileIO.ReadLinesAsync(file);
|
||||
return result;
|
||||
}
|
||||
|
||||
public void ReleaseFile(string path)
|
||||
{
|
||||
StorageApplicationPermissions.FutureAccessList.Remove(path);
|
||||
}
|
||||
|
||||
public async Task WriteBinaryContentsToFile(string path, byte[] contents)
|
||||
{
|
||||
var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(path);
|
||||
await FileIO.WriteBytesAsync(file, contents);
|
||||
}
|
||||
}
|
||||
}
|
63
ModernKeePass.Infrastructure/UWP/UwpRecentFilesClient.cs
Normal file
63
ModernKeePass.Infrastructure/UWP/UwpRecentFilesClient.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Windows.Storage.AccessCache;
|
||||
using ModernKeePass.Application.Common.Interfaces;
|
||||
using ModernKeePass.Domain.Dtos;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.UWP
|
||||
{
|
||||
public class UwpRecentFilesClient: IRecentProxy
|
||||
{
|
||||
private readonly StorageItemMostRecentlyUsedList _mru = StorageApplicationPermissions.MostRecentlyUsedList;
|
||||
|
||||
public int EntryCount => _mru.Entries.Count;
|
||||
|
||||
public async Task<FileInfo> Get(string token)
|
||||
{
|
||||
var recentEntry = _mru.Entries.FirstOrDefault(e => e.Token == token);
|
||||
var file = await _mru.GetFileAsync(token);
|
||||
StorageApplicationPermissions.FutureAccessList.AddOrReplace(recentEntry.Metadata, file);
|
||||
return new FileInfo
|
||||
{
|
||||
Name = file.DisplayName,
|
||||
Path = recentEntry.Metadata
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<FileInfo>> GetAll()
|
||||
{
|
||||
var result = new List<FileInfo>();
|
||||
foreach (var entry in _mru.Entries)
|
||||
{
|
||||
try
|
||||
{
|
||||
var recentItem = await Get(entry.Token);
|
||||
result.Add(recentItem);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
_mru.Remove(entry.Token);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task Add(FileInfo recentItem)
|
||||
{
|
||||
var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(recentItem.Path);
|
||||
_mru.Add(file, recentItem.Path);
|
||||
}
|
||||
|
||||
public void ClearAll()
|
||||
{
|
||||
for (var i = _mru.Entries.Count; i > 0; i--)
|
||||
{
|
||||
var entry = _mru.Entries[i];
|
||||
StorageApplicationPermissions.FutureAccessList.Remove(entry.Metadata);
|
||||
_mru.Remove(entry.Token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
17
ModernKeePass.Infrastructure/UWP/UwpResourceClient.cs
Normal file
17
ModernKeePass.Infrastructure/UWP/UwpResourceClient.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using Windows.ApplicationModel.Resources;
|
||||
using ModernKeePass.Application.Common.Interfaces;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.UWP
|
||||
{
|
||||
public class UwpResourceClient: IResourceProxy
|
||||
{
|
||||
private const string ResourceFileName = "CodeBehind";
|
||||
private readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView();
|
||||
|
||||
public string GetResourceValue(string key)
|
||||
{
|
||||
var resource = _resourceLoader.GetString($"/{ResourceFileName}/{key}");
|
||||
return resource;
|
||||
}
|
||||
}
|
||||
}
|
31
ModernKeePass.Infrastructure/UWP/UwpSettingsClient.cs
Normal file
31
ModernKeePass.Infrastructure/UWP/UwpSettingsClient.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using Windows.Foundation.Collections;
|
||||
using Windows.Storage;
|
||||
using ModernKeePass.Application.Common.Interfaces;
|
||||
|
||||
namespace ModernKeePass.Infrastructure.UWP
|
||||
{
|
||||
public class UwpSettingsClient : ISettingsProxy
|
||||
{
|
||||
private readonly IPropertySet _values = ApplicationData.Current.LocalSettings.Values;
|
||||
|
||||
public T GetSetting<T>(string property, T defaultValue = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (T)Convert.ChangeType(_values[property], typeof(T));
|
||||
}
|
||||
catch (InvalidCastException)
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public void PutSetting<T>(string property, T value)
|
||||
{
|
||||
if (_values.ContainsKey(property))
|
||||
_values[property] = value;
|
||||
else _values.Add(property, value);
|
||||
}
|
||||
}
|
||||
}
|
11
ModernKeePass.Infrastructure/project.json
Normal file
11
ModernKeePass.Infrastructure/project.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"supports": {},
|
||||
"dependencies": {
|
||||
"Microsoft.NETCore.Portable.Compatibility": "1.0.1",
|
||||
"ModernKeePassLib": "2.44.1",
|
||||
"NETStandard.Library": "1.6.1"
|
||||
},
|
||||
"frameworks": {
|
||||
"netstandard1.2": {}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user