feat: add E2EE DMs, group chats, local serversettings.json, and security/perf fixes
This commit is contained in:
parent
b60b5a0774
commit
3b52de20d1
33 changed files with 5107 additions and 366 deletions
|
|
@ -1,6 +1,8 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using GsDChat.Core.Models;
|
||||
using GsDChat.Core.Protocol;
|
||||
|
||||
|
|
@ -9,6 +11,7 @@ namespace GsDChat.Client.State;
|
|||
public class ClientState
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private readonly string? _customKeyCachePath;
|
||||
|
||||
public string ServerUrl { get; set; } = "http://localhost:5000";
|
||||
public string Token { get; set; } = string.Empty;
|
||||
|
|
@ -16,15 +19,30 @@ public class ClientState
|
|||
public string CurrentUsername { get; set; } = string.Empty;
|
||||
public string CurrentUserRole { get; set; } = UserRoles.Member;
|
||||
|
||||
public string PublicKeyBase64 { get; set; } = string.Empty;
|
||||
public string PrivateKeyBase64 { get; set; } = string.Empty;
|
||||
public string? ServerPublicKeyBase64 { get; set; }
|
||||
public string? ServerEncryptedPrivateKey { get; set; }
|
||||
public bool AccountE2eeEnabled { get; set; } = true;
|
||||
|
||||
public bool IsPromptingE2eePin { get; set; } = false;
|
||||
public string E2eePinInputBuffer { get; set; } = string.Empty;
|
||||
|
||||
public string ServerName { get; set; } = "GsDChat Server";
|
||||
public string Motd { get; set; } = string.Empty;
|
||||
public bool AllowDmE2ee { get; set; } = true;
|
||||
public int MaxGroupChatUsers { get; set; } = 10;
|
||||
public ServerUiSync UiSync { get; set; } = ServerUiSync.CreateDefault();
|
||||
|
||||
public string ActiveScreenId { get; set; } = "F1_Chat";
|
||||
public string ActiveChannelId { get; set; } = string.Empty;
|
||||
|
||||
public List<Channel> Channels { get; } = new();
|
||||
public List<Channel> DirectMessages { get; } = new();
|
||||
public List<Channel> GroupChats { get; } = new();
|
||||
public Dictionary<string, List<ChatMessage>> ChannelMessages { get; } = new();
|
||||
public Dictionary<string, bool> ChannelHasMoreHistory { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
public HashSet<string> LoadingHistoryChannels { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
public List<UserSummary> Users { get; } = new();
|
||||
public List<FileSummary> Files { get; } = new();
|
||||
public List<string> SystemNotices { get; } = new();
|
||||
|
|
@ -36,17 +54,217 @@ public class ClientState
|
|||
public string StatusMessage { get; set; } = string.Empty;
|
||||
public DateTime StatusMessageUntil { get; set; } = DateTime.MinValue;
|
||||
|
||||
public ClientState(string? customKeyCachePath = null)
|
||||
{
|
||||
_customKeyCachePath = customKeyCachePath;
|
||||
}
|
||||
|
||||
public bool HasUnlockedE2eeKey => !string.IsNullOrWhiteSpace(PrivateKeyBase64) && !string.IsNullOrWhiteSpace(PublicKeyBase64);
|
||||
public bool HasServerKeyVault => !string.IsNullOrWhiteSpace(ServerEncryptedPrivateKey) || !string.IsNullOrWhiteSpace(ServerPublicKeyBase64);
|
||||
|
||||
public Channel? ActiveChannel
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return Channels.FirstOrDefault(c => c.Id == ActiveChannelId);
|
||||
return GetConversationByIdInternal(ActiveChannelId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Channel? GetConversationById(string channelId)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return GetConversationByIdInternal(channelId);
|
||||
}
|
||||
}
|
||||
|
||||
private Channel? GetConversationByIdInternal(string channelId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(channelId)) return null;
|
||||
return Channels.FirstOrDefault(c => c.Id == channelId)
|
||||
?? GroupChats.FirstOrDefault(g => g.Id == channelId)
|
||||
?? DirectMessages.FirstOrDefault(d => d.Id == channelId);
|
||||
}
|
||||
|
||||
public string? GetPeerPublicKeyForDm(Channel dm)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
// Find the other participant in the DM
|
||||
var peerId = dm.MemberIds.FirstOrDefault(id => !string.Equals(id, CurrentUserId, StringComparison.OrdinalIgnoreCase));
|
||||
if (!string.IsNullOrEmpty(peerId))
|
||||
{
|
||||
if (dm.MemberPublicKeys.TryGetValue(peerId, out var key) && !string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return key;
|
||||
}
|
||||
var user = Users.FirstOrDefault(u => string.Equals(u.Id, peerId, StringComparison.OrdinalIgnoreCase));
|
||||
if (!string.IsNullOrWhiteSpace(user?.PublicKey))
|
||||
{
|
||||
return user.PublicKey;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
var peerName = dm.MemberUsernames.FirstOrDefault(n => !string.Equals(n, CurrentUsername, StringComparison.OrdinalIgnoreCase)) ?? dm.Name;
|
||||
if (!string.IsNullOrEmpty(peerName))
|
||||
{
|
||||
string clean = peerName.TrimStart('@');
|
||||
if (!string.Equals(clean, CurrentUsername, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (dm.MemberPublicKeys.TryGetValue(clean, out var key) && !string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return key;
|
||||
}
|
||||
var user = Users.FirstOrDefault(u => string.Equals(u.Username, clean, StringComparison.OrdinalIgnoreCase));
|
||||
if (!string.IsNullOrWhiteSpace(user?.PublicKey))
|
||||
{
|
||||
return user.PublicKey;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Self-DM fallback only when messaging oneself
|
||||
if (dm.MemberIds.Count == 1 && string.Equals(dm.MemberIds[0], CurrentUserId, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(PublicKeyBase64) ? null : PublicKeyBase64;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void CheckLazyDmE2eePrompt()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var active = GetConversationByIdInternal(ActiveChannelId);
|
||||
if (active != null &&
|
||||
active.Type == ChannelTypes.DirectMessage &&
|
||||
AllowDmE2ee &&
|
||||
AccountE2eeEnabled &&
|
||||
active.IsE2ee &&
|
||||
!HasUnlockedE2eeKey)
|
||||
{
|
||||
IsPromptingE2eePin = true;
|
||||
NeedsRedraw = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
IsPromptingE2eePin = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string GetKeyCacheFilePath()
|
||||
{
|
||||
if (!string.IsNullOrEmpty(_customKeyCachePath)) return _customKeyCachePath;
|
||||
try
|
||||
{
|
||||
string homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
if (string.IsNullOrEmpty(homeDir)) homeDir = Directory.GetCurrentDirectory();
|
||||
string gsdDir = Path.Combine(homeDir, ".gsdchat");
|
||||
Directory.CreateDirectory(gsdDir);
|
||||
return Path.Combine(gsdDir, "e2ee_keys.json");
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Path.Combine(Directory.GetCurrentDirectory(), "e2ee_keys.json");
|
||||
}
|
||||
}
|
||||
|
||||
private string GetCacheEntryKey()
|
||||
{
|
||||
string normUrl = ServerHistoryManager.NormalizeUrl(ServerUrl).ToLowerInvariant();
|
||||
string userKey = !string.IsNullOrWhiteSpace(CurrentUserId) ? CurrentUserId.ToLowerInvariant() : CurrentUsername.ToLowerInvariant();
|
||||
return $"{normUrl}|{userKey}";
|
||||
}
|
||||
|
||||
public bool TryRestoreCachedE2eeKey()
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = GetKeyCacheFilePath();
|
||||
if (!File.Exists(path)) return false;
|
||||
|
||||
string json = File.ReadAllText(path);
|
||||
var dict = JsonSerializer.Deserialize<Dictionary<string, CachedKeyPair>>(json);
|
||||
if (dict == null) return false;
|
||||
|
||||
if (dict.TryGetValue(GetCacheEntryKey(), out var cached) &&
|
||||
!string.IsNullOrWhiteSpace(cached.PublicKey) &&
|
||||
!string.IsNullOrWhiteSpace(cached.PrivateKey))
|
||||
{
|
||||
// Verify cached key matches server public key if server already has one
|
||||
if (!string.IsNullOrWhiteSpace(ServerPublicKeyBase64) &&
|
||||
!string.Equals(ServerPublicKeyBase64, cached.PublicKey, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
PublicKeyBase64 = cached.PublicKey;
|
||||
PrivateKeyBase64 = cached.PrivateKey;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return false;
|
||||
}
|
||||
|
||||
public void SaveCachedE2eeKeys()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(PublicKeyBase64) || string.IsNullOrWhiteSpace(PrivateKeyBase64)) return;
|
||||
try
|
||||
{
|
||||
string path = GetKeyCacheFilePath();
|
||||
Dictionary<string, CachedKeyPair> dict = new();
|
||||
if (File.Exists(path))
|
||||
{
|
||||
try
|
||||
{
|
||||
dict = JsonSerializer.Deserialize<Dictionary<string, CachedKeyPair>>(File.ReadAllText(path)) ?? new();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
dict[GetCacheEntryKey()] = new CachedKeyPair
|
||||
{
|
||||
PublicKey = PublicKeyBase64,
|
||||
PrivateKey = PrivateKeyBase64
|
||||
};
|
||||
|
||||
File.WriteAllText(path, JsonSerializer.Serialize(dict, new JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public void ClearCachedE2eeKeys()
|
||||
{
|
||||
PublicKeyBase64 = string.Empty;
|
||||
PrivateKeyBase64 = string.Empty;
|
||||
try
|
||||
{
|
||||
string path = GetKeyCacheFilePath();
|
||||
if (!File.Exists(path)) return;
|
||||
var dict = JsonSerializer.Deserialize<Dictionary<string, CachedKeyPair>>(File.ReadAllText(path));
|
||||
if (dict != null && dict.Remove(GetCacheEntryKey()))
|
||||
{
|
||||
File.WriteAllText(path, JsonSerializer.Serialize(dict, new JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private class CachedKeyPair
|
||||
{
|
||||
public string PublicKey { get; set; } = string.Empty;
|
||||
public string PrivateKey { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public void SetStatus(string message, int durationSeconds = 5)
|
||||
{
|
||||
lock (_lock)
|
||||
|
|
@ -67,6 +285,28 @@ public class ClientState
|
|||
}
|
||||
}
|
||||
|
||||
public void AddSystemMessageToChat(string text, string channelId)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!ChannelMessages.TryGetValue(channelId, out var list))
|
||||
{
|
||||
list = new List<ChatMessage>();
|
||||
ChannelMessages[channelId] = list;
|
||||
}
|
||||
list.Add(new ChatMessage
|
||||
{
|
||||
Id = Guid.NewGuid().ToString(),
|
||||
ChannelId = channelId,
|
||||
SenderUsername = "System",
|
||||
SenderRole = "System",
|
||||
Content = text,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void AddChatMessage(ChatMessage message)
|
||||
{
|
||||
lock (_lock)
|
||||
|
|
@ -76,32 +316,100 @@ public class ClientState
|
|||
list = new List<ChatMessage>();
|
||||
ChannelMessages[message.ChannelId] = list;
|
||||
}
|
||||
list.Add(message);
|
||||
if (!list.Any(m => m.Id == message.Id))
|
||||
{
|
||||
list.Add(message);
|
||||
}
|
||||
NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetHistory(string channelId, List<ChatMessage> messages)
|
||||
public List<ChatMessage> GetMessagesForChannel(string channelId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(channelId)) return new List<ChatMessage>();
|
||||
lock (_lock)
|
||||
{
|
||||
if (ChannelMessages.TryGetValue(channelId, out var list))
|
||||
{
|
||||
return new List<ChatMessage>(list);
|
||||
}
|
||||
return new List<ChatMessage>();
|
||||
}
|
||||
}
|
||||
|
||||
public List<ChatMessage> GetAllLoadedMessages()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var all = new List<ChatMessage>();
|
||||
foreach (var kvp in ChannelMessages)
|
||||
{
|
||||
all.AddRange(kvp.Value);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetHistory(string channelId, List<ChatMessage> messages, bool hasMore = false)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
ChannelMessages[channelId] = messages;
|
||||
ChannelHasMoreHistory[channelId] = hasMore;
|
||||
LoadingHistoryChannels.Remove(channelId);
|
||||
NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateChannels(List<Channel> channels, string activeId)
|
||||
public void PrependHistory(string channelId, List<ChatMessage> olderMessages, bool hasMore)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!ChannelMessages.TryGetValue(channelId, out var existing))
|
||||
{
|
||||
existing = new List<ChatMessage>();
|
||||
ChannelMessages[channelId] = existing;
|
||||
}
|
||||
|
||||
var existingIds = new HashSet<string>(existing.Select(m => m.Id), StringComparer.OrdinalIgnoreCase);
|
||||
var uniqueOlder = olderMessages.Where(m => !existingIds.Contains(m.Id)).ToList();
|
||||
if (uniqueOlder.Count > 0)
|
||||
{
|
||||
existing.InsertRange(0, uniqueOlder);
|
||||
}
|
||||
|
||||
ChannelHasMoreHistory[channelId] = hasMore;
|
||||
LoadingHistoryChannels.Remove(channelId);
|
||||
NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateChannels(List<Channel> channels, string activeId, List<Channel>? directMessages = null, List<Channel>? groupChats = null)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
Channels.Clear();
|
||||
Channels.AddRange(channels);
|
||||
|
||||
if (directMessages != null)
|
||||
{
|
||||
DirectMessages.Clear();
|
||||
DirectMessages.AddRange(directMessages);
|
||||
}
|
||||
|
||||
if (groupChats != null)
|
||||
{
|
||||
GroupChats.Clear();
|
||||
GroupChats.AddRange(groupChats);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(activeId))
|
||||
{
|
||||
ActiveChannelId = activeId;
|
||||
}
|
||||
NeedsRedraw = true;
|
||||
}
|
||||
CheckLazyDmE2eePrompt();
|
||||
}
|
||||
|
||||
public void UpdateUsers(List<UserSummary> users)
|
||||
|
|
@ -110,6 +418,15 @@ public class ClientState
|
|||
{
|
||||
Users.Clear();
|
||||
Users.AddRange(users);
|
||||
var me = users.FirstOrDefault(u => string.Equals(u.Id, CurrentUserId, StringComparison.OrdinalIgnoreCase));
|
||||
if (me != null)
|
||||
{
|
||||
AccountE2eeEnabled = me.E2eeEnabled;
|
||||
if (!string.IsNullOrWhiteSpace(me.PublicKey))
|
||||
{
|
||||
ServerPublicKeyBase64 = me.PublicKey;
|
||||
}
|
||||
}
|
||||
NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue