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,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
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ public class ConsoleUi
|
|||
// Register default screens
|
||||
RegisterScreen(new ChatScreen(state, connection));
|
||||
RegisterScreen(new ChannelsScreen(state, connection));
|
||||
RegisterScreen(new UsersScreen(state));
|
||||
RegisterScreen(new UsersScreen(state, connection));
|
||||
RegisterScreen(new FilesScreen(state, connection));
|
||||
}
|
||||
|
||||
|
|
@ -168,9 +168,11 @@ public class ConsoleUi
|
|||
|
||||
private void Draw()
|
||||
{
|
||||
Console.SetCursorPosition(0, 0);
|
||||
var (width, height) = GetWindowDimensions();
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(Ansi.ClearScreen);
|
||||
sb.Append(Ansi.CursorHome);
|
||||
|
||||
// 1. Top Bar: Server Title & Screen Tabs
|
||||
|
|
|
|||
|
|
@ -1,22 +1,34 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using GsDChat.Client.Network;
|
||||
using GsDChat.Client.Rendering;
|
||||
using GsDChat.Client.State;
|
||||
using GsDChat.Core.Models;
|
||||
|
||||
namespace GsDChat.Client.Screens;
|
||||
|
||||
public class ChannelsScreen : IScreen
|
||||
{
|
||||
private enum PromptMode
|
||||
{
|
||||
None,
|
||||
CreateChannel,
|
||||
CreateGroup,
|
||||
StartDm,
|
||||
InviteGroup
|
||||
}
|
||||
|
||||
private readonly ClientState _state;
|
||||
private readonly ChatClientConnection _connection;
|
||||
private int _selectedIndex = 0;
|
||||
private bool _isCreating = false;
|
||||
private string _createBuffer = string.Empty;
|
||||
private PromptMode _promptMode = PromptMode.None;
|
||||
private string _inputBuffer = string.Empty;
|
||||
|
||||
public string ScreenId => "F2_Channels";
|
||||
public string Title => "Channels";
|
||||
public string Title => "Channels/DMs";
|
||||
public string ShortcutKey => "F2";
|
||||
|
||||
public ChannelsScreen(ClientState state, ChatClientConnection connection)
|
||||
|
|
@ -25,91 +37,182 @@ public class ChannelsScreen : IScreen
|
|||
_connection = connection;
|
||||
}
|
||||
|
||||
private List<Channel> GetAllConversations()
|
||||
{
|
||||
var list = new List<Channel>();
|
||||
list.AddRange(_state.Channels);
|
||||
list.AddRange(_state.GroupChats);
|
||||
list.AddRange(_state.DirectMessages);
|
||||
return list;
|
||||
}
|
||||
|
||||
public void Render(int width, int height, StringBuilder sb)
|
||||
{
|
||||
sb.AppendLine($" {Ansi.Bold}{Ansi.Yellow}Channel Browser{Ansi.Reset} {Ansi.Gray}(Press ENTER to join, 'C' to create, 'D' to delete){Ansi.Reset}");
|
||||
string e2eeStatus = _state.AllowDmE2ee ? "E2EE: ON" : "E2EE: OFF";
|
||||
sb.AppendLine($" {Ansi.Bold}{Ansi.Yellow}Conversations Browser{Ansi.Reset} {Ansi.Gray}(Max Group Size: {_state.MaxGroupChatUsers} │ DM {e2eeStatus}){Ansi.Reset}");
|
||||
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
||||
|
||||
if (_state.Channels.Count == 0)
|
||||
var all = GetAllConversations();
|
||||
if (all.Count == 0)
|
||||
{
|
||||
sb.AppendLine(" No channels available.");
|
||||
sb.AppendLine(" No conversations available.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_selectedIndex >= _state.Channels.Count) _selectedIndex = _state.Channels.Count - 1;
|
||||
if (_selectedIndex >= all.Count) _selectedIndex = all.Count - 1;
|
||||
if (_selectedIndex < 0) _selectedIndex = 0;
|
||||
|
||||
for (int i = 0; i < _state.Channels.Count; i++)
|
||||
int idx = 0;
|
||||
|
||||
// 1. Public Channels
|
||||
sb.AppendLine($" {Ansi.Bold}{Ansi.Cyan}── Server Channels ──{Ansi.Reset}");
|
||||
foreach (var ch in _state.Channels)
|
||||
{
|
||||
var ch = _state.Channels[i];
|
||||
bool isSelected = i == _selectedIndex;
|
||||
bool isActive = ch.Id == _state.ActiveChannelId;
|
||||
RenderItem(sb, ch, idx == _selectedIndex, $"#{ch.Name}", ch.Topic);
|
||||
idx++;
|
||||
}
|
||||
|
||||
string prefix = isSelected ? $"{Ansi.BrightYellow}► " : " ";
|
||||
string activeTag = isActive ? $" {Ansi.BrightGreen}[ACTIVE]{Ansi.Reset}" : "";
|
||||
string name = $"{Ansi.Bold}#{ch.Name}{Ansi.Reset}";
|
||||
string topic = string.IsNullOrEmpty(ch.Topic) ? "" : $" {Ansi.Gray}- {ch.Topic}{Ansi.Reset}";
|
||||
|
||||
if (isSelected)
|
||||
// 2. Group Chats
|
||||
sb.AppendLine($" {Ansi.Bold}{Ansi.BrightMagenta}── Group Chats (Max {_state.MaxGroupChatUsers} users) ──{Ansi.Reset}");
|
||||
if (_state.GroupChats.Count == 0)
|
||||
{
|
||||
sb.AppendLine($" {Ansi.Gray}(No group chats yet - Press 'G' to create one){Ansi.Reset}");
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var grp in _state.GroupChats)
|
||||
{
|
||||
sb.AppendLine($"{prefix}{Ansi.Inverse}#{ch.Name}{Ansi.Reset}{activeTag}{topic}");
|
||||
int maxU = grp.MaxUsers > 0 ? grp.MaxUsers : _state.MaxGroupChatUsers;
|
||||
string meta = $"({grp.MemberIds.Count}/{maxU} users)" + (string.IsNullOrEmpty(grp.Topic) ? "" : $" - {grp.Topic}");
|
||||
RenderItem(sb, grp, idx == _selectedIndex, $"[Group] {grp.Name}", meta);
|
||||
idx++;
|
||||
}
|
||||
else
|
||||
}
|
||||
|
||||
// 3. Direct Messages
|
||||
sb.AppendLine($" {Ansi.Bold}{Ansi.BrightGreen}── Direct Messages ──{Ansi.Reset}");
|
||||
if (_state.DirectMessages.Count == 0)
|
||||
{
|
||||
sb.AppendLine($" {Ansi.Gray}(No active DMs yet - Press 'M' to start a DM){Ansi.Reset}");
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var dm in _state.DirectMessages)
|
||||
{
|
||||
sb.AppendLine($"{prefix}{name}{activeTag}{topic}");
|
||||
string lockTag = (dm.IsE2ee && _state.AllowDmE2ee) ? "🔒 Full E2EE" : "Plaintext";
|
||||
RenderItem(sb, dm, idx == _selectedIndex, $"@{dm.Name.TrimStart('@')}", lockTag);
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
|
||||
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
||||
|
||||
if (_isCreating)
|
||||
switch (_promptMode)
|
||||
{
|
||||
sb.AppendLine($" {Ansi.BrightYellow}Create Channel > Name [Topic]:{Ansi.Reset} {_createBuffer}█");
|
||||
case PromptMode.CreateChannel:
|
||||
sb.AppendLine($" {Ansi.BrightYellow}Create Channel > Name [Topic]:{Ansi.Reset} {_inputBuffer}█");
|
||||
break;
|
||||
case PromptMode.CreateGroup:
|
||||
sb.AppendLine($" {Ansi.BrightMagenta}Create Group (max {_state.MaxGroupChatUsers}) > GroupName [user1,user2,...]:{Ansi.Reset} {_inputBuffer}█");
|
||||
break;
|
||||
case PromptMode.StartDm:
|
||||
sb.AppendLine($" {Ansi.BrightGreen}Start Direct Message > Target Username:{Ansi.Reset} {_inputBuffer}█");
|
||||
break;
|
||||
case PromptMode.InviteGroup:
|
||||
sb.AppendLine($" {Ansi.BrightCyan}Invite to Group > Username:{Ansi.Reset} {_inputBuffer}█");
|
||||
break;
|
||||
default:
|
||||
sb.AppendLine($" {Ansi.Gray}[↑/↓] Select [Enter] Open [C] Channel [G] Group [M] DM [E] Toggle DM E2EE [A] Account E2EE [L/D] Leave/Del{Ansi.Reset}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderItem(StringBuilder sb, Channel ch, bool isSelected, string label, string subtitle)
|
||||
{
|
||||
bool isActive = ch.Id == _state.ActiveChannelId;
|
||||
string prefix = isSelected ? $"{Ansi.BrightYellow}► " : " ";
|
||||
string activeTag = isActive ? $" {Ansi.BrightGreen}[ACTIVE]{Ansi.Reset}" : "";
|
||||
string sub = string.IsNullOrEmpty(subtitle) ? "" : $" {Ansi.Gray}- {subtitle}{Ansi.Reset}";
|
||||
|
||||
if (isSelected)
|
||||
{
|
||||
sb.AppendLine($"{prefix}{Ansi.Inverse}{label}{Ansi.Reset}{activeTag}{sub}");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.AppendLine($" {Ansi.Gray}[↑/↓] Navigate [Enter] Join Channel [C] Create Channel [D] Delete Channel{Ansi.Reset}");
|
||||
sb.AppendLine($"{prefix}{Ansi.Bold}{label}{Ansi.Reset}{activeTag}{sub}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task HandleKeyAsync(ConsoleKeyInfo key)
|
||||
{
|
||||
if (_isCreating)
|
||||
var all = GetAllConversations();
|
||||
|
||||
if (_promptMode != PromptMode.None)
|
||||
{
|
||||
if (key.Key == ConsoleKey.Enter)
|
||||
{
|
||||
string input = _createBuffer.Trim();
|
||||
_isCreating = false;
|
||||
_createBuffer = string.Empty;
|
||||
string input = _inputBuffer.Trim();
|
||||
var mode = _promptMode;
|
||||
_promptMode = PromptMode.None;
|
||||
_inputBuffer = string.Empty;
|
||||
|
||||
if (!string.IsNullOrEmpty(input))
|
||||
{
|
||||
var parts = input.Split(' ', 2);
|
||||
string name = parts[0];
|
||||
string topic = parts.Length > 1 ? parts[1] : string.Empty;
|
||||
await _connection.CreateChannelAsync(name, topic);
|
||||
_state.ActiveScreenId = "F1_Chat";
|
||||
_state.SetStatus($"Created and joined #{name}");
|
||||
if (mode == PromptMode.CreateChannel)
|
||||
{
|
||||
var parts = input.Split(' ', 2);
|
||||
string name = parts[0];
|
||||
string topic = parts.Length > 1 ? parts[1] : string.Empty;
|
||||
await _connection.CreateChannelAsync(name, topic);
|
||||
_state.ActiveScreenId = "F1_Chat";
|
||||
}
|
||||
else if (mode == PromptMode.CreateGroup)
|
||||
{
|
||||
var parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
string name = parts[0];
|
||||
var members = parts.Skip(1).ToList();
|
||||
await _connection.CreateGroupChatAsync(name, members);
|
||||
_state.ActiveScreenId = "F1_Chat";
|
||||
}
|
||||
else if (mode == PromptMode.StartDm)
|
||||
{
|
||||
string targetUser = input.Split(' ')[0].TrimStart('@');
|
||||
await _connection.StartDmAsync(targetUser);
|
||||
_state.ActiveScreenId = "F1_Chat";
|
||||
}
|
||||
else if (mode == PromptMode.InviteGroup)
|
||||
{
|
||||
var selected = (_selectedIndex >= 0 && _selectedIndex < all.Count) ? all[_selectedIndex] : _state.ActiveChannel;
|
||||
if (selected != null && selected.Type == ChannelTypes.Group)
|
||||
{
|
||||
await _connection.InviteToGroupAsync(selected.Id, input.TrimStart('@'));
|
||||
}
|
||||
else
|
||||
{
|
||||
_state.SetStatus("Select a group chat first to invite a member.");
|
||||
}
|
||||
}
|
||||
}
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.Escape)
|
||||
{
|
||||
_isCreating = false;
|
||||
_createBuffer = string.Empty;
|
||||
_promptMode = PromptMode.None;
|
||||
_inputBuffer = string.Empty;
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.Backspace)
|
||||
{
|
||||
if (_createBuffer.Length > 0)
|
||||
if (_inputBuffer.Length > 0)
|
||||
{
|
||||
_createBuffer = _createBuffer[..^1];
|
||||
_inputBuffer = _inputBuffer[..^1];
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
else if (!char.IsControl(key.KeyChar))
|
||||
{
|
||||
_createBuffer += key.KeyChar;
|
||||
_inputBuffer += key.KeyChar;
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
return;
|
||||
|
|
@ -122,39 +225,88 @@ public class ChannelsScreen : IScreen
|
|||
}
|
||||
else if (key.Key == ConsoleKey.DownArrow)
|
||||
{
|
||||
_selectedIndex = Math.Min(_state.Channels.Count - 1, _selectedIndex + 1);
|
||||
_selectedIndex = Math.Min(Math.Max(0, all.Count - 1), _selectedIndex + 1);
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.Enter)
|
||||
{
|
||||
if (_selectedIndex >= 0 && _selectedIndex < _state.Channels.Count)
|
||||
if (_selectedIndex >= 0 && _selectedIndex < all.Count)
|
||||
{
|
||||
var selected = _state.Channels[_selectedIndex];
|
||||
var selected = all[_selectedIndex];
|
||||
await _connection.JoinChannelAsync(selected.Id);
|
||||
_state.ActiveScreenId = "F1_Chat";
|
||||
_state.SetStatus($"Switched to #{selected.Name}");
|
||||
_state.SetStatus($"Switched to {selected.Name}");
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
else if (key.Key == ConsoleKey.C)
|
||||
{
|
||||
_isCreating = true;
|
||||
_createBuffer = string.Empty;
|
||||
_promptMode = PromptMode.CreateChannel;
|
||||
_inputBuffer = string.Empty;
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.D)
|
||||
else if (key.Key == ConsoleKey.G)
|
||||
{
|
||||
if (_selectedIndex >= 0 && _selectedIndex < _state.Channels.Count)
|
||||
_promptMode = PromptMode.CreateGroup;
|
||||
_inputBuffer = string.Empty;
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.M)
|
||||
{
|
||||
_promptMode = PromptMode.StartDm;
|
||||
_inputBuffer = string.Empty;
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.I)
|
||||
{
|
||||
_promptMode = PromptMode.InviteGroup;
|
||||
_inputBuffer = string.Empty;
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.E)
|
||||
{
|
||||
if (_selectedIndex >= 0 && _selectedIndex < all.Count)
|
||||
{
|
||||
var selected = _state.Channels[_selectedIndex];
|
||||
if (selected.Name == "general")
|
||||
var selected = all[_selectedIndex];
|
||||
if (selected.Type == ChannelTypes.DirectMessage)
|
||||
{
|
||||
_state.SetStatus("Cannot delete the general channel.");
|
||||
await _connection.ToggleE2eeAsync("dm", !selected.IsE2ee, selected.Id);
|
||||
_state.SetStatus($"Toggled E2EE for DM @{selected.Name.TrimStart('@')}.");
|
||||
}
|
||||
else
|
||||
{
|
||||
await _connection.DeleteChannelAsync(selected.Id);
|
||||
_state.SetStatus($"Deleting #{selected.Name}...");
|
||||
_state.SetStatus("Select a Direct Message to toggle per-DM E2EE (or press 'A' for account-wide E2EE).");
|
||||
}
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
else if (key.Key == ConsoleKey.A)
|
||||
{
|
||||
await _connection.ToggleE2eeAsync("account", !_state.AccountE2eeEnabled);
|
||||
_state.SetStatus($"Toggled account-wide E2EE to {(!_state.AccountE2eeEnabled ? "ON" : "OFF")}.");
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.L || key.Key == ConsoleKey.D)
|
||||
{
|
||||
if (_selectedIndex >= 0 && _selectedIndex < all.Count)
|
||||
{
|
||||
var selected = all[_selectedIndex];
|
||||
if (selected.Type == ChannelTypes.Group)
|
||||
{
|
||||
await _connection.LeaveGroupAsync(selected.Id);
|
||||
_state.SetStatus($"Left group '{selected.Name}'.");
|
||||
}
|
||||
else if (selected.Type == ChannelTypes.Channel)
|
||||
{
|
||||
if (selected.Name == "general")
|
||||
{
|
||||
_state.SetStatus("Cannot delete the general channel.");
|
||||
}
|
||||
else
|
||||
{
|
||||
await _connection.DeleteChannelAsync(selected.Id);
|
||||
_state.SetStatus($"Deleting #{selected.Name}...");
|
||||
}
|
||||
}
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ using System.Threading.Tasks;
|
|||
using GsDChat.Client.Network;
|
||||
using GsDChat.Client.Rendering;
|
||||
using GsDChat.Client.State;
|
||||
using GsDChat.Core.Models;
|
||||
|
||||
namespace GsDChat.Client.Screens;
|
||||
|
||||
|
|
@ -27,8 +28,53 @@ public class ChatScreen : IScreen
|
|||
public void Render(int width, int height, StringBuilder sb)
|
||||
{
|
||||
var ch = _state.ActiveChannel;
|
||||
string chName = ch != null ? $"#{ch.Name}" : "(no channel)";
|
||||
string topic = ch != null && !string.IsNullOrEmpty(ch.Topic) ? $" - {ch.Topic}" : "";
|
||||
string chName;
|
||||
string topic = "";
|
||||
|
||||
if (ch == null)
|
||||
{
|
||||
chName = "(no channel)";
|
||||
}
|
||||
else if (ch.Type == ChannelTypes.DirectMessage)
|
||||
{
|
||||
string e2eeTag;
|
||||
if (!_state.AllowDmE2ee)
|
||||
{
|
||||
e2eeTag = $"{Ansi.BrightYellow}[Plaintext / Server E2EE Off]{Ansi.Reset}";
|
||||
}
|
||||
else if (!_state.AccountE2eeEnabled || !ch.IsE2ee)
|
||||
{
|
||||
e2eeTag = $"{Ansi.BrightYellow}[⚠ Plaintext / E2EE Disabled]{Ansi.Reset}";
|
||||
}
|
||||
else if (!_state.HasUnlockedE2eeKey)
|
||||
{
|
||||
e2eeTag = $"{Ansi.BrightYellow}[🔑 E2EE Vault Locked — Enter PIN]{Ansi.Reset}";
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(_state.GetPeerPublicKeyForDm(ch)))
|
||||
{
|
||||
e2eeTag = $"{Ansi.BrightYellow}[⚠ Plaintext — Peer E2EE Not Set Up]{Ansi.Reset}";
|
||||
}
|
||||
else
|
||||
{
|
||||
e2eeTag = $"{Ansi.BrightGreen}[🔒 Full E2EE]{Ansi.Reset}";
|
||||
}
|
||||
chName = $"DM @{ch.Name.TrimStart('@')}";
|
||||
topic = $" {e2eeTag}";
|
||||
}
|
||||
else if (ch.Type == ChannelTypes.Group)
|
||||
{
|
||||
int maxU = ch.MaxUsers > 0 ? ch.MaxUsers : _state.MaxGroupChatUsers;
|
||||
string membersList = ch.MemberUsernames.Count > 0 ? string.Join(", @", ch.MemberUsernames) : "";
|
||||
chName = $"[Group] {ch.Name} ({ch.MemberIds.Count}/{maxU})";
|
||||
topic = !string.IsNullOrEmpty(ch.Topic)
|
||||
? $" - {ch.Topic}"
|
||||
: (!string.IsNullOrEmpty(membersList) ? $" - @{membersList}" : "");
|
||||
}
|
||||
else
|
||||
{
|
||||
chName = $"#{ch.Name}";
|
||||
topic = !string.IsNullOrEmpty(ch.Topic) ? $" - {ch.Topic}" : "";
|
||||
}
|
||||
|
||||
// Header line
|
||||
int onlineCount = _state.Users.Count(u => u.IsOnline);
|
||||
|
|
@ -40,12 +86,10 @@ public class ChatScreen : IScreen
|
|||
// Messages area: height minus (Header: 2, Footer/Input: 3, Tab bar & status: 3) = height - 8
|
||||
int msgAreaHeight = Math.Max(3, height - 8);
|
||||
|
||||
List<Core.Models.ChatMessage> messages = new();
|
||||
if (!string.IsNullOrEmpty(_state.ActiveChannelId) &&
|
||||
_state.ChannelMessages.TryGetValue(_state.ActiveChannelId, out var msgs))
|
||||
{
|
||||
messages = msgs;
|
||||
}
|
||||
List<ChatMessage> messages = _state.GetMessagesForChannel(_state.ActiveChannelId);
|
||||
|
||||
bool hasMore = !string.IsNullOrEmpty(_state.ActiveChannelId) &&
|
||||
_state.ChannelHasMoreHistory.TryGetValue(_state.ActiveChannelId, out bool hm) && hm;
|
||||
|
||||
// Viewport calculation with scroll offset
|
||||
int totalMessages = messages.Count;
|
||||
|
|
@ -56,8 +100,14 @@ public class ChatScreen : IScreen
|
|||
|
||||
var visible = messages.Skip(startIndex).Take(countToTake).ToList();
|
||||
|
||||
// Print blank lines if fewer messages than viewport height
|
||||
int emptyLines = msgAreaHeight - visible.Count;
|
||||
if (startIndex == 0 && hasMore && emptyLines > 0)
|
||||
{
|
||||
sb.AppendLine($" {Ansi.Gray}[↑ Press PageUp or /history to load older messages from server ↑]{Ansi.Reset}");
|
||||
emptyLines--;
|
||||
}
|
||||
|
||||
// Print blank lines if fewer messages than viewport height
|
||||
for (int i = 0; i < emptyLines; i++)
|
||||
{
|
||||
sb.AppendLine();
|
||||
|
|
@ -70,17 +120,31 @@ public class ChatScreen : IScreen
|
|||
{
|
||||
"Owner" => Ansi.BrightYellow,
|
||||
"Admin" => Ansi.BrightMagenta,
|
||||
"System" => Ansi.BrightGreen,
|
||||
_ => Ansi.BrightCyan
|
||||
};
|
||||
|
||||
string line;
|
||||
if (!string.IsNullOrEmpty(msg.AttachmentId))
|
||||
string lockBadge = msg.IsEncrypted ? $"{Ansi.BrightGreen}🔒 {Ansi.Reset}" : "";
|
||||
string displayContent = msg.Content;
|
||||
if (displayContent.StartsWith("E2EE:v1:", StringComparison.Ordinal))
|
||||
{
|
||||
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} <{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {Ansi.BrightYellow}📎 [{msg.AttachmentName} - {FileStorageServiceFormat(msg.AttachmentSizeBytes ?? 0)}]{Ansi.Reset}";
|
||||
displayContent = !_state.HasUnlockedE2eeKey
|
||||
? $"{Ansi.BrightYellow}[🔒 Encrypted Message — Enter E2EE PIN or '/e2ee pin <pin>' to unlock]{Ansi.Reset}"
|
||||
: $"{Ansi.BrightYellow}[🔒 Encrypted with previous E2EE key]{Ansi.Reset}";
|
||||
}
|
||||
|
||||
string line;
|
||||
if (msg.SenderRole == "System")
|
||||
{
|
||||
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} {Ansi.BrightGreen}*** {msg.Content}{Ansi.Reset}";
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(msg.AttachmentId))
|
||||
{
|
||||
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} {lockBadge}<{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {Ansi.BrightYellow}📎 [{msg.AttachmentName} - {FileStorageServiceFormat(msg.AttachmentSizeBytes ?? 0)}]{Ansi.Reset}";
|
||||
}
|
||||
else
|
||||
{
|
||||
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} <{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {msg.Content}";
|
||||
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} {lockBadge}<{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {displayContent}";
|
||||
}
|
||||
|
||||
sb.AppendLine(PadOrTruncate(line, width));
|
||||
|
|
@ -89,14 +153,68 @@ public class ChatScreen : IScreen
|
|||
// Divider
|
||||
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
||||
|
||||
// Input Line
|
||||
string prompt = $" {Ansi.Cyan}[{chName}] > {Ansi.Reset}";
|
||||
string inputDisplay = _state.InputBuffer + "█";
|
||||
sb.AppendLine(prompt + inputDisplay);
|
||||
// Input Line or Lazy E2EE PIN Prompt
|
||||
if (_state.IsPromptingE2eePin)
|
||||
{
|
||||
string pinPromptLabel = _state.HasServerKeyVault
|
||||
? $"{Ansi.BrightYellow}[🔑 Unlock E2EE Key Vault] Enter E2EE PIN (Esc=Plaintext): {Ansi.Reset}"
|
||||
: $"{Ansi.BrightGreen}[🔑 Setup E2EE Key Vault] Create E2EE PIN (Esc=Plaintext): {Ansi.Reset}";
|
||||
string maskedPin = new string('*', _state.E2eePinInputBuffer.Length) + "█";
|
||||
sb.AppendLine($" {pinPromptLabel}{maskedPin}");
|
||||
}
|
||||
else
|
||||
{
|
||||
string prompt = $" {Ansi.Cyan}[{chName}] > {Ansi.Reset}";
|
||||
string inputDisplay = _state.InputBuffer + "█";
|
||||
sb.AppendLine(prompt + inputDisplay);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task HandleKeyAsync(ConsoleKeyInfo key)
|
||||
{
|
||||
if (_state.IsPromptingE2eePin)
|
||||
{
|
||||
if (key.Key == ConsoleKey.Enter)
|
||||
{
|
||||
string pin = _state.E2eePinInputBuffer.Trim();
|
||||
_state.E2eePinInputBuffer = string.Empty;
|
||||
if (string.IsNullOrEmpty(pin))
|
||||
{
|
||||
_state.SetStatus("PIN cannot be empty (Press Esc to skip and use plaintext).");
|
||||
return;
|
||||
}
|
||||
|
||||
var (ok, msg) = await _connection.UnlockOrInitializeE2eeWithPinAsync(pin, resetKeys: false);
|
||||
_state.SetStatus(msg, 5);
|
||||
if (ok)
|
||||
{
|
||||
_state.IsPromptingE2eePin = false;
|
||||
}
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.Escape)
|
||||
{
|
||||
_state.IsPromptingE2eePin = false;
|
||||
_state.E2eePinInputBuffer = string.Empty;
|
||||
_state.SetStatus("E2EE PIN prompt skipped. Use '/e2ee pin <pin>' anytime to unlock.");
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.Backspace)
|
||||
{
|
||||
if (_state.E2eePinInputBuffer.Length > 0)
|
||||
{
|
||||
_state.E2eePinInputBuffer = _state.E2eePinInputBuffer[..^1];
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
else if (!char.IsControl(key.KeyChar))
|
||||
{
|
||||
_state.E2eePinInputBuffer += key.KeyChar;
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.Key == ConsoleKey.Enter)
|
||||
{
|
||||
string text = _state.InputBuffer.Trim();
|
||||
|
|
@ -133,6 +251,13 @@ public class ChatScreen : IScreen
|
|||
else if (key.Key == ConsoleKey.PageUp)
|
||||
{
|
||||
_state.ChatScrollOffset += 5;
|
||||
if (!string.IsNullOrEmpty(_state.ActiveChannelId) &&
|
||||
_state.ChannelHasMoreHistory.TryGetValue(_state.ActiveChannelId, out bool hasMore) &&
|
||||
hasMore)
|
||||
{
|
||||
await _connection.FetchOlderHistoryAsync(_state.ActiveChannelId, 50);
|
||||
_state.SetStatus("Loading older messages from server...", 2);
|
||||
}
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
else if (key.Key == ConsoleKey.PageDown)
|
||||
|
|
@ -163,18 +288,21 @@ public class ChatScreen : IScreen
|
|||
case "join":
|
||||
if (string.IsNullOrEmpty(args))
|
||||
{
|
||||
_state.SetStatus("Usage: /join <channel_name>");
|
||||
_state.SetStatus("Usage: /join <channel_or_group_or_dm>");
|
||||
return;
|
||||
}
|
||||
var target = _state.Channels.FirstOrDefault(c => c.Name.Equals(args.TrimStart('#'), StringComparison.OrdinalIgnoreCase));
|
||||
string cleanTarget = args.TrimStart('#', '@');
|
||||
var target = _state.Channels.FirstOrDefault(c => c.Name.Equals(cleanTarget, StringComparison.OrdinalIgnoreCase))
|
||||
?? _state.GroupChats.FirstOrDefault(g => g.Name.Equals(cleanTarget, StringComparison.OrdinalIgnoreCase))
|
||||
?? _state.DirectMessages.FirstOrDefault(d => d.Name.TrimStart('@').Equals(cleanTarget, StringComparison.OrdinalIgnoreCase));
|
||||
if (target != null)
|
||||
{
|
||||
await _connection.JoinChannelAsync(target.Id);
|
||||
_state.SetStatus($"Joined #{target.Name}");
|
||||
_state.SetStatus($"Switched to {target.Name}");
|
||||
}
|
||||
else
|
||||
{
|
||||
_state.SetStatus($"Channel #{args} not found.");
|
||||
_state.SetStatus($"Conversation '{args}' not found.");
|
||||
}
|
||||
break;
|
||||
|
||||
|
|
@ -190,6 +318,117 @@ public class ChatScreen : IScreen
|
|||
await _connection.CreateChannelAsync(newName, newTopic);
|
||||
break;
|
||||
|
||||
case "dm":
|
||||
if (string.IsNullOrEmpty(args))
|
||||
{
|
||||
_state.SetStatus("Usage: /dm <username> [message]");
|
||||
return;
|
||||
}
|
||||
var dmParts = args.Split(' ', 2);
|
||||
string dmUser = dmParts[0].TrimStart('@');
|
||||
await _connection.StartDmAsync(dmUser);
|
||||
_state.SetStatus($"Opening DM with @{dmUser}...");
|
||||
if (dmParts.Length > 1 && !string.IsNullOrWhiteSpace(dmParts[1]))
|
||||
{
|
||||
await Task.Delay(100);
|
||||
var dmConv = _state.DirectMessages.FirstOrDefault(d => d.Name.TrimStart('@').Equals(dmUser, StringComparison.OrdinalIgnoreCase));
|
||||
if (dmConv != null)
|
||||
{
|
||||
await _connection.SendChatMessageAsync(dmConv.Id, dmParts[1]);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case "e2ee":
|
||||
var e2eeTokens = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (e2eeTokens.Length == 0)
|
||||
{
|
||||
_state.IsPromptingE2eePin = true;
|
||||
_state.NeedsRedraw = true;
|
||||
return;
|
||||
}
|
||||
string e2eeSub = e2eeTokens[0].ToLowerInvariant();
|
||||
string e2eeArg = e2eeTokens.Length > 1 ? e2eeTokens[1].Trim() : string.Empty;
|
||||
if ((e2eeSub == "pin" || e2eeSub == "unlock") && !string.IsNullOrEmpty(e2eeArg))
|
||||
{
|
||||
var (ok, msg) = await _connection.UnlockOrInitializeE2eeWithPinAsync(e2eeArg, resetKeys: false);
|
||||
_state.SetStatus(msg, 5);
|
||||
}
|
||||
else if (e2eeSub == "reset" && !string.IsNullOrEmpty(e2eeArg))
|
||||
{
|
||||
var (ok, msg) = await _connection.UnlockOrInitializeE2eeWithPinAsync(e2eeArg, resetKeys: true);
|
||||
_state.SetStatus(msg, 5);
|
||||
}
|
||||
else if (e2eeSub == "lock")
|
||||
{
|
||||
_connection.LockE2eeKeys();
|
||||
}
|
||||
else if ((e2eeSub == "dm" || e2eeSub == "account") && !string.IsNullOrEmpty(e2eeArg))
|
||||
{
|
||||
bool enable = e2eeArg.Equals("on", StringComparison.OrdinalIgnoreCase) ||
|
||||
e2eeArg.Equals("true", StringComparison.OrdinalIgnoreCase) ||
|
||||
e2eeArg.Equals("1", StringComparison.OrdinalIgnoreCase);
|
||||
await _connection.ToggleE2eeAsync(e2eeSub, enable, _state.ActiveChannelId);
|
||||
}
|
||||
else
|
||||
{
|
||||
_state.SetStatus("Usage: /e2ee pin <pin> | /e2ee reset <new_pin> | /e2ee lock | /e2ee dm <on|off> | /e2ee account <on|off>", 6);
|
||||
}
|
||||
break;
|
||||
|
||||
case "history":
|
||||
case "more":
|
||||
if (!string.IsNullOrEmpty(_state.ActiveChannelId))
|
||||
{
|
||||
await _connection.FetchOlderHistoryAsync(_state.ActiveChannelId, 50);
|
||||
_state.SetStatus("Fetching older history from server...", 3);
|
||||
}
|
||||
break;
|
||||
|
||||
case "group":
|
||||
case "gcreate":
|
||||
string gArgs = cmd == "gcreate" ? $"create {args}" : args;
|
||||
var gTokens = gArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (gTokens.Length == 0)
|
||||
{
|
||||
_state.SetStatus("Usage: /group create <name> [user1,user2] | /group invite <user> | /group leave");
|
||||
return;
|
||||
}
|
||||
string sub = gTokens[0].ToLowerInvariant();
|
||||
if (sub == "create" && gTokens.Length >= 2)
|
||||
{
|
||||
string gName = gTokens[1];
|
||||
var members = gTokens.Skip(2).ToList();
|
||||
await _connection.CreateGroupChatAsync(gName, members);
|
||||
_state.SetStatus($"Creating group '{gName}'...");
|
||||
}
|
||||
else if (sub == "invite" && gTokens.Length >= 2)
|
||||
{
|
||||
await _connection.InviteToGroupAsync(_state.ActiveChannelId, gTokens[1]);
|
||||
}
|
||||
else if (sub == "leave")
|
||||
{
|
||||
await _connection.LeaveGroupAsync(_state.ActiveChannelId);
|
||||
}
|
||||
else
|
||||
{
|
||||
_state.SetStatus("Usage: /group create <name> [user1,user2] | /group invite <user> | /group leave");
|
||||
}
|
||||
break;
|
||||
|
||||
case "invite":
|
||||
if (string.IsNullOrEmpty(args))
|
||||
{
|
||||
_state.SetStatus("Usage: /invite <username>");
|
||||
return;
|
||||
}
|
||||
await _connection.InviteToGroupAsync(_state.ActiveChannelId, args);
|
||||
break;
|
||||
|
||||
case "leave":
|
||||
await _connection.LeaveGroupAsync(_state.ActiveChannelId);
|
||||
break;
|
||||
|
||||
case "upload":
|
||||
if (string.IsNullOrEmpty(args))
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using GsDChat.Client.Network;
|
||||
using GsDChat.Client.Rendering;
|
||||
using GsDChat.Client.State;
|
||||
|
||||
|
|
@ -9,15 +11,17 @@ namespace GsDChat.Client.Screens;
|
|||
public class UsersScreen : IScreen
|
||||
{
|
||||
private readonly ClientState _state;
|
||||
private readonly ChatClientConnection? _connection;
|
||||
private int _selectedIndex = 0;
|
||||
|
||||
public string ScreenId => "F3_Users";
|
||||
public string Title => "Users";
|
||||
public string ShortcutKey => "F3";
|
||||
|
||||
public UsersScreen(ClientState state)
|
||||
public UsersScreen(ClientState state, ChatClientConnection? connection = null)
|
||||
{
|
||||
_state = state;
|
||||
_connection = connection;
|
||||
}
|
||||
|
||||
public void Render(int width, int height, StringBuilder sb)
|
||||
|
|
@ -48,19 +52,23 @@ public class UsersScreen : IScreen
|
|||
_ => $"{Ansi.Gray}[Member]{Ansi.Reset}"
|
||||
};
|
||||
|
||||
string keyBadge = (!string.IsNullOrWhiteSpace(u.PublicKey) && _state.AllowDmE2ee)
|
||||
? $" {Ansi.BrightGreen}[🔒 E2EE Ready]{Ansi.Reset}"
|
||||
: "";
|
||||
|
||||
string prefix = isSelected ? $"{Ansi.BrightCyan}► " : " ";
|
||||
string userDisplay = isSelected
|
||||
? $"{Ansi.Inverse}@{u.Username}{Ansi.Reset}"
|
||||
: $"@{u.Username}";
|
||||
|
||||
sb.AppendLine($"{prefix}{statusDot} {userDisplay} {roleBadge}");
|
||||
sb.AppendLine($"{prefix}{statusDot} {userDisplay} {roleBadge}{keyBadge}");
|
||||
}
|
||||
|
||||
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
||||
sb.AppendLine($" {Ansi.Gray}[↑/↓] Scroll Directory{Ansi.Reset}");
|
||||
sb.AppendLine($" {Ansi.Gray}[↑/↓] Scroll Directory [Enter / M] Start Direct Message{Ansi.Reset}");
|
||||
}
|
||||
|
||||
public Task HandleKeyAsync(ConsoleKeyInfo key)
|
||||
public async Task HandleKeyAsync(ConsoleKeyInfo key)
|
||||
{
|
||||
if (key.Key == ConsoleKey.UpArrow)
|
||||
{
|
||||
|
|
@ -72,6 +80,16 @@ public class UsersScreen : IScreen
|
|||
_selectedIndex = Math.Min(_state.Users.Count - 1, _selectedIndex + 1);
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
else if ((key.Key == ConsoleKey.Enter || key.Key == ConsoleKey.M) && _connection != null)
|
||||
{
|
||||
if (_selectedIndex >= 0 && _selectedIndex < _state.Users.Count)
|
||||
{
|
||||
var u = _state.Users[_selectedIndex];
|
||||
await _connection.StartDmAsync(u.Username, u.Id);
|
||||
_state.ActiveScreenId = "F1_Chat";
|
||||
_state.SetStatus($"Opened Direct Message with @{u.Username}");
|
||||
_state.NeedsRedraw = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,28 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GsDChat.Core.Models;
|
||||
|
||||
public static class ChannelTypes
|
||||
{
|
||||
public const string Channel = "Channel";
|
||||
public const string DirectMessage = "DM";
|
||||
public const string Group = "Group";
|
||||
}
|
||||
|
||||
public class Channel
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString("N");
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Topic { get; set; } = string.Empty;
|
||||
public string Type { get; set; } = ChannelTypes.Channel;
|
||||
public bool IsPrivate { get; set; } = false;
|
||||
public bool IsE2ee { get; set; } = false;
|
||||
public string CreatorId { get; set; } = string.Empty;
|
||||
public int MaxUsers { get; set; } = 0;
|
||||
public string AllowedRoles { get; set; } = string.Empty; // Comma-separated or empty for public
|
||||
public List<string> MemberIds { get; set; } = new();
|
||||
public List<string> MemberUsernames { get; set; } = new();
|
||||
public Dictionary<string, string> MemberPublicKeys { get; set; } = new();
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,9 @@ public class ChatMessage
|
|||
public string SenderUsername { get; set; } = string.Empty;
|
||||
public string SenderRole { get; set; } = UserRoles.Member;
|
||||
public string Content { get; set; } = string.Empty;
|
||||
public bool IsEncrypted { get; set; } = false;
|
||||
public string? SenderPublicKey { get; set; }
|
||||
public string? RecipientPublicKey { get; set; }
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public string? AttachmentId { get; set; }
|
||||
public string? AttachmentName { get; set; }
|
||||
|
|
|
|||
|
|
@ -16,6 +16,9 @@ public class User
|
|||
public string PasswordHash { get; set; } = string.Empty;
|
||||
public string PasswordSalt { get; set; } = string.Empty;
|
||||
public string Role { get; set; } = UserRoles.Member;
|
||||
public string? PublicKey { get; set; }
|
||||
public string? EncryptedPrivateKey { get; set; }
|
||||
public bool E2eeEnabled { get; set; } = true;
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public bool IsBanned { get; set; } = false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ public class RegisterRequest
|
|||
public string Password { get; set; } = string.Empty;
|
||||
public string? ServerPassword { get; set; }
|
||||
public string? InviteToken { get; set; }
|
||||
public string? PublicKey { get; set; }
|
||||
public string? EncryptedPrivateKey { get; set; }
|
||||
}
|
||||
|
||||
public class LoginRequest
|
||||
|
|
@ -15,6 +17,8 @@ public class LoginRequest
|
|||
public string Username { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
public string? ServerPassword { get; set; }
|
||||
public string? PublicKey { get; set; }
|
||||
public string? EncryptedPrivateKey { get; set; }
|
||||
}
|
||||
|
||||
public class AuthResponse
|
||||
|
|
@ -24,6 +28,9 @@ public class AuthResponse
|
|||
public string? UserId { get; set; }
|
||||
public string? Username { get; set; }
|
||||
public string? Role { get; set; }
|
||||
public string? PublicKey { get; set; }
|
||||
public string? EncryptedPrivateKey { get; set; }
|
||||
public bool E2eeEnabled { get; set; } = true;
|
||||
public string? ErrorMessage { get; set; }
|
||||
}
|
||||
|
||||
|
|
@ -36,6 +43,8 @@ public class ServerInfoResponse
|
|||
public string Motd { get; set; } = "Welcome to GsDChat!";
|
||||
public long MaxFileSizeMb { get; set; } = 50;
|
||||
public bool AllowMemberChannelCreation { get; set; } = true;
|
||||
public bool AllowDmE2ee { get; set; } = true;
|
||||
public int MaxGroupChatUsers { get; set; } = 10;
|
||||
}
|
||||
|
||||
public class UploadFileResponse
|
||||
|
|
|
|||
|
|
@ -17,6 +17,13 @@ public static class MessageTypes
|
|||
public const string ChannelListSync = "CHANNEL_LIST_SYNC";
|
||||
public const string CreateChannel = "CREATE_CHANNEL";
|
||||
public const string DeleteChannel = "DELETE_CHANNEL";
|
||||
public const string StartDm = "START_DM";
|
||||
public const string CreateGroup = "CREATE_GROUP";
|
||||
public const string InviteToGroup = "INVITE_TO_GROUP";
|
||||
public const string LeaveGroup = "LEAVE_GROUP";
|
||||
public const string PublishPublicKey = "PUBLISH_PUBLIC_KEY";
|
||||
public const string ToggleE2ee = "TOGGLE_E2EE";
|
||||
public const string FetchHistory = "FETCH_HISTORY";
|
||||
public const string UserListSync = "USER_LIST_SYNC";
|
||||
public const string FileListSync = "FILE_LIST_SYNC";
|
||||
public const string SystemNotice = "SYSTEM_NOTICE";
|
||||
|
|
@ -68,6 +75,9 @@ public class AuthResultPacket
|
|||
public string UserId { get; set; } = string.Empty;
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string Role { get; set; } = UserRoles.Member;
|
||||
public string? PublicKey { get; set; }
|
||||
public string? EncryptedPrivateKey { get; set; }
|
||||
public bool E2eeEnabled { get; set; } = true;
|
||||
public string? ErrorMessage { get; set; }
|
||||
public ServerUiSync? UiSync { get; set; }
|
||||
public string? ActiveChannelId { get; set; }
|
||||
|
|
@ -77,6 +87,9 @@ public class SendMessagePacket
|
|||
{
|
||||
public string ChannelId { get; set; } = string.Empty;
|
||||
public string Content { get; set; } = string.Empty;
|
||||
public bool IsEncrypted { get; set; } = false;
|
||||
public string? SenderPublicKey { get; set; }
|
||||
public string? RecipientPublicKey { get; set; }
|
||||
}
|
||||
|
||||
public class MessageBroadcastPacket
|
||||
|
|
@ -88,6 +101,16 @@ public class HistorySyncPacket
|
|||
{
|
||||
public string ChannelId { get; set; } = string.Empty;
|
||||
public List<ChatMessage> Messages { get; set; } = new();
|
||||
public bool Prepend { get; set; } = false;
|
||||
public bool HasMore { get; set; } = false;
|
||||
public int Offset { get; set; } = 0;
|
||||
}
|
||||
|
||||
public class FetchHistoryPacket
|
||||
{
|
||||
public string ChannelId { get; set; } = string.Empty;
|
||||
public int Offset { get; set; } = 0;
|
||||
public int Limit { get; set; } = 50;
|
||||
}
|
||||
|
||||
public class JoinChannelPacket
|
||||
|
|
@ -98,6 +121,8 @@ public class JoinChannelPacket
|
|||
public class ChannelListSyncPacket
|
||||
{
|
||||
public List<Channel> Channels { get; set; } = new();
|
||||
public List<Channel> DirectMessages { get; set; } = new();
|
||||
public List<Channel> GroupChats { get; set; } = new();
|
||||
public string ActiveChannelId { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
|
|
@ -112,12 +137,53 @@ public class DeleteChannelPacket
|
|||
public string ChannelId { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class StartDmPacket
|
||||
{
|
||||
public string TargetUserId { get; set; } = string.Empty;
|
||||
public string TargetUsername { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class CreateGroupPacket
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Topic { get; set; } = string.Empty;
|
||||
public List<string> MemberUsernames { get; set; } = new();
|
||||
public int? MaxUsers { get; set; }
|
||||
}
|
||||
|
||||
public class InviteToGroupPacket
|
||||
{
|
||||
public string ChannelId { get; set; } = string.Empty;
|
||||
public string TargetUsername { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class LeaveGroupPacket
|
||||
{
|
||||
public string ChannelId { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class PublishPublicKeyPacket
|
||||
{
|
||||
public string PublicKey { get; set; } = string.Empty;
|
||||
public string? EncryptedPrivateKey { get; set; }
|
||||
public bool ResetKeys { get; set; } = false;
|
||||
}
|
||||
|
||||
public class ToggleE2eePacket
|
||||
{
|
||||
public string Scope { get; set; } = "dm"; // "dm" or "account"
|
||||
public string? ChannelId { get; set; }
|
||||
public bool Enabled { get; set; } = true;
|
||||
}
|
||||
|
||||
public class UserSummary
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string Role { get; set; } = UserRoles.Member;
|
||||
public bool IsOnline { get; set; }
|
||||
public string? PublicKey { get; set; }
|
||||
public bool E2eeEnabled { get; set; } = true;
|
||||
}
|
||||
|
||||
public class UserListSyncPacket
|
||||
|
|
@ -164,4 +230,5 @@ public class CommandResultPacket
|
|||
{
|
||||
public bool Success { get; set; }
|
||||
public string Output { get; set; } = string.Empty;
|
||||
public string ChannelId { get; set; } = string.Empty;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,15 +38,23 @@ public class ServerUiSync
|
|||
{
|
||||
public string ServerName { get; set; } = "GsDChat Server";
|
||||
public string Motd { get; set; } = "Welcome to GsDChat!";
|
||||
public bool AllowDmE2ee { get; set; } = true;
|
||||
public int MaxGroupChatUsers { get; set; } = 10;
|
||||
public ThemeDefinition Theme { get; set; } = new();
|
||||
public List<ScreenDefinition> Screens { get; set; } = new();
|
||||
|
||||
public static ServerUiSync CreateDefault(string serverName = "GsDChat Server", string motd = "Welcome to GsDChat!")
|
||||
public static ServerUiSync CreateDefault(
|
||||
string serverName = "GsDChat Server",
|
||||
string motd = "Welcome to GsDChat!",
|
||||
bool allowDmE2ee = true,
|
||||
int maxGroupChatUsers = 10)
|
||||
{
|
||||
return new ServerUiSync
|
||||
{
|
||||
ServerName = serverName,
|
||||
Motd = motd,
|
||||
AllowDmE2ee = allowDmE2ee,
|
||||
MaxGroupChatUsers = maxGroupChatUsers,
|
||||
Theme = new ThemeDefinition(),
|
||||
Screens = new List<ScreenDefinition>
|
||||
{
|
||||
|
|
|
|||
184
src/GsDChat.Core/Security/E2eeCrypto.cs
Normal file
184
src/GsDChat.Core/Security/E2eeCrypto.cs
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace GsDChat.Core.Security;
|
||||
|
||||
public static class E2eeCrypto
|
||||
{
|
||||
public const string EncryptedPrefix = "E2EE:v1:";
|
||||
private const string WrappedKeyPrefix = "WRAP:v1:";
|
||||
private const int NonceByteLength = 12;
|
||||
private const int TagByteLength = 16;
|
||||
private const int KeyWrapIterations = 100_000;
|
||||
|
||||
public static (string PublicKeyBase64, string PrivateKeyBase64) GenerateKeyPair()
|
||||
{
|
||||
using var ecdh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);
|
||||
byte[] pubBytes = ecdh.ExportSubjectPublicKeyInfo();
|
||||
byte[] privBytes = ecdh.ExportPkcs8PrivateKey();
|
||||
return (Convert.ToBase64String(pubBytes), Convert.ToBase64String(privBytes));
|
||||
}
|
||||
|
||||
public static string ExtractPublicKeyFromPrivateKey(string privateKeyBase64)
|
||||
{
|
||||
byte[] privBytes = Convert.FromBase64String(privateKeyBase64);
|
||||
using var ecdh = ECDiffieHellman.Create();
|
||||
ecdh.ImportPkcs8PrivateKey(privBytes, out _);
|
||||
byte[] pubBytes = ecdh.ExportSubjectPublicKeyInfo();
|
||||
return Convert.ToBase64String(pubBytes);
|
||||
}
|
||||
|
||||
public static string WrapPrivateKey(string privateKeyBase64, string password, string username)
|
||||
{
|
||||
byte[] wrapKey = DeriveWrappingKey(password, username);
|
||||
byte[] nonce = RandomNumberGenerator.GetBytes(NonceByteLength);
|
||||
byte[] plaintext = Encoding.UTF8.GetBytes(privateKeyBase64);
|
||||
byte[] ciphertext = new byte[plaintext.Length];
|
||||
byte[] tag = new byte[TagByteLength];
|
||||
|
||||
using var aes = new AesGcm(wrapKey, TagByteLength);
|
||||
aes.Encrypt(nonce, plaintext, ciphertext, tag);
|
||||
|
||||
byte[] combined = new byte[ciphertext.Length + tag.Length];
|
||||
Buffer.BlockCopy(ciphertext, 0, combined, 0, ciphertext.Length);
|
||||
Buffer.BlockCopy(tag, 0, combined, ciphertext.Length, tag.Length);
|
||||
|
||||
return $"{WrappedKeyPrefix}{Convert.ToBase64String(nonce)}:{Convert.ToBase64String(combined)}";
|
||||
}
|
||||
|
||||
public static string? UnwrapPrivateKey(string? wrappedBlob, string password, string username)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(wrappedBlob) || !wrappedBlob.StartsWith(WrappedKeyPrefix, StringComparison.Ordinal))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string rest = wrappedBlob.Substring(WrappedKeyPrefix.Length);
|
||||
string[] parts = rest.Split(':', 2);
|
||||
if (parts.Length != 2) return null;
|
||||
|
||||
byte[] nonce = Convert.FromBase64String(parts[0]);
|
||||
byte[] combined = Convert.FromBase64String(parts[1]);
|
||||
if (combined.Length < TagByteLength) return null;
|
||||
|
||||
int cipherLen = combined.Length - TagByteLength;
|
||||
byte[] ciphertext = new byte[cipherLen];
|
||||
byte[] tag = new byte[TagByteLength];
|
||||
Buffer.BlockCopy(combined, 0, ciphertext, 0, cipherLen);
|
||||
Buffer.BlockCopy(combined, cipherLen, tag, 0, TagByteLength);
|
||||
|
||||
byte[] wrapKey = DeriveWrappingKey(password, username);
|
||||
byte[] plaintext = new byte[cipherLen];
|
||||
|
||||
using var aes = new AesGcm(wrapKey, TagByteLength);
|
||||
aes.Decrypt(nonce, ciphertext, tag, plaintext);
|
||||
|
||||
return Encoding.UTF8.GetString(plaintext);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] DeriveSharedAesKey(string myPrivateKeyBase64, string peerPublicKeyBase64)
|
||||
{
|
||||
byte[] privBytes = Convert.FromBase64String(myPrivateKeyBase64);
|
||||
byte[] pubBytes = Convert.FromBase64String(peerPublicKeyBase64);
|
||||
|
||||
using var myEcdh = ECDiffieHellman.Create();
|
||||
myEcdh.ImportPkcs8PrivateKey(privBytes, out _);
|
||||
|
||||
using var peerEcdh = ECDiffieHellman.Create();
|
||||
peerEcdh.ImportSubjectPublicKeyInfo(pubBytes, out _);
|
||||
|
||||
byte[] rawSecret = myEcdh.DeriveRawSecretAgreement(peerEcdh.PublicKey);
|
||||
return SHA256.HashData(rawSecret);
|
||||
}
|
||||
|
||||
public static string EncryptMessage(string plaintext, string myPrivateKeyBase64, string peerPublicKeyBase64)
|
||||
{
|
||||
byte[] aesKey = DeriveSharedAesKey(myPrivateKeyBase64, peerPublicKeyBase64);
|
||||
byte[] nonce = RandomNumberGenerator.GetBytes(NonceByteLength);
|
||||
byte[] plainBytes = Encoding.UTF8.GetBytes(plaintext);
|
||||
byte[] cipherBytes = new byte[plainBytes.Length];
|
||||
byte[] tag = new byte[TagByteLength];
|
||||
|
||||
using var aes = new AesGcm(aesKey, TagByteLength);
|
||||
aes.Encrypt(nonce, plainBytes, cipherBytes, tag);
|
||||
|
||||
byte[] combined = new byte[cipherBytes.Length + tag.Length];
|
||||
Buffer.BlockCopy(cipherBytes, 0, combined, 0, cipherBytes.Length);
|
||||
Buffer.BlockCopy(tag, 0, combined, cipherBytes.Length, tag.Length);
|
||||
|
||||
return $"{EncryptedPrefix}{Convert.ToBase64String(nonce)}:{Convert.ToBase64String(combined)}";
|
||||
}
|
||||
|
||||
public static string DecryptMessage(string payload, string myPrivateKeyBase64, string peerPublicKeyBase64)
|
||||
{
|
||||
if (!IsEncryptedPayload(payload))
|
||||
{
|
||||
return payload;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(myPrivateKeyBase64) || string.IsNullOrWhiteSpace(peerPublicKeyBase64))
|
||||
{
|
||||
return "[Encrypted Message - Key Unavailable]";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string rest = payload.Substring(EncryptedPrefix.Length);
|
||||
string[] parts = rest.Split(':', 2);
|
||||
if (parts.Length != 2)
|
||||
{
|
||||
return "[Encrypted Message - Malformed]";
|
||||
}
|
||||
|
||||
byte[] nonce = Convert.FromBase64String(parts[0]);
|
||||
byte[] combined = Convert.FromBase64String(parts[1]);
|
||||
if (combined.Length < TagByteLength)
|
||||
{
|
||||
return "[Encrypted Message - Invalid Tag]";
|
||||
}
|
||||
|
||||
int cipherLen = combined.Length - TagByteLength;
|
||||
byte[] cipherBytes = new byte[cipherLen];
|
||||
byte[] tag = new byte[TagByteLength];
|
||||
Buffer.BlockCopy(combined, 0, cipherBytes, 0, cipherLen);
|
||||
Buffer.BlockCopy(combined, cipherLen, tag, 0, TagByteLength);
|
||||
|
||||
byte[] aesKey = DeriveSharedAesKey(myPrivateKeyBase64, peerPublicKeyBase64);
|
||||
byte[] plainBytes = new byte[cipherLen];
|
||||
|
||||
using var aes = new AesGcm(aesKey, TagByteLength);
|
||||
aes.Decrypt(nonce, cipherBytes, tag, plainBytes);
|
||||
|
||||
return Encoding.UTF8.GetString(plainBytes);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "[Encrypted Message - Decryption Failed]";
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsEncryptedPayload(string? content)
|
||||
{
|
||||
return !string.IsNullOrEmpty(content) && content.StartsWith(EncryptedPrefix, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static byte[] DeriveWrappingKey(string password, string username)
|
||||
{
|
||||
byte[] salt = SHA256.HashData(Encoding.UTF8.GetBytes($"GsDChat-E2EE-KeyWrap:{username.Trim().ToLowerInvariant()}"));
|
||||
return Rfc2898DeriveBytes.Pbkdf2(
|
||||
password,
|
||||
salt,
|
||||
KeyWrapIterations,
|
||||
HashAlgorithmName.SHA256,
|
||||
32
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -14,4 +14,6 @@ public class ServerOptions
|
|||
public string ServerName { get; set; } = "GsDChat Community Server";
|
||||
public string Motd { get; set; } = "Welcome to GsDChat! Enjoy private, modular messaging.";
|
||||
public bool AllowMemberChannelCreation { get; set; } = true;
|
||||
public bool AllowDmE2ee { get; set; } = true;
|
||||
public int MaxGroupChatUsers { get; set; } = 10;
|
||||
}
|
||||
|
|
|
|||
112
src/GsDChat.Server/Configuration/ServerSettingsManager.cs
Normal file
112
src/GsDChat.Server/Configuration/ServerSettingsManager.cs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace GsDChat.Server.Configuration;
|
||||
|
||||
public class ServerSettingsManager
|
||||
{
|
||||
private static readonly JsonSerializerOptions s_readOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true
|
||||
};
|
||||
|
||||
private static readonly JsonSerializerOptions s_writeOptions = new()
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
public string FilePath { get; }
|
||||
|
||||
public ServerSettingsManager(string? customFilePath = null)
|
||||
{
|
||||
FilePath = ResolveSettingsFilePath(customFilePath);
|
||||
}
|
||||
|
||||
public static string ResolveSettingsFilePath(string? customFilePath = null, string[]? args = null)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(customFilePath))
|
||||
{
|
||||
return Path.GetFullPath(customFilePath);
|
||||
}
|
||||
|
||||
if (args != null)
|
||||
{
|
||||
for (int i = 0; i < args.Length - 1; i++)
|
||||
{
|
||||
if (args[i] == "--settings" && !string.IsNullOrWhiteSpace(args[i + 1]))
|
||||
{
|
||||
return Path.GetFullPath(args[i + 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
string? envPath = Environment.GetEnvironmentVariable("GSDCHAT_SETTINGS_FILE");
|
||||
if (!string.IsNullOrWhiteSpace(envPath))
|
||||
{
|
||||
return Path.GetFullPath(envPath);
|
||||
}
|
||||
|
||||
string cwdSettings = Path.Combine(Directory.GetCurrentDirectory(), "serversettings.json");
|
||||
if (File.Exists(cwdSettings))
|
||||
{
|
||||
return cwdSettings;
|
||||
}
|
||||
|
||||
return Path.Combine(AppContext.BaseDirectory, "serversettings.json");
|
||||
}
|
||||
|
||||
public ServerOptions LoadOrCreate()
|
||||
{
|
||||
var options = new ServerOptions();
|
||||
|
||||
if (File.Exists(FilePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
string json = File.ReadAllText(FilePath);
|
||||
if (!string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
var loaded = JsonSerializer.Deserialize<ServerOptions>(json, s_readOptions);
|
||||
if (loaded != null)
|
||||
{
|
||||
options = loaded;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[Warning] Failed to read {FilePath}: {ex.Message}. Using defaults.");
|
||||
}
|
||||
}
|
||||
|
||||
if (options.MaxGroupChatUsers < 2)
|
||||
{
|
||||
options.MaxGroupChatUsers = 2;
|
||||
}
|
||||
|
||||
Save(options);
|
||||
return options;
|
||||
}
|
||||
|
||||
public void Save(ServerOptions options)
|
||||
{
|
||||
try
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(FilePath);
|
||||
if (!string.IsNullOrEmpty(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
|
||||
string json = JsonSerializer.Serialize(options, s_writeOptions);
|
||||
File.WriteAllText(FilePath, json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[Warning] Failed to persist settings to {FilePath}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using GsDChat.Core.Models;
|
||||
|
|
@ -41,19 +42,44 @@ public class ChatDatabase : IDisposable
|
|||
password_hash TEXT NOT NULL,
|
||||
password_salt TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
public_key TEXT,
|
||||
encrypted_private_key TEXT,
|
||||
e2ee_enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
is_banned INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS channels (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
name TEXT NOT NULL COLLATE NOCASE,
|
||||
topic TEXT NOT NULL,
|
||||
type TEXT NOT NULL DEFAULT 'Channel',
|
||||
is_private INTEGER NOT NULL DEFAULT 0,
|
||||
is_e2ee INTEGER NOT NULL DEFAULT 0,
|
||||
creator_id TEXT NOT NULL DEFAULT '',
|
||||
max_users INTEGER NOT NULL DEFAULT 0,
|
||||
allowed_roles TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_channels_public_name
|
||||
ON channels(name COLLATE NOCASE) WHERE type = 'Channel';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_channels_type_allowed_roles
|
||||
ON channels(type, allowed_roles);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS channel_members (
|
||||
channel_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
joined_at TEXT NOT NULL,
|
||||
PRIMARY KEY (channel_id, user_id),
|
||||
FOREIGN KEY (channel_id) REFERENCES channels (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_channel_members_user
|
||||
ON channel_members(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id TEXT PRIMARY KEY,
|
||||
channel_id TEXT NOT NULL,
|
||||
|
|
@ -61,6 +87,9 @@ public class ChatDatabase : IDisposable
|
|||
sender_username TEXT NOT NULL,
|
||||
sender_role TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
is_encrypted INTEGER NOT NULL DEFAULT 0,
|
||||
sender_public_key TEXT,
|
||||
recipient_public_key TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
attachment_id TEXT,
|
||||
attachment_name TEXT,
|
||||
|
|
@ -85,6 +114,7 @@ public class ChatDatabase : IDisposable
|
|||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_files_created ON files(created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_files_channel ON files(channel_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
|
|
@ -93,20 +123,27 @@ public class ChatDatabase : IDisposable
|
|||
expires_at TEXT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS server_settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
""";
|
||||
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = sql;
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
|
||||
// Ensure schema migrations for pre-existing databases
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE users ADD COLUMN public_key TEXT;");
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE users ADD COLUMN encrypted_private_key TEXT;");
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE users ADD COLUMN e2ee_enabled INTEGER NOT NULL DEFAULT 1;");
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE channels ADD COLUMN type TEXT NOT NULL DEFAULT 'Channel';");
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE channels ADD COLUMN is_e2ee INTEGER NOT NULL DEFAULT 0;");
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE channels ADD COLUMN creator_id TEXT NOT NULL DEFAULT '';");
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE channels ADD COLUMN max_users INTEGER NOT NULL DEFAULT 0;");
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE messages ADD COLUMN is_encrypted INTEGER NOT NULL DEFAULT 0;");
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE messages ADD COLUMN sender_public_key TEXT;");
|
||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE messages ADD COLUMN recipient_public_key TEXT;");
|
||||
|
||||
// Seed default channels if none exist
|
||||
var channelsCountCmd = conn.CreateCommand();
|
||||
channelsCountCmd.CommandText = "SELECT COUNT(*) FROM channels;";
|
||||
channelsCountCmd.CommandText = "SELECT COUNT(*) FROM channels WHERE type = 'Channel';";
|
||||
long count = (long)(await channelsCountCmd.ExecuteScalarAsync() ?? 0L);
|
||||
|
||||
if (count == 0)
|
||||
|
|
@ -115,6 +152,7 @@ public class ChatDatabase : IDisposable
|
|||
{
|
||||
Name = "general",
|
||||
Topic = "General discussion and chat",
|
||||
Type = ChannelTypes.Channel,
|
||||
IsPrivate = false,
|
||||
AllowedRoles = string.Empty
|
||||
});
|
||||
|
|
@ -123,24 +161,43 @@ public class ChatDatabase : IDisposable
|
|||
{
|
||||
Name = "announcements",
|
||||
Topic = "Official server announcements and news",
|
||||
Type = ChannelTypes.Channel,
|
||||
IsPrivate = false,
|
||||
AllowedRoles = string.Empty
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task TryExecuteColumnMigrationAsync(SqliteConnection conn, string sql)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = sql;
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
catch (SqliteException)
|
||||
{
|
||||
// Column already exists
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> CreateChannelInternalAsync(SqliteConnection conn, Channel channel)
|
||||
{
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
INSERT INTO channels (id, name, topic, is_private, allowed_roles, created_at)
|
||||
VALUES (@id, @name, @topic, @is_private, @allowed_roles, @created_at);
|
||||
INSERT INTO channels (id, name, topic, type, is_private, is_e2ee, creator_id, max_users, allowed_roles, created_at)
|
||||
VALUES (@id, @name, @topic, @type, @is_private, @is_e2ee, @creator_id, @max_users, @allowed_roles, @created_at);
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@id", channel.Id);
|
||||
cmd.Parameters.AddWithValue("@name", channel.Name);
|
||||
cmd.Parameters.AddWithValue("@topic", channel.Topic);
|
||||
cmd.Parameters.AddWithValue("@type", string.IsNullOrWhiteSpace(channel.Type) ? ChannelTypes.Channel : channel.Type);
|
||||
cmd.Parameters.AddWithValue("@is_private", channel.IsPrivate ? 1 : 0);
|
||||
cmd.Parameters.AddWithValue("@allowed_roles", channel.AllowedRoles);
|
||||
cmd.Parameters.AddWithValue("@is_e2ee", channel.IsE2ee ? 1 : 0);
|
||||
cmd.Parameters.AddWithValue("@creator_id", channel.CreatorId ?? string.Empty);
|
||||
cmd.Parameters.AddWithValue("@max_users", channel.MaxUsers);
|
||||
cmd.Parameters.AddWithValue("@allowed_roles", channel.AllowedRoles ?? string.Empty);
|
||||
cmd.Parameters.AddWithValue("@created_at", channel.CreatedAt.ToString("O"));
|
||||
|
||||
try
|
||||
|
|
@ -169,14 +226,17 @@ public class ChatDatabase : IDisposable
|
|||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
INSERT INTO users (id, username, password_hash, password_salt, role, created_at, is_banned)
|
||||
VALUES (@id, @username, @hash, @salt, @role, @created_at, @is_banned);
|
||||
INSERT INTO users (id, username, password_hash, password_salt, role, public_key, encrypted_private_key, e2ee_enabled, created_at, is_banned)
|
||||
VALUES (@id, @username, @hash, @salt, @role, @pub, @enc_priv, @e2ee_enabled, @created_at, @is_banned);
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@id", user.Id);
|
||||
cmd.Parameters.AddWithValue("@username", user.Username);
|
||||
cmd.Parameters.AddWithValue("@hash", user.PasswordHash);
|
||||
cmd.Parameters.AddWithValue("@salt", user.PasswordSalt);
|
||||
cmd.Parameters.AddWithValue("@role", user.Role);
|
||||
cmd.Parameters.AddWithValue("@pub", (object?)user.PublicKey ?? DBNull.Value);
|
||||
cmd.Parameters.AddWithValue("@enc_priv", (object?)user.EncryptedPrivateKey ?? DBNull.Value);
|
||||
cmd.Parameters.AddWithValue("@e2ee_enabled", user.E2eeEnabled ? 1 : 0);
|
||||
cmd.Parameters.AddWithValue("@created_at", user.CreatedAt.ToString("O"));
|
||||
cmd.Parameters.AddWithValue("@is_banned", user.IsBanned ? 1 : 0);
|
||||
|
||||
|
|
@ -194,7 +254,7 @@ public class ChatDatabase : IDisposable
|
|||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT id, username, password_hash, password_salt, role, created_at, is_banned FROM users WHERE username = @username LIMIT 1;";
|
||||
cmd.CommandText = "SELECT id, username, password_hash, password_salt, role, created_at, is_banned, public_key, encrypted_private_key, e2ee_enabled FROM users WHERE username = @username LIMIT 1;";
|
||||
cmd.Parameters.AddWithValue("@username", username);
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
|
|
@ -208,7 +268,10 @@ public class ChatDatabase : IDisposable
|
|||
PasswordSalt = reader.GetString(3),
|
||||
Role = reader.GetString(4),
|
||||
CreatedAt = DateTime.Parse(reader.GetString(5)),
|
||||
IsBanned = reader.GetInt32(6) == 1
|
||||
IsBanned = reader.GetInt32(6) == 1,
|
||||
PublicKey = reader.IsDBNull(7) ? null : reader.GetString(7),
|
||||
EncryptedPrivateKey = reader.IsDBNull(8) ? null : reader.GetString(8),
|
||||
E2eeEnabled = reader.IsDBNull(9) || reader.GetInt32(9) == 1
|
||||
};
|
||||
}
|
||||
return null;
|
||||
|
|
@ -218,7 +281,7 @@ public class ChatDatabase : IDisposable
|
|||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT id, username, password_hash, password_salt, role, created_at, is_banned FROM users WHERE id = @id LIMIT 1;";
|
||||
cmd.CommandText = "SELECT id, username, password_hash, password_salt, role, created_at, is_banned, public_key, encrypted_private_key, e2ee_enabled FROM users WHERE id = @id LIMIT 1;";
|
||||
cmd.Parameters.AddWithValue("@id", id);
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
|
|
@ -232,7 +295,10 @@ public class ChatDatabase : IDisposable
|
|||
PasswordSalt = reader.GetString(3),
|
||||
Role = reader.GetString(4),
|
||||
CreatedAt = DateTime.Parse(reader.GetString(5)),
|
||||
IsBanned = reader.GetInt32(6) == 1
|
||||
IsBanned = reader.GetInt32(6) == 1,
|
||||
PublicKey = reader.IsDBNull(7) ? null : reader.GetString(7),
|
||||
EncryptedPrivateKey = reader.IsDBNull(8) ? null : reader.GetString(8),
|
||||
E2eeEnabled = reader.IsDBNull(9) || reader.GetInt32(9) == 1
|
||||
};
|
||||
}
|
||||
return null;
|
||||
|
|
@ -243,7 +309,7 @@ public class ChatDatabase : IDisposable
|
|||
var users = new List<UserSummary>();
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT id, username, role FROM users ORDER BY username ASC;";
|
||||
cmd.CommandText = "SELECT id, username, role, public_key, e2ee_enabled FROM users ORDER BY username ASC;";
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
|
|
@ -253,12 +319,44 @@ public class ChatDatabase : IDisposable
|
|||
Id = reader.GetString(0),
|
||||
Username = reader.GetString(1),
|
||||
Role = reader.GetString(2),
|
||||
IsOnline = false
|
||||
IsOnline = false,
|
||||
PublicKey = reader.IsDBNull(3) ? null : reader.GetString(3),
|
||||
E2eeEnabled = reader.IsDBNull(4) || reader.GetInt32(4) == 1
|
||||
});
|
||||
}
|
||||
return users;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateUserKeysAsync(string userId, string publicKey, string? encryptedPrivateKey = null)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
if (!string.IsNullOrWhiteSpace(encryptedPrivateKey))
|
||||
{
|
||||
cmd.CommandText = "UPDATE users SET public_key = @pub, encrypted_private_key = @priv WHERE id = @id;";
|
||||
cmd.Parameters.AddWithValue("@pub", publicKey);
|
||||
cmd.Parameters.AddWithValue("@priv", encryptedPrivateKey);
|
||||
cmd.Parameters.AddWithValue("@id", userId);
|
||||
}
|
||||
else
|
||||
{
|
||||
cmd.CommandText = "UPDATE users SET public_key = @pub WHERE id = @id;";
|
||||
cmd.Parameters.AddWithValue("@pub", publicKey);
|
||||
cmd.Parameters.AddWithValue("@id", userId);
|
||||
}
|
||||
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||
}
|
||||
|
||||
public async Task<bool> SetUserE2eeEnabledAsync(string userId, bool enabled)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "UPDATE users SET e2ee_enabled = @enabled WHERE id = @id;";
|
||||
cmd.Parameters.AddWithValue("@enabled", enabled ? 1 : 0);
|
||||
cmd.Parameters.AddWithValue("@id", userId);
|
||||
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateUserRoleAsync(string userId, string newRole)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
|
|
@ -332,73 +430,208 @@ public class ChatDatabase : IDisposable
|
|||
|
||||
#endregion
|
||||
|
||||
#region Channel Operations
|
||||
#region Channel, DM & Group Chat Operations
|
||||
|
||||
private static Channel ReadChannelRow(SqliteDataReader reader)
|
||||
{
|
||||
return new Channel
|
||||
{
|
||||
Id = reader.GetString(0),
|
||||
Name = reader.GetString(1),
|
||||
Topic = reader.GetString(2),
|
||||
Type = reader.GetString(3),
|
||||
IsPrivate = reader.GetInt32(4) == 1,
|
||||
IsE2ee = reader.GetInt32(5) == 1,
|
||||
CreatorId = reader.GetString(6),
|
||||
MaxUsers = reader.GetInt32(7),
|
||||
AllowedRoles = reader.GetString(8),
|
||||
CreatedAt = DateTime.Parse(reader.GetString(9))
|
||||
};
|
||||
}
|
||||
|
||||
private static Task PopulateChannelMembersAsync(SqliteConnection conn, Channel channel, bool? serverAllowDmE2ee = null)
|
||||
{
|
||||
return PopulateChannelsMembersBatchAsync(conn, new[] { channel }, serverAllowDmE2ee);
|
||||
}
|
||||
|
||||
private static async Task PopulateChannelsMembersBatchAsync(SqliteConnection conn, IReadOnlyList<Channel> channels, bool? serverAllowDmE2ee = null)
|
||||
{
|
||||
if (channels.Count == 0) return;
|
||||
|
||||
var channelMap = new Dictionary<string, Channel>(channels.Count, StringComparer.OrdinalIgnoreCase);
|
||||
var allMembersAccountE2ee = new Dictionary<string, bool>(channels.Count, StringComparer.OrdinalIgnoreCase);
|
||||
var paramNames = new string[channels.Count];
|
||||
|
||||
using var cmd = conn.CreateCommand();
|
||||
for (int i = 0; i < channels.Count; i++)
|
||||
{
|
||||
var ch = channels[i];
|
||||
ch.MemberIds.Clear();
|
||||
ch.MemberUsernames.Clear();
|
||||
ch.MemberPublicKeys.Clear();
|
||||
|
||||
channelMap[ch.Id] = ch;
|
||||
allMembersAccountE2ee[ch.Id] = true;
|
||||
|
||||
string pName = $"@cid{i}";
|
||||
paramNames[i] = pName;
|
||||
cmd.Parameters.AddWithValue(pName, ch.Id);
|
||||
}
|
||||
|
||||
cmd.CommandText = $"""
|
||||
SELECT cm.channel_id, u.id, u.username, u.public_key, u.e2ee_enabled
|
||||
FROM channel_members cm
|
||||
JOIN users u ON u.id = cm.user_id
|
||||
WHERE cm.channel_id IN ({string.Join(", ", paramNames)})
|
||||
ORDER BY u.username ASC;
|
||||
""";
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
string cid = reader.GetString(0);
|
||||
if (!channelMap.TryGetValue(cid, out var channel)) continue;
|
||||
|
||||
string uid = reader.GetString(1);
|
||||
string uname = reader.GetString(2);
|
||||
string? pubKey = reader.IsDBNull(3) ? null : reader.GetString(3);
|
||||
bool userE2ee = reader.IsDBNull(4) || reader.GetInt32(4) == 1;
|
||||
|
||||
if (!userE2ee)
|
||||
{
|
||||
allMembersAccountE2ee[cid] = false;
|
||||
}
|
||||
|
||||
channel.MemberIds.Add(uid);
|
||||
channel.MemberUsernames.Add(uname);
|
||||
if (!string.IsNullOrWhiteSpace(pubKey))
|
||||
{
|
||||
channel.MemberPublicKeys[uid] = pubKey;
|
||||
channel.MemberPublicKeys[uname] = pubKey;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var channel in channels)
|
||||
{
|
||||
if (channel.Type == ChannelTypes.DirectMessage)
|
||||
{
|
||||
bool dmRowE2ee = channel.IsE2ee;
|
||||
bool serverAllowed = serverAllowDmE2ee ?? true;
|
||||
bool membersE2ee = allMembersAccountE2ee.GetValueOrDefault(channel.Id, true);
|
||||
channel.IsE2ee = serverAllowed && dmRowE2ee && membersE2ee;
|
||||
|
||||
if (!serverAllowed)
|
||||
{
|
||||
channel.Topic = "Direct Message (Server-Visible)";
|
||||
}
|
||||
else if (!dmRowE2ee)
|
||||
{
|
||||
channel.Topic = "Direct Message (E2EE Disabled for DM)";
|
||||
}
|
||||
else if (!membersE2ee)
|
||||
{
|
||||
channel.Topic = "Direct Message (E2EE Disabled by User)";
|
||||
}
|
||||
else
|
||||
{
|
||||
channel.Topic = "Direct Message (Full E2EE)";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task CleanupChannelResourcesAsync(SqliteConnection conn, string channelId)
|
||||
{
|
||||
var storagePaths = new List<string>();
|
||||
using (var selectFilesCmd = conn.CreateCommand())
|
||||
{
|
||||
selectFilesCmd.CommandText = "SELECT storage_path FROM files WHERE channel_id = @id;";
|
||||
selectFilesCmd.Parameters.AddWithValue("@id", channelId);
|
||||
using var reader = await selectFilesCmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
if (!reader.IsDBNull(0))
|
||||
{
|
||||
storagePaths.Add(reader.GetString(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var path in storagePaths)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(path) && File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore best-effort disk deletion errors
|
||||
}
|
||||
}
|
||||
|
||||
using var cleanupCmd = conn.CreateCommand();
|
||||
cleanupCmd.CommandText = """
|
||||
DELETE FROM files WHERE channel_id = @id;
|
||||
DELETE FROM messages WHERE channel_id = @id;
|
||||
DELETE FROM channel_members WHERE channel_id = @id;
|
||||
""";
|
||||
cleanupCmd.Parameters.AddWithValue("@id", channelId);
|
||||
await cleanupCmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
public async Task<List<Channel>> GetChannelsAsync()
|
||||
{
|
||||
var channels = new List<Channel>();
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT id, name, topic, is_private, allowed_roles, created_at FROM channels ORDER BY name ASC;";
|
||||
cmd.CommandText = "SELECT id, name, topic, type, is_private, is_e2ee, creator_id, max_users, allowed_roles, created_at FROM channels WHERE type = 'Channel' ORDER BY name ASC;";
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
channels.Add(new Channel
|
||||
{
|
||||
Id = reader.GetString(0),
|
||||
Name = reader.GetString(1),
|
||||
Topic = reader.GetString(2),
|
||||
IsPrivate = reader.GetInt32(3) == 1,
|
||||
AllowedRoles = reader.GetString(4),
|
||||
CreatedAt = DateTime.Parse(reader.GetString(5))
|
||||
});
|
||||
channels.Add(ReadChannelRow(reader));
|
||||
}
|
||||
return channels;
|
||||
}
|
||||
|
||||
public async Task<Channel?> GetChannelByIdAsync(string id)
|
||||
public async Task<Channel?> GetChannelByIdAsync(string id, bool? allowDmE2ee = null)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT id, name, topic, is_private, allowed_roles, created_at FROM channels WHERE id = @id LIMIT 1;";
|
||||
cmd.CommandText = "SELECT id, name, topic, type, is_private, is_e2ee, creator_id, max_users, allowed_roles, created_at FROM channels WHERE id = @id LIMIT 1;";
|
||||
cmd.Parameters.AddWithValue("@id", id);
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
if (await reader.ReadAsync())
|
||||
Channel? channel = null;
|
||||
using (var reader = await cmd.ExecuteReaderAsync())
|
||||
{
|
||||
return new Channel
|
||||
if (await reader.ReadAsync())
|
||||
{
|
||||
Id = reader.GetString(0),
|
||||
Name = reader.GetString(1),
|
||||
Topic = reader.GetString(2),
|
||||
IsPrivate = reader.GetInt32(3) == 1,
|
||||
AllowedRoles = reader.GetString(4),
|
||||
CreatedAt = DateTime.Parse(reader.GetString(5))
|
||||
};
|
||||
channel = ReadChannelRow(reader);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
if (channel != null && channel.Type != ChannelTypes.Channel)
|
||||
{
|
||||
await PopulateChannelMembersAsync(conn, channel, allowDmE2ee);
|
||||
}
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
public async Task<Channel?> GetChannelByNameAsync(string name)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT id, name, topic, is_private, allowed_roles, created_at FROM channels WHERE name = @name LIMIT 1;";
|
||||
cmd.CommandText = "SELECT id, name, topic, type, is_private, is_e2ee, creator_id, max_users, allowed_roles, created_at FROM channels WHERE type = 'Channel' AND name = @name LIMIT 1;";
|
||||
cmd.Parameters.AddWithValue("@name", name);
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
if (await reader.ReadAsync())
|
||||
{
|
||||
return new Channel
|
||||
{
|
||||
Id = reader.GetString(0),
|
||||
Name = reader.GetString(1),
|
||||
Topic = reader.GetString(2),
|
||||
IsPrivate = reader.GetInt32(3) == 1,
|
||||
AllowedRoles = reader.GetString(4),
|
||||
CreatedAt = DateTime.Parse(reader.GetString(5))
|
||||
};
|
||||
return ReadChannelRow(reader);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -406,18 +639,296 @@ public class ChatDatabase : IDisposable
|
|||
public async Task<bool> CreateChannelAsync(Channel channel)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
channel.Type = ChannelTypes.Channel;
|
||||
return await CreateChannelInternalAsync(conn, channel);
|
||||
}
|
||||
|
||||
public async Task<bool> SetChannelE2eeAsync(string channelId, bool enabled)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "UPDATE channels SET is_e2ee = @e2ee WHERE id = @id;";
|
||||
cmd.Parameters.AddWithValue("@e2ee", enabled ? 1 : 0);
|
||||
cmd.Parameters.AddWithValue("@id", channelId);
|
||||
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteChannelAsync(string channelId)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
await CleanupChannelResourcesAsync(conn, channelId);
|
||||
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "DELETE FROM channels WHERE id = @id;";
|
||||
cmd.Parameters.AddWithValue("@id", channelId);
|
||||
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||
}
|
||||
|
||||
public async Task<Channel> GetOrCreateDirectMessageAsync(string user1Id, string user2Id, bool allowDmE2ee)
|
||||
{
|
||||
var sorted = string.CompareOrdinal(user1Id, user2Id) <= 0 ? (user1Id, user2Id) : (user2Id, user1Id);
|
||||
string dmKey = $"dm:{sorted.Item1}:{sorted.Item2}";
|
||||
|
||||
using var conn = CreateConnection();
|
||||
|
||||
Channel? existing = null;
|
||||
using (var findCmd = conn.CreateCommand())
|
||||
{
|
||||
findCmd.CommandText = "SELECT id, name, topic, type, is_private, is_e2ee, creator_id, max_users, allowed_roles, created_at FROM channels WHERE type = 'DM' AND allowed_roles = @dmKey LIMIT 1;";
|
||||
findCmd.Parameters.AddWithValue("@dmKey", dmKey);
|
||||
using var reader = await findCmd.ExecuteReaderAsync();
|
||||
if (await reader.ReadAsync())
|
||||
{
|
||||
existing = ReadChannelRow(reader);
|
||||
}
|
||||
}
|
||||
|
||||
if (existing != null)
|
||||
{
|
||||
await PopulateChannelMembersAsync(conn, existing, allowDmE2ee);
|
||||
return existing;
|
||||
}
|
||||
|
||||
var u1 = await GetUserByIdAsync(user1Id);
|
||||
var u2 = await GetUserByIdAsync(user2Id);
|
||||
string dmName = u1 != null && u2 != null
|
||||
? $"{u1.Username} & {u2.Username}"
|
||||
: "Direct Message";
|
||||
|
||||
var dmChannel = new Channel
|
||||
{
|
||||
Name = dmName,
|
||||
Topic = allowDmE2ee ? "Direct Message (Full E2EE)" : "Direct Message (Server-Visible)",
|
||||
Type = ChannelTypes.DirectMessage,
|
||||
IsPrivate = true,
|
||||
IsE2ee = true,
|
||||
CreatorId = user1Id,
|
||||
MaxUsers = 2,
|
||||
AllowedRoles = dmKey,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await CreateChannelInternalAsync(conn, dmChannel);
|
||||
await AddChannelMemberInternalAsync(conn, dmChannel.Id, user1Id);
|
||||
if (user1Id != user2Id)
|
||||
{
|
||||
await AddChannelMemberInternalAsync(conn, dmChannel.Id, user2Id);
|
||||
}
|
||||
|
||||
await PopulateChannelMembersAsync(conn, dmChannel, allowDmE2ee);
|
||||
return dmChannel;
|
||||
}
|
||||
|
||||
public async Task<List<Channel>> GetDirectMessagesForUserAsync(string userId, bool allowDmE2ee)
|
||||
{
|
||||
var dms = new List<Channel>();
|
||||
using var conn = CreateConnection();
|
||||
using (var cmd = conn.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = """
|
||||
SELECT c.id, c.name, c.topic, c.type, c.is_private, c.is_e2ee, c.creator_id, c.max_users, c.allowed_roles, c.created_at
|
||||
FROM channels c
|
||||
JOIN channel_members cm ON cm.channel_id = c.id
|
||||
WHERE c.type = 'DM' AND cm.user_id = @uid
|
||||
ORDER BY c.created_at DESC;
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@uid", userId);
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
dms.Add(ReadChannelRow(reader));
|
||||
}
|
||||
}
|
||||
|
||||
await PopulateChannelsMembersBatchAsync(conn, dms, allowDmE2ee);
|
||||
|
||||
foreach (var dm in dms)
|
||||
{
|
||||
// Format Name relative to the requesting user as the peer's username
|
||||
var peerIndex = dm.MemberIds.FindIndex(id => !string.Equals(id, userId, StringComparison.OrdinalIgnoreCase));
|
||||
if (peerIndex >= 0 && peerIndex < dm.MemberUsernames.Count)
|
||||
{
|
||||
dm.Name = dm.MemberUsernames[peerIndex];
|
||||
}
|
||||
else if (dm.MemberUsernames.Count > 0)
|
||||
{
|
||||
dm.Name = dm.MemberUsernames[0];
|
||||
}
|
||||
}
|
||||
|
||||
return dms;
|
||||
}
|
||||
|
||||
public async Task<Channel> CreateGroupChatAsync(string name, string topic, string creatorId, IEnumerable<string> memberUserIds, int maxUsers)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
|
||||
var group = new Channel
|
||||
{
|
||||
Name = name.Trim(),
|
||||
Topic = topic?.Trim() ?? string.Empty,
|
||||
Type = ChannelTypes.Group,
|
||||
IsPrivate = true,
|
||||
IsE2ee = false,
|
||||
CreatorId = creatorId,
|
||||
MaxUsers = maxUsers,
|
||||
AllowedRoles = string.Empty,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await CreateChannelInternalAsync(conn, group);
|
||||
|
||||
var distinctMembers = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { creatorId };
|
||||
if (memberUserIds != null)
|
||||
{
|
||||
foreach (var mid in memberUserIds)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(mid))
|
||||
{
|
||||
distinctMembers.Add(mid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var uid in distinctMembers)
|
||||
{
|
||||
await AddChannelMemberInternalAsync(conn, group.Id, uid);
|
||||
}
|
||||
|
||||
await PopulateChannelMembersAsync(conn, group);
|
||||
return group;
|
||||
}
|
||||
|
||||
public async Task<List<Channel>> GetGroupChatsForUserAsync(string userId)
|
||||
{
|
||||
var groups = new List<Channel>();
|
||||
using var conn = CreateConnection();
|
||||
using (var cmd = conn.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = """
|
||||
SELECT c.id, c.name, c.topic, c.type, c.is_private, c.is_e2ee, c.creator_id, c.max_users, c.allowed_roles, c.created_at
|
||||
FROM channels c
|
||||
JOIN channel_members cm ON cm.channel_id = c.id
|
||||
WHERE c.type = 'Group' AND cm.user_id = @uid
|
||||
ORDER BY c.name ASC;
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@uid", userId);
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
groups.Add(ReadChannelRow(reader));
|
||||
}
|
||||
}
|
||||
|
||||
await PopulateChannelsMembersBatchAsync(conn, groups);
|
||||
return groups;
|
||||
}
|
||||
|
||||
public async Task<bool> AddGroupMemberAsync(string channelId, string userId)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
return await AddChannelMemberInternalAsync(conn, channelId, userId);
|
||||
}
|
||||
|
||||
private static async Task<bool> AddChannelMemberInternalAsync(SqliteConnection conn, string channelId, string userId)
|
||||
{
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
INSERT INTO channel_members (channel_id, user_id, joined_at)
|
||||
VALUES (@cid, @uid, @joined_at)
|
||||
ON CONFLICT(channel_id, user_id) DO NOTHING;
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@cid", channelId);
|
||||
cmd.Parameters.AddWithValue("@uid", userId);
|
||||
cmd.Parameters.AddWithValue("@joined_at", DateTime.UtcNow.ToString("O"));
|
||||
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveGroupMemberAsync(string channelId, string userId)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "DELETE FROM channel_members WHERE channel_id = @cid AND user_id = @uid;";
|
||||
cmd.Parameters.AddWithValue("@cid", channelId);
|
||||
cmd.Parameters.AddWithValue("@uid", userId);
|
||||
bool removed = (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||
|
||||
if (removed)
|
||||
{
|
||||
using var countCmd = conn.CreateCommand();
|
||||
countCmd.CommandText = "SELECT COUNT(*) FROM channel_members WHERE channel_id = @cid;";
|
||||
countCmd.Parameters.AddWithValue("@cid", channelId);
|
||||
long remaining = (long)(await countCmd.ExecuteScalarAsync() ?? 0L);
|
||||
if (remaining == 0)
|
||||
{
|
||||
await CleanupChannelResourcesAsync(conn, channelId);
|
||||
|
||||
using var delCmd = conn.CreateCommand();
|
||||
delCmd.CommandText = "DELETE FROM channels WHERE id = @cid AND type = 'Group';";
|
||||
delCmd.Parameters.AddWithValue("@cid", channelId);
|
||||
await delCmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
public async Task<bool> IsUserInChannelAsync(string channelId, string userId)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM channel_members WHERE channel_id = @cid AND user_id = @uid;";
|
||||
cmd.Parameters.AddWithValue("@cid", channelId);
|
||||
cmd.Parameters.AddWithValue("@uid", userId);
|
||||
long count = (long)(await cmd.ExecuteScalarAsync() ?? 0L);
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
public async Task<bool> CanUserAccessChannelAsync(string channelId, string userId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(channelId)) return false;
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
SELECT c.type,
|
||||
EXISTS(SELECT 1 FROM channel_members cm WHERE cm.channel_id = c.id AND cm.user_id = @uid) AS is_member
|
||||
FROM channels c
|
||||
WHERE c.id = @cid
|
||||
LIMIT 1;
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@cid", channelId);
|
||||
cmd.Parameters.AddWithValue("@uid", userId);
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
if (!await reader.ReadAsync()) return false;
|
||||
|
||||
string type = reader.GetString(0);
|
||||
if (type == ChannelTypes.Channel) return true;
|
||||
return reader.GetInt32(1) == 1;
|
||||
}
|
||||
|
||||
public async Task<HashSet<string>> GetAccessibleChannelIdsForUserAsync(string userId)
|
||||
{
|
||||
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
SELECT id FROM channels WHERE type = 'Channel'
|
||||
UNION
|
||||
SELECT channel_id FROM channel_members WHERE user_id = @uid;
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@uid", userId);
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
ids.Add(reader.GetString(0));
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Message Operations
|
||||
|
|
@ -427,8 +938,8 @@ public class ChatDatabase : IDisposable
|
|||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
INSERT INTO messages (id, channel_id, sender_id, sender_username, sender_role, content, created_at, attachment_id, attachment_name, attachment_size)
|
||||
VALUES (@id, @channel_id, @sender_id, @sender_username, @sender_role, @content, @created_at, @attachment_id, @attachment_name, @attachment_size);
|
||||
INSERT INTO messages (id, channel_id, sender_id, sender_username, sender_role, content, is_encrypted, sender_public_key, recipient_public_key, created_at, attachment_id, attachment_name, attachment_size)
|
||||
VALUES (@id, @channel_id, @sender_id, @sender_username, @sender_role, @content, @is_encrypted, @sender_public_key, @recipient_public_key, @created_at, @attachment_id, @attachment_name, @attachment_size);
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@id", message.Id);
|
||||
cmd.Parameters.AddWithValue("@channel_id", message.ChannelId);
|
||||
|
|
@ -436,6 +947,9 @@ public class ChatDatabase : IDisposable
|
|||
cmd.Parameters.AddWithValue("@sender_username", message.SenderUsername);
|
||||
cmd.Parameters.AddWithValue("@sender_role", message.SenderRole);
|
||||
cmd.Parameters.AddWithValue("@content", message.Content);
|
||||
cmd.Parameters.AddWithValue("@is_encrypted", message.IsEncrypted ? 1 : 0);
|
||||
cmd.Parameters.AddWithValue("@sender_public_key", (object?)message.SenderPublicKey ?? DBNull.Value);
|
||||
cmd.Parameters.AddWithValue("@recipient_public_key", (object?)message.RecipientPublicKey ?? DBNull.Value);
|
||||
cmd.Parameters.AddWithValue("@created_at", message.CreatedAt.ToString("O"));
|
||||
cmd.Parameters.AddWithValue("@attachment_id", (object?)message.AttachmentId ?? DBNull.Value);
|
||||
cmd.Parameters.AddWithValue("@attachment_name", (object?)message.AttachmentName ?? DBNull.Value);
|
||||
|
|
@ -444,23 +958,34 @@ public class ChatDatabase : IDisposable
|
|||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
public async Task<List<ChatMessage>> GetRecentMessagesAsync(string channelId, int limit = 50)
|
||||
public async Task<int> GetMessageCountAsync(string channelId)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM messages WHERE channel_id = @channel_id;";
|
||||
cmd.Parameters.AddWithValue("@channel_id", channelId);
|
||||
var result = await cmd.ExecuteScalarAsync();
|
||||
return Convert.ToInt32(result);
|
||||
}
|
||||
|
||||
public async Task<List<ChatMessage>> GetRecentMessagesAsync(string channelId, int limit = 50, int offset = 0)
|
||||
{
|
||||
var messages = new List<ChatMessage>();
|
||||
using var conn = CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
SELECT id, channel_id, sender_id, sender_username, sender_role, content, created_at, attachment_id, attachment_name, attachment_size
|
||||
SELECT id, channel_id, sender_id, sender_username, sender_role, content, created_at, attachment_id, attachment_name, attachment_size, is_encrypted, sender_public_key, recipient_public_key
|
||||
FROM (
|
||||
SELECT * FROM messages
|
||||
WHERE channel_id = @channel_id
|
||||
ORDER BY created_at DESC
|
||||
LIMIT @limit
|
||||
LIMIT @limit OFFSET @offset
|
||||
)
|
||||
ORDER BY created_at ASC;
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@channel_id", channelId);
|
||||
cmd.Parameters.AddWithValue("@limit", limit);
|
||||
cmd.Parameters.AddWithValue("@offset", Math.Max(0, offset));
|
||||
|
||||
using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
|
|
@ -476,7 +1001,10 @@ public class ChatDatabase : IDisposable
|
|||
CreatedAt = DateTime.Parse(reader.GetString(6)),
|
||||
AttachmentId = reader.IsDBNull(7) ? null : reader.GetString(7),
|
||||
AttachmentName = reader.IsDBNull(8) ? null : reader.GetString(8),
|
||||
AttachmentSizeBytes = reader.IsDBNull(9) ? null : reader.GetInt64(9)
|
||||
AttachmentSizeBytes = reader.IsDBNull(9) ? null : reader.GetInt64(9),
|
||||
IsEncrypted = !reader.IsDBNull(10) && reader.GetInt32(10) == 1,
|
||||
SenderPublicKey = reader.IsDBNull(11) ? null : reader.GetString(11),
|
||||
RecipientPublicKey = reader.IsDBNull(12) ? null : reader.GetString(12)
|
||||
});
|
||||
}
|
||||
return messages;
|
||||
|
|
|
|||
|
|
@ -18,24 +18,12 @@ using GsDChat.Server.WebSockets;
|
|||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Load Server Configuration
|
||||
var configPath = Path.Combine(AppContext.BaseDirectory, "serversettings.json");
|
||||
var serverOptions = new ServerOptions();
|
||||
if (File.Exists(configPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(configPath);
|
||||
var loaded = JsonSerializer.Deserialize<ServerOptions>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
if (loaded != null) serverOptions = loaded;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[Warning] Failed to read serversettings.json: {ex.Message}. Using defaults.");
|
||||
}
|
||||
}
|
||||
// Load Server Configuration from local .json file (serversettings.json)
|
||||
var settingsFilePath = ServerSettingsManager.ResolveSettingsFilePath(args: args);
|
||||
var settingsManager = new ServerSettingsManager(settingsFilePath);
|
||||
var serverOptions = settingsManager.LoadOrCreate();
|
||||
|
||||
// Environment variable overrides (convenient for Docker & Docker Compose)
|
||||
// Optional environment variable overrides
|
||||
string? envPort = Environment.GetEnvironmentVariable("GSDCHAT_PORT") ?? Environment.GetEnvironmentVariable("PORT");
|
||||
if (!string.IsNullOrEmpty(envPort) && int.TryParse(envPort, out int ep)) serverOptions.Port = ep;
|
||||
|
||||
|
|
@ -46,7 +34,7 @@ string? envTls = Environment.GetEnvironmentVariable("GSDCHAT_USE_TLS");
|
|||
if (!string.IsNullOrEmpty(envTls) && bool.TryParse(envTls, out bool etls)) serverOptions.UseTls = etls;
|
||||
|
||||
string? envPass = Environment.GetEnvironmentVariable("GSDCHAT_SERVER_PASSWORD") ?? Environment.GetEnvironmentVariable("SERVER_PASSWORD");
|
||||
if (envPass != null) serverOptions.ServerWidePassword = envPass;
|
||||
if (!string.IsNullOrEmpty(envPass)) serverOptions.ServerWidePassword = envPass;
|
||||
|
||||
string? envReg = Environment.GetEnvironmentVariable("GSDCHAT_REGISTRATION_MODE") ?? Environment.GetEnvironmentVariable("REGISTRATION_MODE");
|
||||
if (!string.IsNullOrEmpty(envReg)) serverOptions.RegistrationMode = envReg;
|
||||
|
|
@ -72,6 +60,12 @@ if (!string.IsNullOrEmpty(envCertPass)) serverOptions.CertificatePassword = envC
|
|||
string? envAllowMemberChannels = Environment.GetEnvironmentVariable("GSDCHAT_ALLOW_MEMBER_CHANNELS");
|
||||
if (!string.IsNullOrEmpty(envAllowMemberChannels) && bool.TryParse(envAllowMemberChannels, out bool eamc)) serverOptions.AllowMemberChannelCreation = eamc;
|
||||
|
||||
string? envAllowDmE2ee = Environment.GetEnvironmentVariable("GSDCHAT_ALLOW_DM_E2EE");
|
||||
if (!string.IsNullOrEmpty(envAllowDmE2ee) && bool.TryParse(envAllowDmE2ee, out bool eadme)) serverOptions.AllowDmE2ee = eadme;
|
||||
|
||||
string? envMaxGroupUsers = Environment.GetEnvironmentVariable("GSDCHAT_MAX_GROUP_USERS");
|
||||
if (!string.IsNullOrEmpty(envMaxGroupUsers) && int.TryParse(envMaxGroupUsers, out int emgu)) serverOptions.MaxGroupChatUsers = emgu;
|
||||
|
||||
// Allow CLI overrides e.g. --port 5000 --tls false
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
|
|
@ -82,8 +76,11 @@ for (int i = 0; i < args.Length; i++)
|
|||
if (args[i] == "--data-dir" && i + 1 < args.Length) serverOptions.DataDirectory = args[i + 1];
|
||||
if (args[i] == "--server-name" && i + 1 < args.Length) serverOptions.ServerName = args[i + 1];
|
||||
if (args[i] == "--motd" && i + 1 < args.Length) serverOptions.Motd = args[i + 1];
|
||||
if (args[i] == "--allow-dm-e2ee" && i + 1 < args.Length && bool.TryParse(args[i + 1], out bool dme2ee)) serverOptions.AllowDmE2ee = dme2ee;
|
||||
if (args[i] == "--max-group-users" && i + 1 < args.Length && int.TryParse(args[i + 1], out int mgu)) serverOptions.MaxGroupChatUsers = mgu;
|
||||
}
|
||||
|
||||
builder.Services.AddSingleton(settingsManager);
|
||||
builder.Services.AddSingleton(serverOptions);
|
||||
|
||||
// Configure Kestrel bindings
|
||||
|
|
@ -176,7 +173,9 @@ app.MapGet("/api/info", (ServerOptions opt) =>
|
|||
RequiresServerPassword = !string.IsNullOrWhiteSpace(opt.ServerWidePassword),
|
||||
Motd = opt.Motd,
|
||||
MaxFileSizeMb = opt.MaxFileSizeMb,
|
||||
AllowMemberChannelCreation = opt.AllowMemberChannelCreation
|
||||
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
|
||||
AllowDmE2ee = opt.AllowDmE2ee,
|
||||
MaxGroupChatUsers = opt.MaxGroupChatUsers
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -193,7 +192,7 @@ app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth) =>
|
|||
});
|
||||
|
||||
// File Upload
|
||||
app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, FileStorageService fileService, ChatWebSocketManager wsManager) =>
|
||||
app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileService, ChatWebSocketManager wsManager) =>
|
||||
{
|
||||
string? token = ExtractBearerToken(req);
|
||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||
|
|
@ -220,20 +219,26 @@ app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, File
|
|||
return Results.BadRequest(new UploadFileResponse { Success = false, ErrorMessage = "channelId is required." });
|
||||
}
|
||||
|
||||
if (!await chatDb.CanUserAccessChannelAsync(channelId, user.Id))
|
||||
{
|
||||
return Results.Json(new UploadFileResponse { Success = false, ErrorMessage = "You do not have access to this conversation." }, statusCode: StatusCodes.Status403Forbidden);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var stream = file.OpenReadStream();
|
||||
var record = await fileService.StoreFileAsync(
|
||||
var (record, savedMsg) = await fileService.StoreFileWithMessageAsync(
|
||||
channelId,
|
||||
user.Id,
|
||||
user.Username,
|
||||
file.FileName,
|
||||
file.ContentType,
|
||||
stream,
|
||||
file.Length
|
||||
file.Length,
|
||||
user.Role
|
||||
);
|
||||
|
||||
await wsManager.BroadcastFileUploadedAsync(record);
|
||||
await wsManager.BroadcastFileUploadedAsync(record, savedMsg);
|
||||
|
||||
return Results.Ok(new UploadFileResponse
|
||||
{
|
||||
|
|
@ -251,7 +256,7 @@ app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, File
|
|||
});
|
||||
|
||||
// File Download
|
||||
app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService auth, FileStorageService fileService) =>
|
||||
app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileService) =>
|
||||
{
|
||||
string? token = ExtractBearerToken(req);
|
||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||
|
|
@ -266,6 +271,11 @@ app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService au
|
|||
return Results.NotFound();
|
||||
}
|
||||
|
||||
if (!await chatDb.CanUserAccessChannelAsync(record.ChannelId, user.Id))
|
||||
{
|
||||
return Results.StatusCode(StatusCodes.Status403Forbidden);
|
||||
}
|
||||
|
||||
var stream = fileService.OpenFileStream(record);
|
||||
if (stream == null)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -108,6 +108,8 @@ public class AuthService : IAuthService
|
|||
PasswordHash = hash,
|
||||
PasswordSalt = salt,
|
||||
Role = assignedRole,
|
||||
PublicKey = request.PublicKey,
|
||||
EncryptedPrivateKey = request.EncryptedPrivateKey,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
IsBanned = false
|
||||
};
|
||||
|
|
@ -139,7 +141,10 @@ public class AuthService : IAuthService
|
|||
Token = sessionToken,
|
||||
UserId = newUser.Id,
|
||||
Username = newUser.Username,
|
||||
Role = newUser.Role
|
||||
Role = newUser.Role,
|
||||
PublicKey = newUser.PublicKey,
|
||||
EncryptedPrivateKey = newUser.EncryptedPrivateKey,
|
||||
E2eeEnabled = newUser.E2eeEnabled
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -192,6 +197,13 @@ public class AuthService : IAuthService
|
|||
};
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(user.PublicKey) && !string.IsNullOrWhiteSpace(request.PublicKey))
|
||||
{
|
||||
await _db.UpdateUserKeysAsync(user.Id, request.PublicKey, request.EncryptedPrivateKey);
|
||||
user.PublicKey = request.PublicKey;
|
||||
user.EncryptedPrivateKey = request.EncryptedPrivateKey;
|
||||
}
|
||||
|
||||
var sessionToken = TokenGenerator.GenerateSecureToken();
|
||||
var session = new Session
|
||||
{
|
||||
|
|
@ -209,7 +221,10 @@ public class AuthService : IAuthService
|
|||
Token = sessionToken,
|
||||
UserId = user.Id,
|
||||
Username = user.Username,
|
||||
Role = user.Role
|
||||
Role = user.Role,
|
||||
PublicKey = user.PublicKey,
|
||||
EncryptedPrivateKey = user.EncryptedPrivateKey,
|
||||
E2eeEnabled = user.E2eeEnabled
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,7 +29,30 @@ public class FileStorageService
|
|||
string originalFileName,
|
||||
string contentType,
|
||||
Stream stream,
|
||||
long length)
|
||||
long length,
|
||||
string uploaderRole = UserRoles.Member)
|
||||
{
|
||||
var (record, _) = await StoreFileWithMessageAsync(
|
||||
channelId,
|
||||
uploaderId,
|
||||
uploaderUsername,
|
||||
originalFileName,
|
||||
contentType,
|
||||
stream,
|
||||
length,
|
||||
uploaderRole);
|
||||
return record;
|
||||
}
|
||||
|
||||
public async Task<(FileRecord Record, ChatMessage Message)> StoreFileWithMessageAsync(
|
||||
string channelId,
|
||||
string uploaderId,
|
||||
string uploaderUsername,
|
||||
string originalFileName,
|
||||
string contentType,
|
||||
Stream stream,
|
||||
long length,
|
||||
string uploaderRole = UserRoles.Member)
|
||||
{
|
||||
long maxBytes = _options.MaxFileSizeMb * 1024 * 1024;
|
||||
if (length > maxBytes)
|
||||
|
|
@ -73,6 +96,7 @@ public class FileStorageService
|
|||
sha256Hex = Convert.ToHexString(sha256.Hash ?? Array.Empty<byte>());
|
||||
}
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var record = new FileRecord
|
||||
{
|
||||
Id = fileId,
|
||||
|
|
@ -84,7 +108,7 @@ public class FileStorageService
|
|||
FileSizeBytes = writtenBytes,
|
||||
StoragePath = diskFilePath,
|
||||
Sha256Checksum = sha256Hex,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
CreatedAt = now
|
||||
};
|
||||
|
||||
await _db.SaveFileRecordAsync(record);
|
||||
|
|
@ -95,15 +119,16 @@ public class FileStorageService
|
|||
ChannelId = channelId,
|
||||
SenderId = uploaderId,
|
||||
SenderUsername = uploaderUsername,
|
||||
SenderRole = string.IsNullOrWhiteSpace(uploaderRole) ? UserRoles.Member : uploaderRole,
|
||||
Content = $"Shared file: {safeName} ({FormatBytes(writtenBytes)})",
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = now,
|
||||
AttachmentId = record.Id,
|
||||
AttachmentName = safeName,
|
||||
AttachmentSizeBytes = writtenBytes
|
||||
};
|
||||
await _db.SaveMessageAsync(msg);
|
||||
|
||||
return record;
|
||||
return (record, msg);
|
||||
}
|
||||
|
||||
public async Task<FileRecord?> GetFileRecordAsync(string fileId)
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ using System.Threading.Tasks;
|
|||
using Microsoft.Extensions.Logging;
|
||||
using GsDChat.Core.Models;
|
||||
using GsDChat.Core.Protocol;
|
||||
using GsDChat.Core.Security;
|
||||
using GsDChat.Server.Configuration;
|
||||
using GsDChat.Server.Data;
|
||||
using GsDChat.Server.Services;
|
||||
|
|
@ -55,30 +56,41 @@ public class ChatWebSocketManager
|
|||
}
|
||||
|
||||
// Send UI Definition
|
||||
var uiSync = UiSyncProvider?.Invoke() ?? ServerUiSync.CreateDefault(_options.ServerName, _options.Motd);
|
||||
await client.SendMessageAsync(MessageTypes.UiSync, uiSync, cancellationToken);
|
||||
var uiSync = UiSyncProvider?.Invoke() ?? ServerUiSync.CreateDefault(
|
||||
_options.ServerName,
|
||||
_options.Motd,
|
||||
_options.AllowDmE2ee,
|
||||
_options.MaxGroupChatUsers);
|
||||
uiSync.AllowDmE2ee = _options.AllowDmE2ee;
|
||||
uiSync.MaxGroupChatUsers = _options.MaxGroupChatUsers;
|
||||
|
||||
// Send Channel List
|
||||
await client.SendMessageAsync(MessageTypes.ChannelListSync, new ChannelListSyncPacket
|
||||
// Send AuthResult with current E2EE key vault metadata so restored sessions have latest server state
|
||||
await client.SendMessageAsync(MessageTypes.AuthResult, new AuthResultPacket
|
||||
{
|
||||
Channels = channels,
|
||||
Success = true,
|
||||
UserId = user.Id,
|
||||
Username = user.Username,
|
||||
Role = user.Role,
|
||||
PublicKey = user.PublicKey,
|
||||
EncryptedPrivateKey = user.EncryptedPrivateKey,
|
||||
E2eeEnabled = user.E2eeEnabled,
|
||||
UiSync = uiSync,
|
||||
ActiveChannelId = client.ActiveChannelId
|
||||
}, cancellationToken);
|
||||
|
||||
// Send Initial Chat History
|
||||
await client.SendMessageAsync(MessageTypes.UiSync, uiSync, cancellationToken);
|
||||
|
||||
// Send Channel, DM, and Group Chat Lists
|
||||
await SendChannelListToClientAsync(client, cancellationToken);
|
||||
|
||||
// Send Initial Chat History (latest 50 messages, with HasMore flag for on-demand loading)
|
||||
if (!string.IsNullOrEmpty(client.ActiveChannelId))
|
||||
{
|
||||
var messages = await _db.GetRecentMessagesAsync(client.ActiveChannelId, 50);
|
||||
await client.SendMessageAsync(MessageTypes.HistorySync, new HistorySyncPacket
|
||||
{
|
||||
ChannelId = client.ActiveChannelId,
|
||||
Messages = messages
|
||||
}, cancellationToken);
|
||||
await SendHistoryPageAsync(client, client.ActiveChannelId, offset: 0, limit: 50, prepend: false, cancellationToken);
|
||||
}
|
||||
|
||||
// Send Files List
|
||||
var files = await _db.GetRecentFilesAsync(100);
|
||||
await client.SendMessageAsync(MessageTypes.FileListSync, new FileListSyncPacket { Files = files }, cancellationToken);
|
||||
// Send Files List (filtered for user access)
|
||||
await SendFileListToClientAsync(client, cancellationToken);
|
||||
|
||||
// Send Initial User List
|
||||
var initialUsers = await _db.GetAllUsersAsync();
|
||||
|
|
@ -180,6 +192,14 @@ public class ChatWebSocketManager
|
|||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.FetchHistory:
|
||||
var fetchPkg = envelope.Unpack<FetchHistoryPacket>();
|
||||
if (fetchPkg != null)
|
||||
{
|
||||
await HandleFetchHistoryAsync(client, fetchPkg, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.CreateChannel:
|
||||
var createPkg = envelope.Unpack<CreateChannelPacket>();
|
||||
if (createPkg != null)
|
||||
|
|
@ -196,6 +216,54 @@ public class ChatWebSocketManager
|
|||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.StartDm:
|
||||
var dmPkg = envelope.Unpack<StartDmPacket>();
|
||||
if (dmPkg != null)
|
||||
{
|
||||
await HandleStartDmAsync(client, dmPkg, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.CreateGroup:
|
||||
var groupPkg = envelope.Unpack<CreateGroupPacket>();
|
||||
if (groupPkg != null)
|
||||
{
|
||||
await HandleCreateGroupAsync(client, groupPkg, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.InviteToGroup:
|
||||
var invitePkg = envelope.Unpack<InviteToGroupPacket>();
|
||||
if (invitePkg != null)
|
||||
{
|
||||
await HandleInviteToGroupAsync(client, invitePkg, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.LeaveGroup:
|
||||
var leavePkg = envelope.Unpack<LeaveGroupPacket>();
|
||||
if (leavePkg != null)
|
||||
{
|
||||
await HandleLeaveGroupAsync(client, leavePkg, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.PublishPublicKey:
|
||||
var keyPkg = envelope.Unpack<PublishPublicKeyPacket>();
|
||||
if (keyPkg != null)
|
||||
{
|
||||
await HandlePublishPublicKeyAsync(client, keyPkg, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.ToggleE2ee:
|
||||
var togglePkg = envelope.Unpack<ToggleE2eePacket>();
|
||||
if (togglePkg != null)
|
||||
{
|
||||
await HandleToggleE2eeAsync(client, togglePkg, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.ExecuteCommand:
|
||||
var cmdPkg = envelope.Unpack<ExecuteCommandPacket>();
|
||||
if (cmdPkg != null)
|
||||
|
|
@ -221,6 +289,146 @@ public class ChatWebSocketManager
|
|||
}
|
||||
}
|
||||
|
||||
private async Task SendHistoryPageAsync(ConnectedClient client, string channelId, int offset, int limit, bool prepend, CancellationToken ct)
|
||||
{
|
||||
int clampedLimit = Math.Clamp(limit <= 0 ? 50 : limit, 1, 200);
|
||||
int clampedOffset = Math.Max(0, offset);
|
||||
int totalCount = await _db.GetMessageCountAsync(channelId);
|
||||
var history = await _db.GetRecentMessagesAsync(channelId, clampedLimit, clampedOffset);
|
||||
bool hasMore = totalCount > (clampedOffset + history.Count);
|
||||
|
||||
await client.SendMessageAsync(MessageTypes.HistorySync, new HistorySyncPacket
|
||||
{
|
||||
ChannelId = channelId,
|
||||
Messages = history,
|
||||
Prepend = prepend,
|
||||
HasMore = hasMore,
|
||||
Offset = clampedOffset
|
||||
}, ct);
|
||||
}
|
||||
|
||||
private async Task HandleFetchHistoryAsync(ConnectedClient client, FetchHistoryPacket packet, CancellationToken ct)
|
||||
{
|
||||
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
||||
if (string.IsNullOrWhiteSpace(channelId)) return;
|
||||
|
||||
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
||||
if (channel == null)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Channel not found." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
||||
{
|
||||
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
||||
if (!isMember)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this conversation." }, ct);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await SendHistoryPageAsync(client, channelId, packet.Offset, packet.Limit, prepend: true, ct);
|
||||
}
|
||||
|
||||
private async Task HandlePublishPublicKeyAsync(ConnectedClient client, PublishPublicKeyPacket packet, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(packet.PublicKey)) return;
|
||||
|
||||
var dbUser = await _db.GetUserByIdAsync(client.User.Id);
|
||||
bool hasExistingKey = !string.IsNullOrWhiteSpace(dbUser?.PublicKey);
|
||||
|
||||
// Protect against accidental overwrite of an existing E2EE keypair unless ResetKeys is explicitly requested
|
||||
if (hasExistingKey && !packet.ResetKeys && !string.Equals(dbUser!.PublicKey, packet.PublicKey, StringComparison.Ordinal))
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
||||
{
|
||||
Message = "An E2EE key vault already exists for your account. Unlock it with your E2EE PIN or explicitly reset your E2EE keys.",
|
||||
Code = "E2EE_KEY_EXISTS"
|
||||
}, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
await _db.UpdateUserKeysAsync(client.User.Id, packet.PublicKey, packet.EncryptedPrivateKey);
|
||||
foreach (var c in _clients.Values.Where(x => string.Equals(x.User.Id, client.User.Id, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
c.User.PublicKey = packet.PublicKey;
|
||||
if (!string.IsNullOrWhiteSpace(packet.EncryptedPrivateKey))
|
||||
{
|
||||
c.User.EncryptedPrivateKey = packet.EncryptedPrivateKey;
|
||||
}
|
||||
}
|
||||
|
||||
await BroadcastUserListAsync();
|
||||
await BroadcastChannelListAsync();
|
||||
|
||||
if (packet.ResetKeys)
|
||||
{
|
||||
var dms = await _db.GetDirectMessagesForUserAsync(client.User.Id, _options.AllowDmE2ee);
|
||||
foreach (var dm in dms)
|
||||
{
|
||||
await BroadcastToMembersAsync(dm.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{client.User.Username} reset their E2EE keypair.",
|
||||
Level = "Warning"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleToggleE2eeAsync(ConnectedClient client, ToggleE2eePacket packet, CancellationToken ct)
|
||||
{
|
||||
string scope = (packet.Scope ?? "dm").Trim().ToLowerInvariant();
|
||||
if (scope == "account")
|
||||
{
|
||||
await _db.SetUserE2eeEnabledAsync(client.User.Id, packet.Enabled);
|
||||
foreach (var c in _clients.Values.Where(x => string.Equals(x.User.Id, client.User.Id, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
c.User.E2eeEnabled = packet.Enabled;
|
||||
}
|
||||
|
||||
await BroadcastUserListAsync();
|
||||
var dms = await _db.GetDirectMessagesForUserAsync(client.User.Id, _options.AllowDmE2ee);
|
||||
var affectedUsers = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { client.User.Id };
|
||||
foreach (var dm in dms)
|
||||
{
|
||||
foreach (var mid in dm.MemberIds) affectedUsers.Add(mid);
|
||||
}
|
||||
await SyncChannelListForUsersAsync(affectedUsers);
|
||||
await BroadcastToMembersAsync(affectedUsers, MessageTypes.SystemNotice, new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{client.User.Username} {(packet.Enabled ? "enabled" : "disabled")} E2EE for their account.",
|
||||
Level = packet.Enabled ? "Success" : "Warning"
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
||||
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
||||
if (channel == null || channel.Type != ChannelTypes.DirectMessage)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Can only toggle per-DM E2EE on a Direct Message." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
||||
if (!isMember)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this Direct Message." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
await _db.SetChannelE2eeAsync(channel.Id, packet.Enabled);
|
||||
await SyncChannelListForUsersAsync(channel.MemberIds);
|
||||
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{client.User.Username} {(packet.Enabled ? "enabled" : "disabled")} E2EE for this Direct Message.",
|
||||
Level = packet.Enabled ? "Success" : "Warning"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleSendMessageAsync(ConnectedClient client, SendMessagePacket packet, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(packet.Content))
|
||||
|
|
@ -229,13 +437,49 @@ public class ChatWebSocketManager
|
|||
}
|
||||
|
||||
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
||||
var channel = await _db.GetChannelByIdAsync(channelId);
|
||||
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
||||
if (channel == null)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Channel does not exist." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify membership for DMs and Group Chats
|
||||
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
||||
{
|
||||
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
||||
if (!isMember)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You do not have access to this conversation." }, ct);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
bool isPayloadEncrypted = packet.IsEncrypted || E2eeCrypto.IsEncryptedPayload(packet.Content);
|
||||
|
||||
if (channel.Type == ChannelTypes.DirectMessage)
|
||||
{
|
||||
if (!_options.AllowDmE2ee && isPayloadEncrypted)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
||||
{
|
||||
Message = "Full E2EE for Direct Messages is disabled on this server.",
|
||||
Code = "E2EE_DISABLED"
|
||||
}, ct);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
string? recipientPubKey = packet.RecipientPublicKey;
|
||||
if (string.IsNullOrWhiteSpace(recipientPubKey) && channel.Type == ChannelTypes.DirectMessage)
|
||||
{
|
||||
var peerId = channel.MemberIds.FirstOrDefault(id => !string.Equals(id, client.User.Id, StringComparison.OrdinalIgnoreCase)) ?? client.User.Id;
|
||||
if (channel.MemberPublicKeys.TryGetValue(peerId, out var foundPeerKey))
|
||||
{
|
||||
recipientPubKey = foundPeerKey;
|
||||
}
|
||||
}
|
||||
|
||||
var message = new ChatMessage
|
||||
{
|
||||
ChannelId = channelId,
|
||||
|
|
@ -243,11 +487,14 @@ public class ChatWebSocketManager
|
|||
SenderUsername = client.User.Username,
|
||||
SenderRole = client.User.Role,
|
||||
Content = packet.Content.Trim(),
|
||||
IsEncrypted = isPayloadEncrypted,
|
||||
SenderPublicKey = packet.SenderPublicKey ?? client.User.PublicKey,
|
||||
RecipientPublicKey = recipientPubKey,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
// Pass through mod pipeline if present
|
||||
if (MessagePipelineInterceptor != null)
|
||||
// Pass through mod pipeline only if not E2EE encrypted
|
||||
if (!message.IsEncrypted && MessagePipelineInterceptor != null)
|
||||
{
|
||||
var processed = await MessagePipelineInterceptor(message);
|
||||
if (processed == null)
|
||||
|
|
@ -260,35 +507,243 @@ public class ChatWebSocketManager
|
|||
|
||||
await _db.SaveMessageAsync(message);
|
||||
|
||||
// Broadcast to all clients currently in this channel
|
||||
await BroadcastToChannelAsync(channelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
|
||||
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
||||
{
|
||||
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
|
||||
}
|
||||
else
|
||||
{
|
||||
await BroadcastToChannelAsync(channelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleJoinChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
|
||||
{
|
||||
var channel = await _db.GetChannelByIdAsync(channelId);
|
||||
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
||||
if (channel == null)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Channel not found." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
||||
{
|
||||
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
||||
if (!isMember)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this conversation." }, ct);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
client.ActiveChannelId = channelId;
|
||||
|
||||
// Send confirmation and history
|
||||
var channels = await _db.GetChannelsAsync();
|
||||
await client.SendMessageAsync(MessageTypes.ChannelListSync, new ChannelListSyncPacket
|
||||
{
|
||||
Channels = channels,
|
||||
ActiveChannelId = client.ActiveChannelId
|
||||
}, ct);
|
||||
await SendChannelListToClientAsync(client, ct);
|
||||
await SendHistoryPageAsync(client, channelId, offset: 0, limit: 50, prepend: false, ct);
|
||||
}
|
||||
|
||||
var history = await _db.GetRecentMessagesAsync(channelId, 50);
|
||||
private async Task HandleStartDmAsync(ConnectedClient client, StartDmPacket packet, CancellationToken ct)
|
||||
{
|
||||
User? targetUser = null;
|
||||
if (!string.IsNullOrWhiteSpace(packet.TargetUserId))
|
||||
{
|
||||
targetUser = await _db.GetUserByIdAsync(packet.TargetUserId.Trim());
|
||||
}
|
||||
if (targetUser == null && !string.IsNullOrWhiteSpace(packet.TargetUsername))
|
||||
{
|
||||
string cleanName = packet.TargetUsername.Trim().TrimStart('@');
|
||||
targetUser = await _db.GetUserByUsernameAsync(cleanName);
|
||||
}
|
||||
|
||||
if (targetUser == null)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Target user not found." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var dmChannel = await _db.GetOrCreateDirectMessageAsync(client.User.Id, targetUser.Id, _options.AllowDmE2ee);
|
||||
client.ActiveChannelId = dmChannel.Id;
|
||||
|
||||
// Sync channel lists for both participants
|
||||
await SyncChannelListForUsersAsync(dmChannel.MemberIds);
|
||||
|
||||
// Send DM history (initial 50 messages, with HasMore flag) to initiating client
|
||||
await SendHistoryPageAsync(client, dmChannel.Id, offset: 0, limit: 50, prepend: false, ct);
|
||||
}
|
||||
|
||||
private async Task HandleCreateGroupAsync(ConnectedClient client, CreateGroupPacket packet, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(packet.Name) || packet.Name.Trim().Length < 2)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Group name must be at least 2 characters." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
int serverMax = Math.Max(2, _options.MaxGroupChatUsers);
|
||||
int groupMax = packet.MaxUsers.HasValue && packet.MaxUsers.Value > 0 ? packet.MaxUsers.Value : serverMax;
|
||||
|
||||
if (groupMax > serverMax)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
||||
{
|
||||
Message = $"Group max user count ({groupMax}) cannot exceed the server setting limit ({serverMax})."
|
||||
}, ct);
|
||||
return;
|
||||
}
|
||||
if (groupMax < 2) groupMax = 2;
|
||||
|
||||
var memberIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { client.User.Id };
|
||||
if (packet.MemberUsernames != null)
|
||||
{
|
||||
foreach (var rawName in packet.MemberUsernames)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(rawName)) continue;
|
||||
var parts = rawName.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (var p in parts)
|
||||
{
|
||||
string cleanUser = p.Trim().TrimStart('@');
|
||||
if (string.IsNullOrWhiteSpace(cleanUser)) continue;
|
||||
var u = await _db.GetUserByUsernameAsync(cleanUser);
|
||||
if (u == null)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = $"User '@{cleanUser}' not found." }, ct);
|
||||
return;
|
||||
}
|
||||
memberIds.Add(u.Id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (memberIds.Count > groupMax)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
||||
{
|
||||
Message = $"Cannot create group chat with {memberIds.Count} members. Maximum allowed is {groupMax}."
|
||||
}, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var group = await _db.CreateGroupChatAsync(packet.Name.Trim(), packet.Topic ?? string.Empty, client.User.Id, memberIds, groupMax);
|
||||
client.ActiveChannelId = group.Id;
|
||||
|
||||
await SyncChannelListForUsersAsync(group.MemberIds);
|
||||
await client.SendMessageAsync(MessageTypes.HistorySync, new HistorySyncPacket
|
||||
{
|
||||
ChannelId = channelId,
|
||||
Messages = history
|
||||
ChannelId = group.Id,
|
||||
Messages = new()
|
||||
}, ct);
|
||||
|
||||
await BroadcastToMembersAsync(
|
||||
group.MemberIds,
|
||||
MessageTypes.SystemNotice,
|
||||
new SystemNoticePacket
|
||||
{
|
||||
Text = $"Group chat '{group.Name}' created by @{client.User.Username} ({group.MemberIds.Count}/{group.MaxUsers} members).",
|
||||
Level = "Success"
|
||||
});
|
||||
}
|
||||
|
||||
private async Task HandleInviteToGroupAsync(ConnectedClient client, InviteToGroupPacket packet, CancellationToken ct)
|
||||
{
|
||||
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
||||
var group = await _db.GetChannelByIdAsync(channelId);
|
||||
if (group == null || group.Type != ChannelTypes.Group)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Active conversation is not a group chat." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!group.MemberIds.Contains(client.User.Id, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this group chat." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
string targetName = (packet.TargetUsername ?? string.Empty).Trim().TrimStart('@');
|
||||
if (string.IsNullOrWhiteSpace(targetName))
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Please specify a username to invite." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var targetUser = await _db.GetUserByUsernameAsync(targetName);
|
||||
if (targetUser == null)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = $"User '@{targetName}' not found." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (group.MemberIds.Contains(targetUser.Id, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = $"@{targetUser.Username} is already a member of '{group.Name}'." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
int effectiveMax = group.MaxUsers > 0 ? Math.Min(group.MaxUsers, _options.MaxGroupChatUsers) : _options.MaxGroupChatUsers;
|
||||
if (group.MemberIds.Count >= effectiveMax)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
||||
{
|
||||
Message = $"Group chat '{group.Name}' has reached the maximum user limit ({effectiveMax})."
|
||||
}, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
await _db.AddGroupMemberAsync(group.Id, targetUser.Id);
|
||||
var updatedGroup = await _db.GetChannelByIdAsync(group.Id);
|
||||
var memberIds = updatedGroup?.MemberIds ?? group.MemberIds;
|
||||
|
||||
await SyncChannelListForUsersAsync(memberIds);
|
||||
await BroadcastToMembersAsync(
|
||||
memberIds,
|
||||
MessageTypes.SystemNotice,
|
||||
new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{targetUser.Username} was added to group '{group.Name}' by @{client.User.Username}.",
|
||||
Level = "Info"
|
||||
});
|
||||
}
|
||||
|
||||
private async Task HandleLeaveGroupAsync(ConnectedClient client, LeaveGroupPacket packet, CancellationToken ct)
|
||||
{
|
||||
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
||||
var group = await _db.GetChannelByIdAsync(channelId);
|
||||
if (group == null || group.Type != ChannelTypes.Group)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Specified conversation is not a group chat." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var previousMembers = new List<string>(group.MemberIds);
|
||||
bool removed = await _db.RemoveGroupMemberAsync(group.Id, client.User.Id);
|
||||
if (!removed)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this group chat." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (client.ActiveChannelId == group.Id)
|
||||
{
|
||||
var channels = await _db.GetChannelsAsync();
|
||||
var general = channels.FirstOrDefault(c => c.Name == "general") ?? channels.FirstOrDefault();
|
||||
client.ActiveChannelId = general?.Id ?? string.Empty;
|
||||
|
||||
if (!string.IsNullOrEmpty(client.ActiveChannelId))
|
||||
{
|
||||
await SendHistoryPageAsync(client, client.ActiveChannelId, offset: 0, limit: 50, prepend: false, ct);
|
||||
}
|
||||
}
|
||||
|
||||
await SyncChannelListForUsersAsync(previousMembers);
|
||||
await SendFileListToClientAsync(client, ct);
|
||||
await BroadcastToMembersAsync(
|
||||
previousMembers.Where(id => !string.Equals(id, client.User.Id, StringComparison.OrdinalIgnoreCase)),
|
||||
MessageTypes.SystemNotice,
|
||||
new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{client.User.Username} left group '{group.Name}'.",
|
||||
Level = "Info"
|
||||
});
|
||||
}
|
||||
|
||||
private async Task HandleCreateChannelAsync(ConnectedClient client, CreateChannelPacket packet, CancellationToken ct)
|
||||
|
|
@ -310,6 +765,7 @@ public class ChatWebSocketManager
|
|||
{
|
||||
Name = cleanName,
|
||||
Topic = packet.Topic?.Trim() ?? string.Empty,
|
||||
Type = ChannelTypes.Channel,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
|
|
@ -341,14 +797,28 @@ public class ChatWebSocketManager
|
|||
var channel = await _db.GetChannelByIdAsync(channelId);
|
||||
if (channel == null) return;
|
||||
|
||||
if (channel.Name == "general")
|
||||
if (channel.Name == "general" && channel.Type == ChannelTypes.Channel)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Cannot delete the default #general channel." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
await _db.DeleteChannelAsync(channelId);
|
||||
|
||||
var channels = await _db.GetChannelsAsync();
|
||||
var fallbackId = (channels.FirstOrDefault(c => c.Name == "general") ?? channels.FirstOrDefault())?.Id ?? string.Empty;
|
||||
|
||||
foreach (var c in _clients.Values.Where(x => x.ActiveChannelId == channelId))
|
||||
{
|
||||
c.ActiveChannelId = fallbackId;
|
||||
if (!string.IsNullOrEmpty(fallbackId))
|
||||
{
|
||||
await SendHistoryPageAsync(c, fallbackId, offset: 0, limit: 50, prepend: false, ct);
|
||||
}
|
||||
}
|
||||
|
||||
await BroadcastChannelListAsync();
|
||||
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c, ct)));
|
||||
await BroadcastSystemNoticeAsync($"Channel #{channel.Name} was deleted.", "Warning");
|
||||
}
|
||||
|
||||
|
|
@ -372,44 +842,141 @@ public class ChatWebSocketManager
|
|||
{
|
||||
case "help":
|
||||
string createDesc = _options.AllowMemberChannelCreation ? "Create a new channel" : "Create a new channel (Admin)";
|
||||
string e2eeStatus = _options.AllowDmE2ee ? "Full E2EE Enabled" : "Server-Visible (E2EE Off)";
|
||||
string helpText = "Available commands:\n" +
|
||||
" /help - Show this help\n" +
|
||||
" /join <channel> - Switch active channel\n" +
|
||||
$" /create <name> [topic]- {createDesc}\n" +
|
||||
" /delete <name> - Delete a channel (Admin)\n" +
|
||||
" /users - List all registered users\n" +
|
||||
" /motd - Display message of the day";
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText }, ct);
|
||||
" /help - Show this help\n" +
|
||||
" /join <channel> - Switch active channel\n" +
|
||||
$" /create <name> [topic] - {createDesc}\n" +
|
||||
" /delete <name> - Delete a channel (Admin)\n" +
|
||||
$" /dm <username> - Open a Direct Message ({e2eeStatus})\n" +
|
||||
" /e2ee pin <passphrase> - Create or unlock E2EE key vault with PIN\n" +
|
||||
" /e2ee reset <new_pin> - Reset E2EE keypair & PIN\n" +
|
||||
" /e2ee dm <on|off> - Toggle E2EE for the active DM\n" +
|
||||
" /e2ee account <on|off> - Toggle E2EE for your entire account\n" +
|
||||
$" /group create <name> [users] - Create a group chat (max {_options.MaxGroupChatUsers} users)\n" +
|
||||
" /group invite <username> - Invite a user to the active group chat\n" +
|
||||
" /group leave - Leave the active group chat\n" +
|
||||
" /users - List all registered users\n" +
|
||||
" /motd - Display message of the day";
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText, ChannelId = packet.ChannelId }, ct);
|
||||
break;
|
||||
|
||||
case "motd":
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}" }, ct);
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}", ChannelId = packet.ChannelId }, ct);
|
||||
break;
|
||||
|
||||
case "users":
|
||||
var users = await _db.GetAllUsersAsync();
|
||||
var userListStr = string.Join("\n", users.Select(u => $" • {u.Username} [{u.Role}]"));
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"Users:\n{userListStr}" }, ct);
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"Users:\n{userListStr}", ChannelId = packet.ChannelId }, ct);
|
||||
break;
|
||||
|
||||
case "dm":
|
||||
string dmTarget = (packet.Args ?? string.Empty).Trim().Split(' ', 2)[0].TrimStart('@');
|
||||
if (string.IsNullOrEmpty(dmTarget))
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = "Usage: /dm <username>", ChannelId = packet.ChannelId }, ct);
|
||||
break;
|
||||
}
|
||||
await HandleStartDmAsync(client, new StartDmPacket { TargetUsername = dmTarget }, ct);
|
||||
break;
|
||||
|
||||
case "e2ee":
|
||||
var e2eeParts = (packet.Args ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (e2eeParts.Length >= 2 && (e2eeParts[0].Equals("dm", StringComparison.OrdinalIgnoreCase) || e2eeParts[0].Equals("account", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
bool enable = e2eeParts[1].Equals("on", StringComparison.OrdinalIgnoreCase) ||
|
||||
e2eeParts[1].Equals("true", StringComparison.OrdinalIgnoreCase) ||
|
||||
e2eeParts[1].Equals("1", StringComparison.OrdinalIgnoreCase);
|
||||
await HandleToggleE2eeAsync(client, new ToggleE2eePacket
|
||||
{
|
||||
Scope = e2eeParts[0].ToLowerInvariant(),
|
||||
ChannelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId,
|
||||
Enabled = enable
|
||||
}, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
||||
{
|
||||
Success = false,
|
||||
Output = "Usage: /e2ee dm <on|off> | /e2ee account <on|off> | /e2ee pin <pin> | /e2ee reset <new_pin>",
|
||||
ChannelId = packet.ChannelId
|
||||
}, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case "group":
|
||||
case "gcreate":
|
||||
string groupArgs = (packet.Args ?? string.Empty).Trim();
|
||||
if (cmd == "gcreate")
|
||||
{
|
||||
groupArgs = "create " + groupArgs;
|
||||
}
|
||||
var gParts = groupArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (gParts.Length == 0)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
||||
{
|
||||
Success = false,
|
||||
Output = "Usage: /group create <name> [user1,user2,...] | /group invite <username> | /group leave",
|
||||
ChannelId = packet.ChannelId
|
||||
}, ct);
|
||||
break;
|
||||
}
|
||||
string subCmd = gParts[0].ToLowerInvariant();
|
||||
if (subCmd == "create" && gParts.Length >= 2)
|
||||
{
|
||||
string gName = gParts[1];
|
||||
var members = gParts.Skip(2).ToList();
|
||||
await HandleCreateGroupAsync(client, new CreateGroupPacket { Name = gName, MemberUsernames = members }, ct);
|
||||
}
|
||||
else if (subCmd == "invite" && gParts.Length >= 2)
|
||||
{
|
||||
await HandleInviteToGroupAsync(client, new InviteToGroupPacket { ChannelId = client.ActiveChannelId, TargetUsername = gParts[1] }, ct);
|
||||
}
|
||||
else if (subCmd == "leave")
|
||||
{
|
||||
await HandleLeaveGroupAsync(client, new LeaveGroupPacket { ChannelId = client.ActiveChannelId }, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
||||
{
|
||||
Success = false,
|
||||
Output = "Usage: /group create <name> [user1,user2,...] | /group invite <username> | /group leave",
|
||||
ChannelId = packet.ChannelId
|
||||
}, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case "invite":
|
||||
string invTarget = (packet.Args ?? string.Empty).Trim();
|
||||
await HandleInviteToGroupAsync(client, new InviteToGroupPacket { ChannelId = client.ActiveChannelId, TargetUsername = invTarget }, ct);
|
||||
break;
|
||||
|
||||
case "leave":
|
||||
await HandleLeaveGroupAsync(client, new LeaveGroupPacket { ChannelId = client.ActiveChannelId }, ct);
|
||||
break;
|
||||
|
||||
case "delete":
|
||||
string channelToDelete = (packet.Args ?? string.Empty).Trim().TrimStart('#');
|
||||
if (string.IsNullOrEmpty(channelToDelete))
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = "Usage: /delete <channel_name>" }, ct);
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = "Usage: /delete <channel_name>", ChannelId = packet.ChannelId }, ct);
|
||||
break;
|
||||
}
|
||||
var chToDelete = await _db.GetChannelByNameAsync(channelToDelete);
|
||||
if (chToDelete == null)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Channel #{channelToDelete} not found." }, ct);
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Channel #{channelToDelete} not found.", ChannelId = packet.ChannelId }, ct);
|
||||
break;
|
||||
}
|
||||
await HandleDeleteChannelAsync(client, chToDelete.Id, ct);
|
||||
break;
|
||||
|
||||
default:
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Unknown command '/{cmd}'. Type /help for available commands." }, ct);
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Unknown command '/{cmd}'. Type /help for available commands.", ChannelId = packet.ChannelId }, ct);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
@ -424,6 +991,17 @@ public class ChatWebSocketManager
|
|||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
public async Task BroadcastToMembersAsync<T>(IEnumerable<string> memberUserIds, string type, T payload)
|
||||
{
|
||||
var memberSet = new HashSet<string>(memberUserIds, StringComparer.OrdinalIgnoreCase);
|
||||
var envelope = NetworkEnvelope.Create(type, payload);
|
||||
var tasks = _clients.Values
|
||||
.Where(c => memberSet.Contains(c.User.Id))
|
||||
.Select(c => c.SendEnvelopeAsync(envelope));
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
public async Task BroadcastToAllAsync<T>(string type, T payload)
|
||||
{
|
||||
var envelope = NetworkEnvelope.Create(type, payload);
|
||||
|
|
@ -445,17 +1023,43 @@ public class ChatWebSocketManager
|
|||
await BroadcastToAllAsync(MessageTypes.UserListSync, new UserListSyncPacket { Users = allUsers });
|
||||
}
|
||||
|
||||
public async Task BroadcastChannelListAsync()
|
||||
public async Task SendChannelListToClientAsync(ConnectedClient client, CancellationToken ct = default)
|
||||
{
|
||||
var channels = await _db.GetChannelsAsync();
|
||||
foreach (var client in _clients.Values)
|
||||
var dms = await _db.GetDirectMessagesForUserAsync(client.User.Id, _options.AllowDmE2ee);
|
||||
var groups = await _db.GetGroupChatsForUserAsync(client.User.Id);
|
||||
|
||||
await client.SendMessageAsync(MessageTypes.ChannelListSync, new ChannelListSyncPacket
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.ChannelListSync, new ChannelListSyncPacket
|
||||
{
|
||||
Channels = channels,
|
||||
ActiveChannelId = client.ActiveChannelId
|
||||
});
|
||||
}
|
||||
Channels = channels,
|
||||
DirectMessages = dms,
|
||||
GroupChats = groups,
|
||||
ActiveChannelId = client.ActiveChannelId
|
||||
}, ct);
|
||||
}
|
||||
|
||||
public Task SyncChannelListForUsersAsync(IEnumerable<string> userIds)
|
||||
{
|
||||
var idSet = new HashSet<string>(userIds, StringComparer.OrdinalIgnoreCase);
|
||||
var tasks = _clients.Values
|
||||
.Where(c => idSet.Contains(c.User.Id))
|
||||
.Select(c => SendChannelListToClientAsync(c));
|
||||
return Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
public Task BroadcastChannelListAsync()
|
||||
{
|
||||
var tasks = _clients.Values.Select(c => SendChannelListToClientAsync(c));
|
||||
return Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
private async Task SendFileListToClientAsync(ConnectedClient client, CancellationToken ct = default)
|
||||
{
|
||||
var allFiles = await _db.GetRecentFilesAsync(100);
|
||||
var accessibleChannelIds = await _db.GetAccessibleChannelIdsForUserAsync(client.User.Id);
|
||||
|
||||
var visibleFiles = allFiles.Where(f => accessibleChannelIds.Contains(f.ChannelId)).ToList();
|
||||
await client.SendMessageAsync(MessageTypes.FileListSync, new FileListSyncPacket { Files = visibleFiles }, ct);
|
||||
}
|
||||
|
||||
public Task BroadcastSystemNoticeAsync(string text, string level = "Info")
|
||||
|
|
@ -463,13 +1067,25 @@ public class ChatWebSocketManager
|
|||
return BroadcastToAllAsync(MessageTypes.SystemNotice, new SystemNoticePacket { Text = text, Level = level });
|
||||
}
|
||||
|
||||
public async Task BroadcastFileUploadedAsync(FileRecord file)
|
||||
public async Task BroadcastFileUploadedAsync(FileRecord file, ChatMessage? savedMessage = null)
|
||||
{
|
||||
var files = await _db.GetRecentFilesAsync(100);
|
||||
await BroadcastToAllAsync(MessageTypes.FileListSync, new FileListSyncPacket { Files = files });
|
||||
var channel = await _db.GetChannelByIdAsync(file.ChannelId);
|
||||
bool isPrivateConv = channel != null && (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group);
|
||||
|
||||
// Broadcast message to channel
|
||||
var msg = new ChatMessage
|
||||
if (isPrivateConv)
|
||||
{
|
||||
var memberSet = new HashSet<string>(channel!.MemberIds, StringComparer.OrdinalIgnoreCase);
|
||||
await Task.WhenAll(_clients.Values
|
||||
.Where(c => memberSet.Contains(c.User.Id))
|
||||
.Select(c => SendFileListToClientAsync(c)));
|
||||
}
|
||||
else
|
||||
{
|
||||
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c)));
|
||||
}
|
||||
|
||||
// Broadcast message to channel or conversation members using the exact saved ChatMessage when available
|
||||
var msg = savedMessage ?? new ChatMessage
|
||||
{
|
||||
ChannelId = file.ChannelId,
|
||||
SenderId = file.UploaderId,
|
||||
|
|
@ -481,6 +1097,13 @@ public class ChatWebSocketManager
|
|||
AttachmentSizeBytes = file.FileSizeBytes
|
||||
};
|
||||
|
||||
await BroadcastToChannelAsync(file.ChannelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = msg });
|
||||
if (isPrivateConv)
|
||||
{
|
||||
await BroadcastToMembersAsync(channel!.MemberIds, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = msg });
|
||||
}
|
||||
else
|
||||
{
|
||||
await BroadcastToChannelAsync(file.ChannelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = msg });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,5 +9,8 @@
|
|||
"DataDirectory": "data",
|
||||
"MaxFileSizeMb": 50,
|
||||
"ServerName": "GsDChat Community Server",
|
||||
"Motd": "Welcome to GsDChat! Enjoy private and modular messaging."
|
||||
"Motd": "Welcome to GsDChat! Enjoy private and modular messaging.",
|
||||
"AllowMemberChannelCreation": true,
|
||||
"AllowDmE2ee": true,
|
||||
"MaxGroupChatUsers": 10
|
||||
}
|
||||
|
|
|
|||
|
|
@ -653,10 +653,58 @@ html, body {
|
|||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.conversations-scroll-area {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: var(--ctp-base);
|
||||
}
|
||||
|
||||
.section-sub-hint {
|
||||
font-size: 0.76rem;
|
||||
color: var(--ctp-subtext0);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.conv-security-badge {
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
padding: 1px 6px;
|
||||
border: 1px solid var(--ctp-surface2);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.conv-security-badge.e2ee-on {
|
||||
color: var(--ctp-green);
|
||||
border-color: var(--ctp-green);
|
||||
background-color: rgba(166, 227, 161, 0.12);
|
||||
}
|
||||
|
||||
.conv-security-badge.e2ee-off {
|
||||
color: var(--ctp-yellow);
|
||||
border-color: var(--ctp-yellow);
|
||||
background-color: rgba(249, 226, 175, 0.12);
|
||||
}
|
||||
|
||||
.conv-security-badge.group-badge {
|
||||
color: var(--ctp-mauve);
|
||||
border-color: var(--ctp-mauve);
|
||||
background-color: rgba(203, 166, 247, 0.12);
|
||||
}
|
||||
|
||||
.msg-e2ee-tag {
|
||||
font-size: 0.66rem;
|
||||
font-weight: 700;
|
||||
padding: 1px 4px;
|
||||
color: var(--ctp-green);
|
||||
border: 1px solid var(--ctp-green);
|
||||
background-color: rgba(166, 227, 161, 0.1);
|
||||
}
|
||||
|
||||
.channel-list,
|
||||
.user-list,
|
||||
.files-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 10px;
|
||||
display: flex;
|
||||
|
|
@ -665,6 +713,11 @@ html, body {
|
|||
background-color: var(--ctp-base);
|
||||
}
|
||||
|
||||
.user-list,
|
||||
.files-list {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.channel-item,
|
||||
.user-item,
|
||||
.file-item {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -46,7 +46,7 @@
|
|||
|
||||
<nav class="nav-tabs" id="navTabs">
|
||||
<button class="nav-tab active" data-tab="chat">[1:chat]</button>
|
||||
<button class="nav-tab" data-tab="channels">[2:channels]</button>
|
||||
<button class="nav-tab" data-tab="channels">[2:channels/dms]</button>
|
||||
<button class="nav-tab" data-tab="users">[3:users]</button>
|
||||
<button class="nav-tab" data-tab="files">[4:files]</button>
|
||||
</nav>
|
||||
|
|
@ -56,6 +56,7 @@
|
|||
<span class="user-name" id="currentUsername"></span>
|
||||
<span class="user-role" id="currentUserRole"></span>
|
||||
</div>
|
||||
<button class="btn btn-secondary btn-sm" id="e2eeVaultBtn" title="Manage E2EE PIN Vault & Encryption Settings" style="display:none;">[🔒 E2EE Vault]</button>
|
||||
<button class="btn btn-outline-danger btn-sm" id="logoutBtn" title="Logout">[Disconnect]</button>
|
||||
</div>
|
||||
</header>
|
||||
|
|
@ -67,13 +68,17 @@
|
|||
<section id="view-chat" class="tab-view active">
|
||||
<div class="chat-header">
|
||||
<div class="channel-info">
|
||||
<span class="channel-hash">#</span>
|
||||
<select class="channel-dropdown" id="channelSelectDropdown" title="Switch Channel">
|
||||
<span class="channel-hash" id="activeConvPrefix">#</span>
|
||||
<select class="channel-dropdown" id="channelSelectDropdown" title="Switch Conversation">
|
||||
<option value="">general</option>
|
||||
</select>
|
||||
<span class="conv-security-badge" id="chatSecurityBadge" style="display:none; cursor:pointer;" title="Click to manage E2EE settings"></span>
|
||||
<span class="channel-topic" id="activeChannelTopic"></span>
|
||||
</div>
|
||||
<div class="chat-header-actions">
|
||||
<button type="button" class="btn btn-sm btn-secondary" id="toggleDmE2eeBtn" style="display:none;" title="Toggle E2EE for this Direct Message">[DM E2EE: ON]</button>
|
||||
<button type="button" class="btn btn-sm btn-secondary" id="inviteGroupBtn" style="display:none;" title="Invite User to Group">[+ Invite]</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-danger" id="leaveGroupBtn" style="display:none;" title="Leave Group">[Leave]</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-members" id="toggleMembersBtn" title="Toggle Online Members">
|
||||
[●] <span class="members-btn-label">Online</span> (<span id="chatHeaderOnlineCount">0</span>)
|
||||
</button>
|
||||
|
|
@ -85,7 +90,7 @@
|
|||
<div class="chat-messages" id="chatMessages">
|
||||
<div class="welcome-message">
|
||||
<div class="welcome-motd" id="welcomeMotd">== Connected to GsDChat ==</div>
|
||||
<div class="welcome-hint">> Select a channel or enter a message below. Type /help for commands.</div>
|
||||
<div class="welcome-hint">> Select a channel, group, or DM below. Type /help for commands.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -112,30 +117,88 @@
|
|||
</div>
|
||||
</section>
|
||||
|
||||
<!-- View 2: Channels View -->
|
||||
<!-- View 2: Channels, Groups & DMs View -->
|
||||
<section id="view-channels" class="tab-view">
|
||||
<div class="view-header">
|
||||
<h2>== SERVER CHANNELS ==</h2>
|
||||
<button class="btn btn-primary" id="openCreateChannelBtn" style="display:none;">[+] Create Channel</button>
|
||||
</div>
|
||||
<div class="channel-list" id="channelList">
|
||||
<!-- Populated by JS -->
|
||||
</div>
|
||||
<div class="conversations-scroll-area">
|
||||
<!-- Server Channels Section -->
|
||||
<div class="view-header">
|
||||
<h2>== SERVER CHANNELS ==</h2>
|
||||
<button class="btn btn-primary btn-sm" id="openCreateChannelBtn" style="display:none;">[+] Create Channel</button>
|
||||
</div>
|
||||
|
||||
<!-- Channel Creation Form -->
|
||||
<div class="card channel-create-card" id="createChannelCard" style="display:none;">
|
||||
<h3>[+] Create New Channel</h3>
|
||||
<div class="form-group">
|
||||
<label for="newChannelName">Channel Name</label>
|
||||
<input type="text" id="newChannelName" placeholder="e.g. gaming, dev, music">
|
||||
<div class="card channel-create-card" id="createChannelCard" style="display:none;">
|
||||
<h3>[+] Create New Channel</h3>
|
||||
<div class="form-group">
|
||||
<label for="newChannelName">Channel Name</label>
|
||||
<input type="text" id="newChannelName" placeholder="e.g. gaming, dev, music">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="newChannelTopic">Topic (Optional)</label>
|
||||
<input type="text" id="newChannelTopic" placeholder="Channel description...">
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button class="btn btn-primary" id="submitCreateChannelBtn">[Create]</button>
|
||||
<button class="btn btn-secondary" id="cancelCreateChannelBtn">[Cancel]</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="newChannelTopic">Topic (Optional)</label>
|
||||
<input type="text" id="newChannelTopic" placeholder="Channel description...">
|
||||
|
||||
<div class="channel-list" id="channelList">
|
||||
<!-- Populated by JS -->
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button class="btn btn-primary" id="submitCreateChannelBtn">[Create]</button>
|
||||
<button class="btn btn-secondary" id="cancelCreateChannelBtn">[Cancel]</button>
|
||||
|
||||
<!-- Group Chats Section -->
|
||||
<div class="view-header">
|
||||
<h2>== GROUP CHATS <span id="maxGroupUsersHint" class="section-sub-hint">(Max 10 users)</span> ==</h2>
|
||||
<button class="btn btn-primary btn-sm" id="openCreateGroupBtn">[+] Create Group</button>
|
||||
</div>
|
||||
|
||||
<div class="card channel-create-card" id="createGroupCard" style="display:none;">
|
||||
<h3>[+] Create New Group Chat</h3>
|
||||
<div class="form-group">
|
||||
<label for="newGroupName">Group Name</label>
|
||||
<input type="text" id="newGroupName" placeholder="e.g. Squad, Project Alpha">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="newGroupMembers">Initial Members (comma-separated usernames)</label>
|
||||
<input type="text" id="newGroupMembers" placeholder="e.g. Bob, Charlie">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="newGroupTopic">Topic (Optional)</label>
|
||||
<input type="text" id="newGroupTopic" placeholder="Group topic...">
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button class="btn btn-primary" id="submitCreateGroupBtn">[Create Group]</button>
|
||||
<button class="btn btn-secondary" id="cancelCreateGroupBtn">[Cancel]</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="channel-list" id="groupChatList">
|
||||
<!-- Populated by JS -->
|
||||
</div>
|
||||
|
||||
<!-- Direct Messages Section -->
|
||||
<div class="view-header">
|
||||
<h2>== DIRECT MESSAGES <span id="dmE2eeStatusHint" class="section-sub-hint">[Full E2EE]</span> ==</h2>
|
||||
<div style="display:flex; gap:6px;">
|
||||
<button class="btn btn-secondary btn-sm" id="openE2eeSettingsBtn" title="Manage E2EE PIN & Account Encryption">[🔒 E2EE Vault]</button>
|
||||
<button class="btn btn-primary btn-sm" id="openStartDmBtn">[+] New DM</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card channel-create-card" id="startDmCard" style="display:none;">
|
||||
<h3>[+] Start Direct Message</h3>
|
||||
<div class="form-group">
|
||||
<label for="dmTargetUsername">Recipient Username</label>
|
||||
<input type="text" id="dmTargetUsername" placeholder="Enter @username">
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button class="btn btn-primary" id="submitStartDmBtn">[Open DM]</button>
|
||||
<button class="btn btn-secondary" id="cancelStartDmBtn">[Cancel]</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="channel-list" id="dmList">
|
||||
<!-- Populated by JS -->
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
|
@ -170,6 +233,42 @@
|
|||
<!-- Toast Notification Overlay -->
|
||||
<div id="toastContainer" class="toast-container"></div>
|
||||
|
||||
<!-- E2EE PIN / Key Vault Modal -->
|
||||
<div id="e2eeModal" class="modal-backdrop" style="display:none;">
|
||||
<div class="modal-card">
|
||||
<div class="modal-header">
|
||||
<div class="modal-badge">[ ZERO-KNOWLEDGE E2EE KEY VAULT ]</div>
|
||||
<h2 id="e2eeModalTitle">Direct Message Encryption</h2>
|
||||
<p class="modal-motd" id="e2eeModalSubtitle">Your E2EE PIN is never sent to the server. It wraps your P-256 keypair so you never lose DM history across devices.</p>
|
||||
</div>
|
||||
|
||||
<div id="e2eeVaultStatusBanner" class="system-notice" style="margin-bottom:12px;">
|
||||
Status: Checking E2EE Key Vault...
|
||||
</div>
|
||||
|
||||
<form id="e2eePinForm" class="auth-form" onsubmit="return false;">
|
||||
<div class="form-group">
|
||||
<label for="e2eePinInput" id="e2eePinLabel">Enter E2EE PIN / Passphrase</label>
|
||||
<input type="password" id="e2eePinInput" placeholder="Enter your dedicated E2EE PIN or passphrase..." autocomplete="off">
|
||||
</div>
|
||||
|
||||
<div class="auth-error" id="e2eeModalError"></div>
|
||||
|
||||
<button type="submit" class="btn btn-primary btn-block" id="e2eeSubmitPinBtn">[ Unlock / Initialize E2EE Vault ]</button>
|
||||
</form>
|
||||
|
||||
<div class="form-actions" style="flex-wrap:wrap; margin-top:12px;">
|
||||
<button type="button" class="btn btn-secondary btn-sm" id="e2eeToggleAccountBtn" style="flex:1;">[Account E2EE: ON]</button>
|
||||
<button type="button" class="btn btn-secondary btn-sm" id="e2eeLockDeviceBtn" style="flex:1;">[Lock This Device]</button>
|
||||
<button type="button" class="btn btn-outline-danger btn-sm" id="e2eeResetPinBtn" style="flex:1;" title="Forgot your E2EE PIN? Enter a new PIN above and click here to generate a fresh keypair.">[Reset PIN / New Keys]</button>
|
||||
</div>
|
||||
|
||||
<div style="margin-top:10px;">
|
||||
<button type="button" class="btn btn-secondary btn-block btn-sm" id="e2eeCloseModalBtn">[ Close / Continue ]</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Auth Modal (Login / Register) -->
|
||||
<div id="authModal" class="modal-backdrop">
|
||||
<div class="modal-card">
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue