feat: add E2EE DMs, group chats, local serversettings.json, and security/perf fixes

This commit is contained in:
tyuXX 2026-10-17 13:16:42 +00:00
parent b60b5a0774
commit 3b52de20d1
33 changed files with 5107 additions and 366 deletions

View file

@ -1,16 +1,18 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Net.WebSockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using GsDChat.Client.State;
using GsDChat.Core.Models;
using GsDChat.Core.Protocol;
using GsDChat.Core.Security;
namespace GsDChat.Client.Network;
@ -57,7 +59,13 @@ public class ChatClientConnection : IDisposable
}
var json = await res.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<ServerInfoResponse>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
var info = JsonSerializer.Deserialize<ServerInfoResponse>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (info != null)
{
_state.AllowDmE2ee = info.AllowDmE2ee;
_state.MaxGroupChatUsers = info.MaxGroupChatUsers;
}
return info;
}
else
{
@ -95,8 +103,22 @@ public class ChatClientConnection : IDisposable
};
}
return JsonSerializer.Deserialize<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
var authRes = JsonSerializer.Deserialize<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." };
if (authRes.Success)
{
_state.Token = authRes.Token ?? _state.Token;
_state.CurrentUserId = authRes.UserId ?? _state.CurrentUserId;
_state.CurrentUsername = authRes.Username ?? username;
_state.CurrentUserRole = authRes.Role ?? _state.CurrentUserRole;
_state.ServerPublicKeyBase64 = authRes.PublicKey;
_state.ServerEncryptedPrivateKey = authRes.EncryptedPrivateKey;
_state.AccountE2eeEnabled = authRes.E2eeEnabled;
_state.TryRestoreCachedE2eeKey();
}
return authRes;
}
catch (Exception ex)
{
@ -128,8 +150,22 @@ public class ChatClientConnection : IDisposable
};
}
return JsonSerializer.Deserialize<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
var authRes = JsonSerializer.Deserialize<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." };
if (authRes.Success)
{
_state.Token = authRes.Token ?? _state.Token;
_state.CurrentUserId = authRes.UserId ?? _state.CurrentUserId;
_state.CurrentUsername = authRes.Username ?? username;
_state.CurrentUserRole = authRes.Role ?? _state.CurrentUserRole;
_state.ServerPublicKeyBase64 = authRes.PublicKey;
_state.ServerEncryptedPrivateKey = authRes.EncryptedPrivateKey;
_state.AccountE2eeEnabled = authRes.E2eeEnabled;
_state.TryRestoreCachedE2eeKey();
}
return authRes;
}
catch (Exception ex)
{
@ -139,6 +175,8 @@ public class ChatClientConnection : IDisposable
public async Task StartWebSocketAsync()
{
_state.TryRestoreCachedE2eeKey();
_cts = new CancellationTokenSource();
_webSocket = new ClientWebSocket();
@ -156,12 +194,86 @@ public class ChatClientConnection : IDisposable
_state.SetStatus("Connected to chat server!");
_ = Task.Run(() => ReceiveLoopAsync(_cts.Token));
if (_state.HasUnlockedE2eeKey && string.IsNullOrWhiteSpace(_state.ServerPublicKeyBase64))
{
await PublishPublicKeyAsync(_state.PublicKeyBase64);
}
}
public async Task<(bool Success, string Message)> UnlockOrInitializeE2eeWithPinAsync(string pin, bool resetKeys = false)
{
if (string.IsNullOrWhiteSpace(pin))
{
return (false, "E2EE Passphrase/PIN cannot be empty.");
}
if (!resetKeys && !string.IsNullOrWhiteSpace(_state.ServerEncryptedPrivateKey))
{
string? unwrapped = E2eeCrypto.UnwrapPrivateKey(_state.ServerEncryptedPrivateKey, pin, _state.CurrentUsername);
if (string.IsNullOrWhiteSpace(unwrapped))
{
return (false, "Incorrect E2EE PIN. Try again, or use '/e2ee reset <new_pin>' to reset your E2EE keys.");
}
string pub = !string.IsNullOrWhiteSpace(_state.ServerPublicKeyBase64)
? _state.ServerPublicKeyBase64!
: E2eeCrypto.ExtractPublicKeyFromPrivateKey(unwrapped);
_state.PrivateKeyBase64 = unwrapped;
_state.PublicKeyBase64 = pub;
_state.ServerPublicKeyBase64 = pub;
_state.IsPromptingE2eePin = false;
_state.E2eePinInputBuffer = string.Empty;
_state.SaveCachedE2eeKeys();
ReDecryptLoadedMessages();
return (true, "E2EE key vault unlocked! Past encrypted DMs decrypted.");
}
else
{
var (pub, priv) = E2eeCrypto.GenerateKeyPair();
string wrapped = E2eeCrypto.WrapPrivateKey(priv, pin, _state.CurrentUsername);
_state.PublicKeyBase64 = pub;
_state.PrivateKeyBase64 = priv;
_state.ServerPublicKeyBase64 = pub;
_state.ServerEncryptedPrivateKey = wrapped;
_state.IsPromptingE2eePin = false;
_state.E2eePinInputBuffer = string.Empty;
_state.SaveCachedE2eeKeys();
await PublishPublicKeyAsync(pub, wrapped, resetKeys);
ReDecryptLoadedMessages();
return (true, resetKeys
? "E2EE keypair & PIN reset! New messages will use your new key."
: "E2EE PIN created and key vault initialized!");
}
}
public void LockE2eeKeys()
{
_state.ClearCachedE2eeKeys();
_state.SetStatus("E2EE key vault locked on this device.");
}
public void ReDecryptLoadedMessages()
{
foreach (var msg in _state.GetAllLoadedMessages())
{
if (E2eeCrypto.IsEncryptedPayload(msg.Content))
{
DecryptMessageIfNeeded(msg);
}
}
_state.NeedsRedraw = true;
}
private async Task ReceiveLoopAsync(CancellationToken ct)
{
var buffer = new byte[8192];
var accumulator = new System.Collections.Generic.List<byte>();
var accumulator = new List<byte>();
try
{
@ -206,6 +318,23 @@ public class ChatClientConnection : IDisposable
switch (envelope.Type)
{
case MessageTypes.AuthResult:
var authRes = envelope.Unpack<AuthResultPacket>();
if (authRes != null && authRes.Success)
{
if (!string.IsNullOrWhiteSpace(authRes.UserId)) _state.CurrentUserId = authRes.UserId;
if (!string.IsNullOrWhiteSpace(authRes.Username)) _state.CurrentUsername = authRes.Username;
if (!string.IsNullOrWhiteSpace(authRes.PublicKey)) _state.ServerPublicKeyBase64 = authRes.PublicKey;
if (!string.IsNullOrWhiteSpace(authRes.EncryptedPrivateKey)) _state.ServerEncryptedPrivateKey = authRes.EncryptedPrivateKey;
_state.AccountE2eeEnabled = authRes.E2eeEnabled;
if (!_state.HasUnlockedE2eeKey)
{
_state.TryRestoreCachedE2eeKey();
}
_state.CheckLazyDmE2eePrompt();
}
break;
case MessageTypes.UiSync:
var ui = envelope.Unpack<ServerUiSync>();
if (ui != null)
@ -213,6 +342,9 @@ public class ChatClientConnection : IDisposable
_state.UiSync = ui;
_state.ServerName = ui.ServerName;
_state.Motd = ui.Motd;
_state.AllowDmE2ee = ui.AllowDmE2ee;
_state.MaxGroupChatUsers = ui.MaxGroupChatUsers;
_state.CheckLazyDmE2eePrompt();
_state.NeedsRedraw = true;
}
break;
@ -221,7 +353,8 @@ public class ChatClientConnection : IDisposable
var chSync = envelope.Unpack<ChannelListSyncPacket>();
if (chSync != null)
{
_state.UpdateChannels(chSync.Channels, chSync.ActiveChannelId);
_state.UpdateChannels(chSync.Channels, chSync.ActiveChannelId, chSync.DirectMessages, chSync.GroupChats);
ReDecryptLoadedMessages();
}
break;
@ -229,7 +362,18 @@ public class ChatClientConnection : IDisposable
var histSync = envelope.Unpack<HistorySyncPacket>();
if (histSync != null)
{
_state.SetHistory(histSync.ChannelId, histSync.Messages);
foreach (var msg in histSync.Messages)
{
DecryptMessageIfNeeded(msg);
}
if (histSync.Prepend)
{
_state.PrependHistory(histSync.ChannelId, histSync.Messages, histSync.HasMore);
}
else
{
_state.SetHistory(histSync.ChannelId, histSync.Messages, histSync.HasMore);
}
}
break;
@ -237,6 +381,7 @@ public class ChatClientConnection : IDisposable
var msgBc = envelope.Unpack<MessageBroadcastPacket>();
if (msgBc != null)
{
DecryptMessageIfNeeded(msgBc.Message);
_state.AddChatMessage(msgBc.Message);
}
break;
@ -246,6 +391,7 @@ public class ChatClientConnection : IDisposable
if (uSync != null)
{
_state.UpdateUsers(uSync.Users);
ReDecryptLoadedMessages();
}
break;
@ -272,6 +418,10 @@ public class ChatClientConnection : IDisposable
{
_state.AddNotice(cmdRes.Output);
_state.SetStatus(cmdRes.Success ? "Command executed." : "Command error.", 4);
if (!string.IsNullOrEmpty(cmdRes.Output) && !string.IsNullOrEmpty(cmdRes.ChannelId))
{
_state.AddSystemMessageToChat(cmdRes.Output, cmdRes.ChannelId);
}
}
break;
@ -290,6 +440,68 @@ public class ChatClientConnection : IDisposable
}
}
private void DecryptMessageIfNeeded(ChatMessage msg)
{
if (!msg.IsEncrypted && !E2eeCrypto.IsEncryptedPayload(msg.Content))
{
return;
}
msg.IsEncrypted = true;
if (!E2eeCrypto.IsEncryptedPayload(msg.Content) || string.IsNullOrWhiteSpace(_state.PrivateKeyBase64))
{
return;
}
string? peerPubKey = null;
bool sentByMe = string.Equals(msg.SenderId, _state.CurrentUserId, StringComparison.OrdinalIgnoreCase) ||
string.Equals(msg.SenderUsername, _state.CurrentUsername, StringComparison.OrdinalIgnoreCase);
if (sentByMe)
{
// For messages I sent, use RecipientPublicKey first so even if the peer later resets their key, my sent history still decrypts!
if (!string.IsNullOrWhiteSpace(msg.RecipientPublicKey))
{
peerPubKey = msg.RecipientPublicKey;
}
}
else
{
// For messages received from peer, use SenderPublicKey first
if (!string.IsNullOrWhiteSpace(msg.SenderPublicKey))
{
peerPubKey = msg.SenderPublicKey;
}
}
// Fallback to current DM channel participant public key
if (string.IsNullOrWhiteSpace(peerPubKey))
{
var conv = _state.GetConversationById(msg.ChannelId);
if (conv != null)
{
peerPubKey = _state.GetPeerPublicKeyForDm(conv);
}
}
if (string.IsNullOrWhiteSpace(peerPubKey))
{
peerPubKey = !string.IsNullOrWhiteSpace(msg.RecipientPublicKey) ? msg.RecipientPublicKey : msg.SenderPublicKey;
}
if (!string.IsNullOrWhiteSpace(peerPubKey))
{
string decrypted = E2eeCrypto.DecryptMessage(msg.Content, _state.PrivateKeyBase64, peerPubKey);
// Only replace raw E2EE:v1: payload if decryption succeeded
if (!decrypted.StartsWith("[Encrypted Message"))
{
msg.Content = decrypted;
}
}
}
public async Task SendEnvelopeAsync(NetworkEnvelope envelope)
{
if (_webSocket == null || _webSocket.State != WebSocketState.Open) return;
@ -311,12 +523,91 @@ public class ChatClientConnection : IDisposable
}
}
public Task SendChatMessageAsync(string channelId, string content)
public Task SendChatMessageAsync(string channelId, string content, bool? forceEncrypt = null)
{
var conv = _state.GetConversationById(channelId);
bool isDm = conv != null && conv.Type == ChannelTypes.DirectMessage;
bool e2eeActiveForDm = isDm && conv!.IsE2ee && _state.AllowDmE2ee && _state.AccountE2eeEnabled;
bool shouldEncrypt = forceEncrypt ?? e2eeActiveForDm;
string payloadContent = content;
bool isEncrypted = false;
string? recipientPubKey = null;
if (shouldEncrypt)
{
if (!_state.HasUnlockedE2eeKey)
{
if (forceEncrypt == true)
{
var (tempPub, tempPriv) = E2eeCrypto.GenerateKeyPair();
payloadContent = E2eeCrypto.EncryptMessage(content, tempPriv, tempPub);
isEncrypted = true;
}
else
{
_state.SetStatus("Warning: Your E2EE key is not unlocked — sending as plaintext. Use '/e2ee pin <pin>' to unlock.", 5);
}
}
else
{
recipientPubKey = conv != null ? _state.GetPeerPublicKeyForDm(conv) : _state.PublicKeyBase64;
if (string.IsNullOrWhiteSpace(recipientPubKey) && forceEncrypt == true)
{
recipientPubKey = _state.PublicKeyBase64;
}
if (!string.IsNullOrWhiteSpace(recipientPubKey))
{
payloadContent = E2eeCrypto.EncryptMessage(content, _state.PrivateKeyBase64, recipientPubKey);
isEncrypted = true;
}
else
{
_state.SetStatus("Warning: Recipient has not initialized E2EE yet — message sent as plaintext.", 5);
}
}
}
var envelope = NetworkEnvelope.Create(MessageTypes.SendMessage, new SendMessagePacket
{
ChannelId = channelId,
Content = content
Content = payloadContent,
IsEncrypted = isEncrypted,
SenderPublicKey = isEncrypted ? _state.PublicKeyBase64 : null,
RecipientPublicKey = isEncrypted ? recipientPubKey : null
});
return SendEnvelopeAsync(envelope);
}
public Task FetchOlderHistoryAsync(string channelId, int limit = 50)
{
if (string.IsNullOrWhiteSpace(channelId)) return Task.CompletedTask;
if (_state.LoadingHistoryChannels.Contains(channelId)) return Task.CompletedTask;
int currentCount = 0;
if (_state.ChannelMessages.TryGetValue(channelId, out var list))
{
currentCount = list.Count;
}
_state.LoadingHistoryChannels.Add(channelId);
var envelope = NetworkEnvelope.Create(MessageTypes.FetchHistory, new FetchHistoryPacket
{
ChannelId = channelId,
Offset = currentCount,
Limit = limit
});
return SendEnvelopeAsync(envelope);
}
public Task ToggleE2eeAsync(string scope, bool enabled, string? channelId = null)
{
var envelope = NetworkEnvelope.Create(MessageTypes.ToggleE2ee, new ToggleE2eePacket
{
Scope = scope,
ChannelId = channelId ?? _state.ActiveChannelId,
Enabled = enabled
});
return SendEnvelopeAsync(envelope);
}
@ -339,6 +630,58 @@ public class ChatClientConnection : IDisposable
return SendEnvelopeAsync(envelope);
}
public Task StartDmAsync(string targetUsername, string? targetUserId = null)
{
var envelope = NetworkEnvelope.Create(MessageTypes.StartDm, new StartDmPacket
{
TargetUsername = targetUsername,
TargetUserId = targetUserId ?? string.Empty
});
return SendEnvelopeAsync(envelope);
}
public Task CreateGroupChatAsync(string name, IEnumerable<string>? memberUsernames = null, string topic = "", int? maxUsers = null)
{
var envelope = NetworkEnvelope.Create(MessageTypes.CreateGroup, new CreateGroupPacket
{
Name = name,
Topic = topic,
MemberUsernames = memberUsernames?.ToList() ?? new List<string>(),
MaxUsers = maxUsers
});
return SendEnvelopeAsync(envelope);
}
public Task InviteToGroupAsync(string channelId, string targetUsername)
{
var envelope = NetworkEnvelope.Create(MessageTypes.InviteToGroup, new InviteToGroupPacket
{
ChannelId = channelId,
TargetUsername = targetUsername
});
return SendEnvelopeAsync(envelope);
}
public Task LeaveGroupAsync(string channelId)
{
var envelope = NetworkEnvelope.Create(MessageTypes.LeaveGroup, new LeaveGroupPacket
{
ChannelId = channelId
});
return SendEnvelopeAsync(envelope);
}
public Task PublishPublicKeyAsync(string publicKey, string? encryptedPrivateKey = null, bool resetKeys = false)
{
var envelope = NetworkEnvelope.Create(MessageTypes.PublishPublicKey, new PublishPublicKeyPacket
{
PublicKey = publicKey,
EncryptedPrivateKey = encryptedPrivateKey,
ResetKeys = resetKeys
});
return SendEnvelopeAsync(envelope);
}
public Task ExecuteCommandAsync(string command, string args, string channelId)
{
var envelope = NetworkEnvelope.Create(MessageTypes.ExecuteCommand, new ExecuteCommandPacket