From 7cc9ba7f4d6eff200aa21fe26c24deb2b30c54c7 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 31 Oct 2026 15:41:51 +0300 Subject: [PATCH] Add persistent Inbox and RFC 8291/8292 Web Push notification system --- .../Network/ChatClientConnection.cs | 99 +++ src/GsDChat.Client/Rendering/ConsoleUi.cs | 27 +- src/GsDChat.Client/Screens/ChannelsScreen.cs | 20 +- src/GsDChat.Client/Screens/ChatScreen.cs | 19 + src/GsDChat.Client/Screens/InboxScreen.cs | 208 ++++++ src/GsDChat.Client/State/ClientState.cs | 56 ++ src/GsDChat.Core/Models/InboxModels.cs | 63 ++ src/GsDChat.Core/Protocol/HttpModels.cs | 14 + src/GsDChat.Core/Protocol/NetworkMessages.cs | 40 + src/GsDChat.Core/Protocol/UiProtocol.cs | 13 + src/GsDChat.Core/Security/WebPushCrypto.cs | 323 +++++++++ .../Configuration/ServerOptions.cs | 5 + .../Configuration/ServerSettingsManager.cs | 8 + src/GsDChat.Server/Data/ChatDatabase.cs | 427 +++++++++++ src/GsDChat.Server/Program.cs | 70 +- src/GsDChat.Server/Services/WebPushService.cs | 209 ++++++ .../WebSockets/ChatWebSocketManager.cs | 540 +++++++++++++- src/GsDChat.Server/wwwroot/app.css | 134 +++- src/GsDChat.Server/wwwroot/app.js | 682 +++++++++++++++++- src/GsDChat.Server/wwwroot/index.html | 34 + src/GsDChat.Server/wwwroot/manifest.json | 10 + src/GsDChat.Server/wwwroot/sw.js | 104 +++ tests/GsDChat.Tests/CryptoTests.cs | 51 ++ tests/GsDChat.Tests/DatabaseTests.cs | 106 +++ tests/GsDChat.Tests/EndToEndChatTests.cs | 280 ++++++- tests/GsDChat.Tests/NetworkProtocolTests.cs | 22 +- tests/GsDChat.Tests/WebClientStaticTests.cs | 26 + 27 files changed, 3573 insertions(+), 17 deletions(-) create mode 100644 src/GsDChat.Client/Screens/InboxScreen.cs create mode 100644 src/GsDChat.Core/Models/InboxModels.cs create mode 100644 src/GsDChat.Core/Security/WebPushCrypto.cs create mode 100644 src/GsDChat.Server/Services/WebPushService.cs create mode 100644 src/GsDChat.Server/wwwroot/manifest.json create mode 100644 src/GsDChat.Server/wwwroot/sw.js diff --git a/src/GsDChat.Client/Network/ChatClientConnection.cs b/src/GsDChat.Client/Network/ChatClientConnection.cs index de10306..29ccdae 100644 --- a/src/GsDChat.Client/Network/ChatClientConnection.cs +++ b/src/GsDChat.Client/Network/ChatClientConnection.cs @@ -326,6 +326,13 @@ public class ChatClientConnection : IDisposable DecryptMessageIfNeeded(msg); } } + foreach (var item in _state.GetInboxItems()) + { + if (E2eeCrypto.IsEncryptedPayload(item.ContentPreview)) + { + DecryptInboxItemIfNeeded(item); + } + } _state.NeedsRedraw = true; } @@ -462,6 +469,28 @@ public class ChatClientConnection : IDisposable } break; + case MessageTypes.InboxSync: + var inSync = envelope.Unpack(); + if (inSync != null) + { + foreach (var item in inSync.Items) + { + DecryptInboxItemIfNeeded(item); + } + _state.SetInboxSync(inSync.Items, inSync.UnreadCount, inSync.Preferences); + } + break; + + case MessageTypes.InboxNewItem: + var inNew = envelope.Unpack(); + if (inNew != null && inNew.Item != null) + { + DecryptInboxItemIfNeeded(inNew.Item); + _state.AddOrUpdateInboxItem(inNew.Item, inNew.UnreadCount); + _state.SetStatus($"[Inbox] New {inNew.Item.Category} from @{inNew.Item.SenderUsername} (Press F5)", 4); + } + break; + case MessageTypes.SystemNotice: var notice = envelope.Unpack(); if (notice != null) @@ -562,6 +591,43 @@ public class ChatClientConnection : IDisposable } } + private void DecryptInboxItemIfNeeded(InboxItem item) + { + if (!item.IsEncrypted && !E2eeCrypto.IsEncryptedPayload(item.ContentPreview)) + { + return; + } + + item.IsEncrypted = true; + + if (!E2eeCrypto.IsEncryptedPayload(item.ContentPreview) || string.IsNullOrWhiteSpace(_state.PrivateKeyBase64)) + { + return; + } + + string? peerPubKey = !string.IsNullOrWhiteSpace(item.SenderPublicKey) + ? item.SenderPublicKey + : item.RecipientPublicKey; + + if (string.IsNullOrWhiteSpace(peerPubKey)) + { + var conv = _state.GetConversationById(item.ChannelId); + if (conv != null) + { + peerPubKey = _state.GetPeerPublicKeyForDm(conv); + } + } + + if (!string.IsNullOrWhiteSpace(peerPubKey)) + { + string decrypted = E2eeCrypto.DecryptMessage(item.ContentPreview, _state.PrivateKeyBase64, peerPubKey); + if (!decrypted.StartsWith("[Encrypted Message")) + { + item.ContentPreview = decrypted; + } + } + } + public async Task SendEnvelopeAsync(NetworkEnvelope envelope) { if (_webSocket == null || _webSocket.State != WebSocketState.Open) return; @@ -753,6 +819,39 @@ public class ChatClientConnection : IDisposable return SendEnvelopeAsync(envelope); } + public Task RequestInboxSyncAsync() + { + var envelope = NetworkEnvelope.Create(MessageTypes.InboxSync, new { }); + return SendEnvelopeAsync(envelope); + } + + public Task SendInboxActionAsync(string action, string? itemId = null, string? channelId = null) + { + var envelope = NetworkEnvelope.Create(MessageTypes.InboxAction, new InboxActionPacket + { + Action = action, + ItemId = itemId, + ChannelId = channelId + }); + return SendEnvelopeAsync(envelope); + } + + public Task UpdateInboxPreferencesAsync(UpdateInboxPreferencesPacket packet) + { + var envelope = NetworkEnvelope.Create(MessageTypes.UpdateInboxPreferences, packet); + return SendEnvelopeAsync(envelope); + } + + public Task ToggleFollowChannelAsync(string channelId, bool? follow = null) + { + var envelope = NetworkEnvelope.Create(MessageTypes.ToggleFollowChannel, new ToggleFollowChannelPacket + { + ChannelId = channelId, + Follow = follow + }); + return SendEnvelopeAsync(envelope); + } + public async Task UploadFileAsync(string localFilePath, string channelId) { if (!File.Exists(localFilePath)) diff --git a/src/GsDChat.Client/Rendering/ConsoleUi.cs b/src/GsDChat.Client/Rendering/ConsoleUi.cs index f6472f9..db676d8 100644 --- a/src/GsDChat.Client/Rendering/ConsoleUi.cs +++ b/src/GsDChat.Client/Rendering/ConsoleUi.cs @@ -27,6 +27,7 @@ public class ConsoleUi RegisterScreen(new ChannelsScreen(state, connection)); RegisterScreen(new UsersScreen(state, connection)); RegisterScreen(new FilesScreen(state, connection)); + RegisterScreen(new InboxScreen(state, connection)); } public void RegisterScreen(IScreen screen) @@ -117,9 +118,15 @@ public class ConsoleUi if (_state.ActiveScreenId != "F4_Files") { _state.ActiveScreenId = "F4_Files"; Console.Clear(); } _state.NeedsRedraw = true; } - else if (key.Key == ConsoleKey.F5 && _screens.ContainsKey("F5_Custom")) + else if (key.Key == ConsoleKey.F5) { - if (_state.ActiveScreenId != "F5_Custom") { _state.ActiveScreenId = "F5_Custom"; Console.Clear(); } + if (_state.ActiveScreenId != "F5_Inbox") { _state.ActiveScreenId = "F5_Inbox"; Console.Clear(); } + _state.NeedsRedraw = true; + } + else if (key.Key == ConsoleKey.F6 && (_screens.ContainsKey("F6_Custom") || _screens.ContainsKey("F5_Custom"))) + { + string customKey = _screens.ContainsKey("F6_Custom") ? "F6_Custom" : "F5_Custom"; + if (_state.ActiveScreenId != customKey) { _state.ActiveScreenId = customKey; Console.Clear(); } _state.NeedsRedraw = true; } else @@ -227,13 +234,23 @@ public class ConsoleUi foreach (var screen in _screens.Values) { bool isActive = screen.ScreenId == _state.ActiveScreenId; + string titleLabel = screen.Title; + if (screen.ScreenId == "F5_Inbox" && _state.UnreadInboxCount > 0) + { + titleLabel = $"Inbox ({_state.UnreadInboxCount})"; + } + if (isActive) { - sb.Append($"{Ansi.Inverse}{Ansi.Bold}[ {screen.ShortcutKey}: {screen.Title} ]{Ansi.Reset} "); + sb.Append($"{Ansi.Inverse}{Ansi.Bold}[ {screen.ShortcutKey}: {titleLabel} ]{Ansi.Reset} "); + } + else if (screen.ScreenId == "F5_Inbox" && _state.UnreadInboxCount > 0) + { + sb.Append($"{Ansi.BrightYellow}{Ansi.Bold}[ {screen.ShortcutKey}: {titleLabel} ]{Ansi.Reset} "); } else { - sb.Append($"{Ansi.Gray}[ {screen.ShortcutKey}: {screen.Title} ]{Ansi.Reset} "); + sb.Append($"{Ansi.Gray}[ {screen.ShortcutKey}: {titleLabel} ]{Ansi.Reset} "); } } @@ -260,7 +277,7 @@ public class ConsoleUi } else { - status = $"{connStatus} │ {userBadge}{Ansi.Gray}F1-F4: Tabs │ /help: Commands │ Ctrl+C: Quit{Ansi.Reset}"; + status = $"{connStatus} │ {userBadge}{Ansi.Gray}F1-F5: Tabs │ /help: Commands │ Ctrl+C: Quit{Ansi.Reset}"; } sb.AppendLine($" {status}"); diff --git a/src/GsDChat.Client/Screens/ChannelsScreen.cs b/src/GsDChat.Client/Screens/ChannelsScreen.cs index 6cef530..bbe2d4b 100644 --- a/src/GsDChat.Client/Screens/ChannelsScreen.cs +++ b/src/GsDChat.Client/Screens/ChannelsScreen.cs @@ -122,7 +122,7 @@ public class ChannelsScreen : IScreen 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}"); + sb.AppendLine($" {Ansi.Gray}[↑/↓] Select [Enter] Open [F] Follow/Mute [C] Channel [G] Group [M] DM [E] DM E2EE [A] Acct E2EE [L/D] Leave/Del{Ansi.Reset}"); break; } } @@ -130,17 +130,22 @@ public class ChannelsScreen : IScreen private void RenderItem(StringBuilder sb, Channel ch, bool isSelected, string label, string subtitle) { bool isActive = ch.Id == _state.ActiveChannelId; + bool isFollowed = _state.IsConversationFollowed(ch); + string followTag = ch.Type == ChannelTypes.Channel + ? (isFollowed ? $" {Ansi.BrightCyan}[🔔 Following]{Ansi.Reset}" : "") + : (!isFollowed ? $" {Ansi.BrightRed}[🔕 Muted]{Ansi.Reset}" : $" {Ansi.Gray}[🔔]{Ansi.Reset}"); + 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}"); + sb.AppendLine($"{prefix}{Ansi.Inverse}{label}{Ansi.Reset}{activeTag}{followTag}{sub}"); } else { - sb.AppendLine($"{prefix}{Ansi.Bold}{label}{Ansi.Reset}{activeTag}{sub}"); + sb.AppendLine($"{prefix}{Ansi.Bold}{label}{Ansi.Reset}{activeTag}{followTag}{sub}"); } } @@ -286,6 +291,15 @@ public class ChannelsScreen : IScreen _state.SetStatus($"Toggled account-wide E2EE to {(!_state.AccountE2eeEnabled ? "ON" : "OFF")}."); _state.NeedsRedraw = true; } + else if (key.Key == ConsoleKey.F) + { + if (_selectedIndex >= 0 && _selectedIndex < all.Count) + { + var selected = all[_selectedIndex]; + await _connection.ToggleFollowChannelAsync(selected.Id); + _state.NeedsRedraw = true; + } + } else if (key.Key == ConsoleKey.L || key.Key == ConsoleKey.D) { if (_selectedIndex >= 0 && _selectedIndex < all.Count) diff --git a/src/GsDChat.Client/Screens/ChatScreen.cs b/src/GsDChat.Client/Screens/ChatScreen.cs index 8c7fb63..631b52d 100644 --- a/src/GsDChat.Client/Screens/ChatScreen.cs +++ b/src/GsDChat.Client/Screens/ChatScreen.cs @@ -429,6 +429,25 @@ public class ChatScreen : IScreen await _connection.LeaveGroupAsync(_state.ActiveChannelId); break; + case "inbox": + if (string.IsNullOrWhiteSpace(args)) + { + await _connection.RequestInboxSyncAsync(); + _state.ActiveScreenId = "F5_Inbox"; + _state.NeedsRedraw = true; + } + else + { + await _connection.ExecuteCommandAsync(cmd, args, _state.ActiveChannelId); + } + break; + + case "follow": + case "unfollow": + case "mute": + await _connection.ExecuteCommandAsync(cmd, args, _state.ActiveChannelId); + break; + case "upload": if (string.IsNullOrEmpty(args)) { diff --git a/src/GsDChat.Client/Screens/InboxScreen.cs b/src/GsDChat.Client/Screens/InboxScreen.cs new file mode 100644 index 0000000..35b7fca --- /dev/null +++ b/src/GsDChat.Client/Screens/InboxScreen.cs @@ -0,0 +1,208 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using GsDChat.Client.Network; +using GsDChat.Client.Rendering; +using GsDChat.Client.State; +using GsDChat.Core.Models; +using GsDChat.Core.Protocol; + +namespace GsDChat.Client.Screens; + +public class InboxScreen : IScreen +{ + private readonly ClientState _state; + private readonly ChatClientConnection _connection; + private int _selectedIndex = 0; + + public string ScreenId => "F5_Inbox"; + public string Title => "Inbox"; + public string ShortcutKey => "F5"; + + public InboxScreen(ClientState state, ChatClientConnection connection) + { + _state = state; + _connection = connection; + } + + public void Render(int width, int height, StringBuilder sb) + { + var items = _state.GetInboxItems(); + var prefs = _state.InboxPreferences; + + string unreadTag = _state.UnreadInboxCount > 0 + ? $"{Ansi.BrightYellow}({_state.UnreadInboxCount} unread){Ansi.Reset}" + : $"{Ansi.Gray}(All caught up){Ansi.Reset}"; + + sb.AppendLine($" {Ansi.Bold}{Ansi.Yellow}User Inbox{Ansi.Reset} {unreadTag}"); + + string mTag = prefs.MentionsEnabled ? $"{Ansi.BrightGreen}ON{Ansi.Reset}" : $"{Ansi.BrightRed}OFF{Ansi.Reset}"; + string aTag = prefs.AnnouncementsEnabled ? $"{Ansi.BrightGreen}ON{Ansi.Reset}" : $"{Ansi.BrightRed}OFF{Ansi.Reset}"; + string dTag = prefs.DirectMessagesEnabled ? $"{Ansi.BrightGreen}ON{Ansi.Reset}" : $"{Ansi.BrightRed}OFF{Ansi.Reset}"; + string fTag = prefs.FollowedChannelsEnabled ? $"{Ansi.BrightGreen}ON{Ansi.Reset}" : $"{Ansi.BrightRed}OFF{Ansi.Reset}"; + + sb.AppendLine($" {Ansi.Gray}Settings:{Ansi.Reset} [1] Mentions: {mTag} │ [2] Announcements: {aTag} │ [3] DMs/Groups: {dTag} │ [4] Followed Channels: {fTag}"); + sb.AppendLine(new string('─', Math.Max(0, width - 1))); + + int maxVisible = Math.Max(4, height - 10); + + if (items.Count == 0) + { + sb.AppendLine($" {Ansi.Gray}Your Inbox is empty.{Ansi.Reset}"); + sb.AppendLine($" {Ansi.Gray}Mentions (@username), announcements, DMs, and followed channels will appear here.{Ansi.Reset}"); + sb.AppendLine($" {Ansi.Gray}Tip: Press F2 and hit [F] on any channel or DM to follow/mute it.{Ansi.Reset}"); + } + else + { + if (_selectedIndex >= items.Count) _selectedIndex = items.Count - 1; + if (_selectedIndex < 0) _selectedIndex = 0; + + int startIdx = 0; + if (_selectedIndex >= maxVisible) + { + startIdx = _selectedIndex - maxVisible + 1; + } + int endIdx = Math.Min(items.Count, startIdx + maxVisible); + + for (int i = startIdx; i < endIdx; i++) + { + var item = items[i]; + bool isSelected = i == _selectedIndex; + string cursor = isSelected ? $"{Ansi.BrightYellow}► " : " "; + string readDot = item.IsRead + ? $"{Ansi.Gray}○{Ansi.Reset}" + : $"{Ansi.BrightYellow}●{Ansi.Reset}"; + + string catBadge = item.Category switch + { + InboxCategories.Mention => $"{Ansi.BrightCyan}[@Mention]{Ansi.Reset}", + InboxCategories.Announcement => $"{Ansi.BrightMagenta}[📢 Announce]{Ansi.Reset}", + InboxCategories.DirectMessage => $"{Ansi.BrightGreen}[DM]{Ansi.Reset}", + InboxCategories.GroupMessage => $"{Ansi.BrightMagenta}[Group]{Ansi.Reset}", + InboxCategories.GroupInvite => $"{Ansi.BrightYellow}[Invite]{Ansi.Reset}", + _ => $"{Ansi.Cyan}[#Followed]{Ansi.Reset}" + }; + + string convLabel = item.ChannelType switch + { + ChannelTypes.DirectMessage => $"@{item.ChannelName.TrimStart('@')}", + ChannelTypes.Group => $"[Group] {item.ChannelName}", + _ => $"#{item.ChannelName}" + }; + + string time = item.CreatedAt.ToLocalTime().ToString("MM-dd HH:mm"); + string preview = item.ContentPreview ?? string.Empty; + if (preview.StartsWith("E2EE:v1:", StringComparison.Ordinal)) + { + preview = !_state.HasUnlockedE2eeKey + ? "[🔒 Encrypted Message — Unlock E2EE PIN]" + : "[🔒 Encrypted Message]"; + } + preview = preview.Replace("\r", " ").Replace("\n", " "); + if (preview.Length > 60) + { + preview = preview[..57] + "..."; + } + + if (isSelected) + { + sb.AppendLine($"{cursor}{readDot} {catBadge} {Ansi.Inverse} {convLabel} {Ansi.Reset} {Ansi.Gray}[{time}]{Ansi.Reset} <@{item.SenderUsername}> {preview}"); + } + else + { + string titleStyle = item.IsRead ? Ansi.Gray : Ansi.Bold; + sb.AppendLine($"{cursor}{readDot} {catBadge} {titleStyle}{convLabel}{Ansi.Reset} {Ansi.Gray}[{time}]{Ansi.Reset} <@{item.SenderUsername}> {preview}"); + } + } + } + + sb.AppendLine(new string('─', Math.Max(0, width - 1))); + sb.AppendLine($" {Ansi.Gray}[↑/↓] Select [Enter] Open Chat [R] Mark Read [A] Mark All Read [D] Dismiss [C] Clear Read [1-4] Toggle Prefs{Ansi.Reset}"); + } + + public async Task HandleKeyAsync(ConsoleKeyInfo key) + { + var items = _state.GetInboxItems(); + var prefs = _state.InboxPreferences; + + if (key.Key == ConsoleKey.UpArrow) + { + _selectedIndex = Math.Max(0, _selectedIndex - 1); + _state.NeedsRedraw = true; + } + else if (key.Key == ConsoleKey.DownArrow) + { + _selectedIndex = Math.Min(Math.Max(0, items.Count - 1), _selectedIndex + 1); + _state.NeedsRedraw = true; + } + else if (key.Key == ConsoleKey.Enter) + { + if (_selectedIndex >= 0 && _selectedIndex < items.Count) + { + var selected = items[_selectedIndex]; + await _connection.SendInboxActionAsync("mark_read", itemId: selected.Id, channelId: selected.ChannelId); + if (!string.IsNullOrWhiteSpace(selected.ChannelId)) + { + await _connection.JoinChannelAsync(selected.ChannelId); + _state.ActiveScreenId = "F1_Chat"; + _state.SetStatus($"Opened {selected.ChannelName} from Inbox."); + } + _state.NeedsRedraw = true; + } + } + else if (key.Key == ConsoleKey.R) + { + if (_selectedIndex >= 0 && _selectedIndex < items.Count) + { + var selected = items[_selectedIndex]; + await _connection.SendInboxActionAsync("mark_read", itemId: selected.Id); + _state.SetStatus("Marked item as read."); + } + } + else if (key.Key == ConsoleKey.A) + { + await _connection.SendInboxActionAsync("mark_all_read"); + _state.SetStatus("Marked all Inbox items as read."); + } + else if (key.Key == ConsoleKey.D || key.Key == ConsoleKey.Delete) + { + if (_selectedIndex >= 0 && _selectedIndex < items.Count) + { + var selected = items[_selectedIndex]; + await _connection.SendInboxActionAsync("dismiss", itemId: selected.Id); + _state.SetStatus("Dismissed Inbox item."); + } + } + else if (key.Key == ConsoleKey.C) + { + bool clearAll = (key.Modifiers & ConsoleModifiers.Shift) != 0; + await _connection.SendInboxActionAsync(clearAll ? "clear_all" : "clear_read"); + _state.SetStatus(clearAll ? "Cleared all Inbox items." : "Cleared read Inbox items."); + } + else if (key.Key == ConsoleKey.D1 || key.Key == ConsoleKey.NumPad1) + { + bool next = !prefs.MentionsEnabled; + await _connection.UpdateInboxPreferencesAsync(new UpdateInboxPreferencesPacket { MentionsEnabled = next }); + _state.SetStatus($"Mention notifications {(next ? "enabled" : "disabled")}."); + } + else if (key.Key == ConsoleKey.D2 || key.Key == ConsoleKey.NumPad2) + { + bool next = !prefs.AnnouncementsEnabled; + await _connection.UpdateInboxPreferencesAsync(new UpdateInboxPreferencesPacket { AnnouncementsEnabled = next }); + _state.SetStatus($"Announcement notifications {(next ? "enabled" : "disabled")}."); + } + else if (key.Key == ConsoleKey.D3 || key.Key == ConsoleKey.NumPad3) + { + bool next = !prefs.DirectMessagesEnabled; + await _connection.UpdateInboxPreferencesAsync(new UpdateInboxPreferencesPacket { DirectMessagesEnabled = next }); + _state.SetStatus($"DM & Group notifications {(next ? "enabled" : "disabled")}."); + } + else if (key.Key == ConsoleKey.D4 || key.Key == ConsoleKey.NumPad4) + { + bool next = !prefs.FollowedChannelsEnabled; + await _connection.UpdateInboxPreferencesAsync(new UpdateInboxPreferencesPacket { FollowedChannelsEnabled = next }); + _state.SetStatus($"Followed channel notifications {(next ? "enabled" : "disabled")}."); + } + } +} diff --git a/src/GsDChat.Client/State/ClientState.cs b/src/GsDChat.Client/State/ClientState.cs index 5812e70..8e260fc 100644 --- a/src/GsDChat.Client/State/ClientState.cs +++ b/src/GsDChat.Client/State/ClientState.cs @@ -45,6 +45,9 @@ public class ClientState public HashSet LoadingHistoryChannels { get; } = new(StringComparer.OrdinalIgnoreCase); public List Users { get; } = new(); public List Files { get; } = new(); + public List InboxItems { get; } = new(); + public int UnreadInboxCount { get; set; } = 0; + public InboxPreferences InboxPreferences { get; set; } = new(); public List SystemNotices { get; } = new(); public int ChatScrollOffset { get; set; } = 0; @@ -440,4 +443,57 @@ public class ClientState NeedsRedraw = true; } } + + public void SetInboxSync(List items, int unreadCount, InboxPreferences? preferences = null) + { + lock (_lock) + { + InboxItems.Clear(); + InboxItems.AddRange(items); + UnreadInboxCount = unreadCount; + if (preferences != null) + { + InboxPreferences = preferences; + } + NeedsRedraw = true; + } + } + + public void AddOrUpdateInboxItem(InboxItem item, int unreadCount) + { + lock (_lock) + { + int idx = InboxItems.FindIndex(x => string.Equals(x.Id, item.Id, StringComparison.OrdinalIgnoreCase)); + if (idx >= 0) + { + InboxItems[idx] = item; + } + else + { + InboxItems.Insert(0, item); + } + UnreadInboxCount = unreadCount; + NeedsRedraw = true; + } + } + + public List GetInboxItems() + { + lock (_lock) + { + return new List(InboxItems); + } + } + + public bool IsConversationFollowed(Channel ch) + { + lock (_lock) + { + if (ch.Type == ChannelTypes.Channel) + { + return InboxPreferences.FollowedChannelIds.Contains(ch.Id, StringComparer.OrdinalIgnoreCase); + } + return !InboxPreferences.MutedChannelIds.Contains(ch.Id, StringComparer.OrdinalIgnoreCase); + } + } } diff --git a/src/GsDChat.Core/Models/InboxModels.cs b/src/GsDChat.Core/Models/InboxModels.cs new file mode 100644 index 0000000..29a0f1e --- /dev/null +++ b/src/GsDChat.Core/Models/InboxModels.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; + +namespace GsDChat.Core.Models; + +public static class InboxCategories +{ + public const string Mention = "Mention"; + public const string Announcement = "Announcement"; + public const string DirectMessage = "DirectMessage"; + public const string GroupMessage = "GroupMessage"; + public const string FollowedChannel = "FollowedChannel"; + public const string GroupInvite = "GroupInvite"; +} + +public static class ConversationFollowModes +{ + public const string Default = "Default"; + public const string Followed = "Followed"; + public const string Muted = "Muted"; +} + +public class InboxItem +{ + public string Id { get; set; } = Guid.NewGuid().ToString("N"); + public string UserId { get; set; } = string.Empty; + public string ChannelId { get; set; } = string.Empty; + public string ChannelName { get; set; } = string.Empty; + public string ChannelType { get; set; } = ChannelTypes.Channel; + public string? MessageId { get; set; } + public string SenderId { get; set; } = string.Empty; + public string SenderUsername { get; set; } = string.Empty; + public string Category { get; set; } = InboxCategories.Mention; + public string ContentPreview { get; set; } = string.Empty; + public bool IsEncrypted { get; set; } = false; + public string? SenderPublicKey { get; set; } + public string? RecipientPublicKey { get; set; } + public bool IsRead { get; set; } = false; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; +} + +public class InboxPreferences +{ + public string UserId { get; set; } = string.Empty; + public bool MentionsEnabled { get; set; } = true; + public bool AnnouncementsEnabled { get; set; } = true; + public bool DirectMessagesEnabled { get; set; } = true; + public bool FollowedChannelsEnabled { get; set; } = true; + public bool PushNotificationsEnabled { get; set; } = true; + public List FollowedChannelIds { get; set; } = new(); + public List MutedChannelIds { get; set; } = new(); +} + +public class PushSubscriptionRecord +{ + public string Id { get; set; } = Guid.NewGuid().ToString("N"); + public string UserId { get; set; } = string.Empty; + public string Endpoint { get; set; } = string.Empty; + public string P256dh { get; set; } = string.Empty; + public string Auth { get; set; } = string.Empty; + public string UserAgent { get; set; } = string.Empty; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; +} diff --git a/src/GsDChat.Core/Protocol/HttpModels.cs b/src/GsDChat.Core/Protocol/HttpModels.cs index 8f256d5..3157aa6 100644 --- a/src/GsDChat.Core/Protocol/HttpModels.cs +++ b/src/GsDChat.Core/Protocol/HttpModels.cs @@ -45,6 +45,20 @@ public class ServerInfoResponse public bool AllowMemberChannelCreation { get; set; } = true; public bool AllowDmE2ee { get; set; } = true; public int MaxGroupChatUsers { get; set; } = 10; + public string? VapidPublicKey { get; set; } +} + +public class PushSubscribeRequest +{ + public string Endpoint { get; set; } = string.Empty; + public string P256dh { get; set; } = string.Empty; + public string Auth { get; set; } = string.Empty; + public string? UserAgent { get; set; } +} + +public class PushUnsubscribeRequest +{ + public string Endpoint { get; set; } = string.Empty; } public class UploadFileResponse diff --git a/src/GsDChat.Core/Protocol/NetworkMessages.cs b/src/GsDChat.Core/Protocol/NetworkMessages.cs index e5b7768..9c9a961 100644 --- a/src/GsDChat.Core/Protocol/NetworkMessages.cs +++ b/src/GsDChat.Core/Protocol/NetworkMessages.cs @@ -30,6 +30,11 @@ public static class MessageTypes public const string Error = "ERROR"; public const string ExecuteCommand = "EXECUTE_COMMAND"; public const string CommandResult = "COMMAND_RESULT"; + public const string InboxSync = "INBOX_SYNC"; + public const string InboxNewItem = "INBOX_NEW_ITEM"; + public const string InboxAction = "INBOX_ACTION"; + public const string UpdateInboxPreferences = "UPDATE_INBOX_PREFERENCES"; + public const string ToggleFollowChannel = "TOGGLE_FOLLOW_CHANNEL"; public const string Ping = "PING"; public const string Pong = "PONG"; } @@ -232,3 +237,38 @@ public class CommandResultPacket public string Output { get; set; } = string.Empty; public string ChannelId { get; set; } = string.Empty; } + +public class InboxSyncPacket +{ + public List Items { get; set; } = new(); + public int UnreadCount { get; set; } + public InboxPreferences Preferences { get; set; } = new(); +} + +public class InboxNewItemPacket +{ + public InboxItem Item { get; set; } = new(); + public int UnreadCount { get; set; } +} + +public class InboxActionPacket +{ + public string Action { get; set; } = string.Empty; // "mark_read", "mark_all_read", "dismiss", "clear_read", "clear_all" + public string? ItemId { get; set; } + public string? ChannelId { get; set; } +} + +public class UpdateInboxPreferencesPacket +{ + public bool? MentionsEnabled { get; set; } + public bool? AnnouncementsEnabled { get; set; } + public bool? DirectMessagesEnabled { get; set; } + public bool? FollowedChannelsEnabled { get; set; } + public bool? PushNotificationsEnabled { get; set; } +} + +public class ToggleFollowChannelPacket +{ + public string ChannelId { get; set; } = string.Empty; + public bool? Follow { get; set; } +} diff --git a/src/GsDChat.Core/Protocol/UiProtocol.cs b/src/GsDChat.Core/Protocol/UiProtocol.cs index 9400499..5fa111d 100644 --- a/src/GsDChat.Core/Protocol/UiProtocol.cs +++ b/src/GsDChat.Core/Protocol/UiProtocol.cs @@ -109,6 +109,19 @@ public class ServerUiSync new() { Name = "FileList", Position = "Center", ShowBorder = true, BorderTitle = "Available Files" }, new() { Name = "Actions", Position = "Bottom", Height = 3, ShowBorder = true, BorderTitle = "Transfer Commands" } } + }, + new() + { + ScreenId = "F5_Inbox", + Title = "Inbox", + ShortcutKey = "F5", + Description = "Notifications, mentions, announcements, and followed conversations", + Panels = new List + { + new() { Name = "Header", Position = "Top", Height = 3, ShowBorder = true, BorderTitle = "Inbox & Notification Settings" }, + new() { Name = "InboxList", Position = "Center", ShowBorder = true, BorderTitle = "Notifications" }, + new() { Name = "Actions", Position = "Bottom", Height = 3, ShowBorder = true, BorderTitle = "Inbox Controls" } + } } } }; diff --git a/src/GsDChat.Core/Security/WebPushCrypto.cs b/src/GsDChat.Core/Security/WebPushCrypto.cs new file mode 100644 index 0000000..97d2366 --- /dev/null +++ b/src/GsDChat.Core/Security/WebPushCrypto.cs @@ -0,0 +1,323 @@ +using System; +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; + +namespace GsDChat.Core.Security; + +/// +/// Pure .NET 10 implementation of RFC 8292 (VAPID) and RFC 8291 (aes128gcm Web Push Encryption). +/// Uses standard System.Security.Cryptography primitives with zero external dependencies. +/// +public static class WebPushCrypto +{ + private const int TagSize = 16; + private const int SaltSize = 16; + private const int NonceSize = 12; + private const int CekSize = 16; + private const int UncompressedP256KeySize = 65; + private const uint DefaultRecordSize = 4096; + + public static (string PublicKeyBase64Url, string PrivateKeyBase64Url) GenerateVapidKeys() + { + using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var parameters = ecdsa.ExportParameters(includePrivateParameters: true); + + byte[] uncompressedPublic = EncodeUncompressedPublicKey(parameters.Q); + string pubUrl = Base64UrlEncode(uncompressedPublic); + string privUrl = Base64UrlEncode(parameters.D!); + + return (pubUrl, privUrl); + } + + public static string CreateVapidAuthorizationHeader( + string endpointUrl, + string subject, + string vapidPublicKeyBase64Url, + string vapidPrivateKeyBase64Url, + DateTimeOffset? expiration = null) + { + var uri = new Uri(endpointUrl); + string origin = $"{uri.Scheme}://{uri.Authority}"; + long exp = (expiration ?? DateTimeOffset.UtcNow.AddHours(12)).ToUnixTimeSeconds(); + + string headerJson = "{\"typ\":\"JWT\",\"alg\":\"ES256\"}"; + string payloadJson = JsonSerializer.Serialize(new + { + aud = origin, + exp = exp, + sub = string.IsNullOrWhiteSpace(subject) ? "mailto:admin@gsdchat.local" : subject + }); + + string unsignedToken = $"{Base64UrlEncode(Encoding.UTF8.GetBytes(headerJson))}.{Base64UrlEncode(Encoding.UTF8.GetBytes(payloadJson))}"; + + byte[] pubBytes = Base64UrlDecode(vapidPublicKeyBase64Url); + byte[] privBytes = Base64UrlDecode(vapidPrivateKeyBase64Url); + + var ecParams = new ECParameters + { + Curve = ECCurve.NamedCurves.nistP256, + Q = DecodeUncompressedPublicKey(pubBytes), + D = privBytes + }; + + using var ecdsa = ECDsa.Create(ecParams); + byte[] sig = ecdsa.SignData( + Encoding.ASCII.GetBytes(unsignedToken), + HashAlgorithmName.SHA256, + DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + + string jwt = $"{unsignedToken}.{Base64UrlEncode(sig)}"; + return $"vapid t={jwt}, k={vapidPublicKeyBase64Url}"; + } + + public static bool VerifyVapidJwt(string jwt, string vapidPublicKeyBase64Url) + { + try + { + string[] parts = jwt.Split('.'); + if (parts.Length != 3) return false; + + string unsignedToken = $"{parts[0]}.{parts[1]}"; + byte[] sig = Base64UrlDecode(parts[2]); + byte[] pubBytes = Base64UrlDecode(vapidPublicKeyBase64Url); + + var ecParams = new ECParameters + { + Curve = ECCurve.NamedCurves.nistP256, + Q = DecodeUncompressedPublicKey(pubBytes) + }; + + using var ecdsa = ECDsa.Create(ecParams); + return ecdsa.VerifyData( + Encoding.ASCII.GetBytes(unsignedToken), + sig, + HashAlgorithmName.SHA256, + DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + } + catch + { + return false; + } + } + + /// + /// Encrypts a Web Push payload using RFC 8291 (aes128gcm content encoding). + /// + public static byte[] EncryptPayload(byte[] plaintext, string clientP256dhBase64Url, string clientAuthBase64Url) + { + byte[] uaPublicBytes = Base64UrlDecode(clientP256dhBase64Url); + byte[] authSecret = Base64UrlDecode(clientAuthBase64Url); + + if (uaPublicBytes.Length != UncompressedP256KeySize || uaPublicBytes[0] != 0x04) + { + throw new ArgumentException("Client p256dh key must be a 65-byte uncompressed P-256 point.", nameof(clientP256dhBase64Url)); + } + + if (authSecret.Length < 16) + { + throw new ArgumentException("Client auth secret must be at least 16 bytes.", nameof(clientAuthBase64Url)); + } + + byte[] salt = RandomNumberGenerator.GetBytes(SaltSize); + + using var asEcdh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256); + var asParams = asEcdh.ExportParameters(includePrivateParameters: false); + byte[] asPublicBytes = EncodeUncompressedPublicKey(asParams.Q); + + var uaParams = new ECParameters + { + Curve = ECCurve.NamedCurves.nistP256, + Q = DecodeUncompressedPublicKey(uaPublicBytes) + }; + using var uaEcdh = ECDiffieHellman.Create(uaParams); + + byte[] sharedSecret = asEcdh.DeriveRawSecretAgreement(uaEcdh.PublicKey); + + var (cek, nonce) = DeriveCekAndNonce(sharedSecret, authSecret, salt, uaPublicBytes, asPublicBytes); + + // RFC 8188 / RFC 8291 final record delimiter (0x02) + byte[] paddedPlaintext = new byte[plaintext.Length + 1]; + Buffer.BlockCopy(plaintext, 0, paddedPlaintext, 0, plaintext.Length); + paddedPlaintext[plaintext.Length] = 0x02; + + byte[] ciphertext = new byte[paddedPlaintext.Length]; + byte[] tag = new byte[TagSize]; + + using (var aesGcm = new AesGcm(cek, TagSize)) + { + aesGcm.Encrypt(nonce, paddedPlaintext, ciphertext, tag); + } + + // RFC 8188 aes128gcm header: salt (16) || rs (4) || idlen (1) || keyid (65) = 86 bytes + int headerLen = SaltSize + 4 + 1 + asPublicBytes.Length; + byte[] output = new byte[headerLen + ciphertext.Length + TagSize]; + + int offset = 0; + Buffer.BlockCopy(salt, 0, output, offset, SaltSize); + offset += SaltSize; + + BinaryPrimitives.WriteUInt32BigEndian(output.AsSpan(offset, 4), DefaultRecordSize); + offset += 4; + + output[offset++] = (byte)asPublicBytes.Length; + + Buffer.BlockCopy(asPublicBytes, 0, output, offset, asPublicBytes.Length); + offset += asPublicBytes.Length; + + Buffer.BlockCopy(ciphertext, 0, output, offset, ciphertext.Length); + offset += ciphertext.Length; + + Buffer.BlockCopy(tag, 0, output, offset, TagSize); + + return output; + } + + /// + /// Decrypts an RFC 8291 aes128gcm Web Push payload (used for verification and testing). + /// + public static byte[] DecryptPayload( + byte[] encryptedBody, + string clientPublicKeyBase64Url, + string clientPrivateKeyBase64Url, + string clientAuthBase64Url) + { + if (encryptedBody.Length < 86 + TagSize + 1) + { + throw new ArgumentException("Encrypted body is too short to be valid aes128gcm.", nameof(encryptedBody)); + } + + byte[] salt = encryptedBody.AsSpan(0, SaltSize).ToArray(); + int idLen = encryptedBody[20]; + if (idLen != UncompressedP256KeySize || encryptedBody.Length < 21 + idLen + TagSize + 1) + { + throw new ArgumentException("Invalid keyid length in aes128gcm header.", nameof(encryptedBody)); + } + + byte[] asPublicBytes = encryptedBody.AsSpan(21, idLen).ToArray(); + int cipherOffset = 21 + idLen; + int cipherLen = encryptedBody.Length - cipherOffset - TagSize; + + byte[] ciphertext = encryptedBody.AsSpan(cipherOffset, cipherLen).ToArray(); + byte[] tag = encryptedBody.AsSpan(cipherOffset + cipherLen, TagSize).ToArray(); + + byte[] uaPublicBytes = Base64UrlDecode(clientPublicKeyBase64Url); + byte[] uaPrivBytes = Base64UrlDecode(clientPrivateKeyBase64Url); + byte[] authSecret = Base64UrlDecode(clientAuthBase64Url); + + var uaParams = new ECParameters + { + Curve = ECCurve.NamedCurves.nistP256, + Q = DecodeUncompressedPublicKey(uaPublicBytes), + D = uaPrivBytes + }; + using var uaEcdh = ECDiffieHellman.Create(uaParams); + + var asParams = new ECParameters + { + Curve = ECCurve.NamedCurves.nistP256, + Q = DecodeUncompressedPublicKey(asPublicBytes) + }; + using var asEcdh = ECDiffieHellman.Create(asParams); + + byte[] sharedSecret = uaEcdh.DeriveRawSecretAgreement(asEcdh.PublicKey); + var (cek, nonce) = DeriveCekAndNonce(sharedSecret, authSecret, salt, uaPublicBytes, asPublicBytes); + + byte[] paddedPlaintext = new byte[cipherLen]; + using (var aesGcm = new AesGcm(cek, TagSize)) + { + aesGcm.Decrypt(nonce, ciphertext, tag, paddedPlaintext); + } + + // Strip trailing 0x00 padding and 0x02 delimiter + int endIdx = paddedPlaintext.Length - 1; + while (endIdx >= 0 && paddedPlaintext[endIdx] == 0x00) + { + endIdx--; + } + if (endIdx < 0 || paddedPlaintext[endIdx] != 0x02) + { + throw new CryptographicException("Missing 0x02 record delimiter in aes128gcm plaintext."); + } + + return paddedPlaintext.AsSpan(0, endIdx).ToArray(); + } + + private static (byte[] Cek, byte[] Nonce) DeriveCekAndNonce( + byte[] sharedSecret, + byte[] authSecret, + byte[] salt, + byte[] uaPublicBytes, + byte[] asPublicBytes) + { + // PRK_key = HKDF-Extract(salt=auth_secret, IKM=ecdh_secret) + byte[] prkKey = HKDF.Extract(HashAlgorithmName.SHA256, sharedSecret, authSecret); + + // key_info = "WebPush: info\0" || ua_public || as_public + byte[] prefix = Encoding.ASCII.GetBytes("WebPush: info\0"); + byte[] keyInfo = new byte[prefix.Length + uaPublicBytes.Length + asPublicBytes.Length]; + Buffer.BlockCopy(prefix, 0, keyInfo, 0, prefix.Length); + Buffer.BlockCopy(uaPublicBytes, 0, keyInfo, prefix.Length, uaPublicBytes.Length); + Buffer.BlockCopy(asPublicBytes, 0, keyInfo, prefix.Length + uaPublicBytes.Length, asPublicBytes.Length); + + byte[] ikm = HKDF.Expand(HashAlgorithmName.SHA256, prkKey, 32, keyInfo); + + // PRK = HKDF-Extract(salt=salt, IKM=IKM) + byte[] prk = HKDF.Extract(HashAlgorithmName.SHA256, ikm, salt); + + byte[] cekInfo = Encoding.ASCII.GetBytes("Content-Encoding: aes128gcm\0"); + byte[] nonceInfo = Encoding.ASCII.GetBytes("Content-Encoding: nonce\0"); + + byte[] cek = HKDF.Expand(HashAlgorithmName.SHA256, prk, CekSize, cekInfo); + byte[] nonce = HKDF.Expand(HashAlgorithmName.SHA256, prk, NonceSize, nonceInfo); + + return (cek, nonce); + } + + public static byte[] EncodeUncompressedPublicKey(ECPoint q) + { + byte[] result = new byte[UncompressedP256KeySize]; + result[0] = 0x04; + Buffer.BlockCopy(q.X!, 0, result, 1, 32); + Buffer.BlockCopy(q.Y!, 0, result, 33, 32); + return result; + } + + public static ECPoint DecodeUncompressedPublicKey(byte[] bytes) + { + if (bytes.Length != UncompressedP256KeySize || bytes[0] != 0x04) + { + throw new ArgumentException("Invalid uncompressed P-256 public key bytes."); + } + + return new ECPoint + { + X = bytes.AsSpan(1, 32).ToArray(), + Y = bytes.AsSpan(33, 32).ToArray() + }; + } + + public static string Base64UrlEncode(byte[] bytes) + { + return Convert.ToBase64String(bytes) + .TrimEnd('=') + .Replace('+', '-') + .Replace('/', '_'); + } + + public static byte[] Base64UrlDecode(string input) + { + string base64 = input.Trim() + .Replace('-', '+') + .Replace('_', '/'); + + switch (base64.Length % 4) + { + case 2: base64 += "=="; break; + case 3: base64 += "="; break; + } + + return Convert.FromBase64String(base64); + } +} diff --git a/src/GsDChat.Server/Configuration/ServerOptions.cs b/src/GsDChat.Server/Configuration/ServerOptions.cs index 0a81546..0ed18a8 100644 --- a/src/GsDChat.Server/Configuration/ServerOptions.cs +++ b/src/GsDChat.Server/Configuration/ServerOptions.cs @@ -17,6 +17,11 @@ public class ServerOptions public bool AllowDmE2ee { get; set; } = true; public int MaxGroupChatUsers { get; set; } = 10; + // Web Push (VAPID RFC 8292) + public string? VapidPublicKey { get; set; } + public string? VapidPrivateKey { get; set; } + public string VapidSubject { get; set; } = "mailto:admin@gsdchat.local"; + // Security Settings public int RateLimitRequestsPerMinute { get; set; } = 60; public int MaxConnectionsPerIp { get; set; } = 10; diff --git a/src/GsDChat.Server/Configuration/ServerSettingsManager.cs b/src/GsDChat.Server/Configuration/ServerSettingsManager.cs index c35d7ca..3446a5a 100644 --- a/src/GsDChat.Server/Configuration/ServerSettingsManager.cs +++ b/src/GsDChat.Server/Configuration/ServerSettingsManager.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Text.Json; +using GsDChat.Core.Security; namespace GsDChat.Server.Configuration; @@ -87,6 +88,13 @@ public class ServerSettingsManager options.MaxGroupChatUsers = 2; } + if (string.IsNullOrWhiteSpace(options.VapidPublicKey) || string.IsNullOrWhiteSpace(options.VapidPrivateKey)) + { + var (pub, priv) = WebPushCrypto.GenerateVapidKeys(); + options.VapidPublicKey = pub; + options.VapidPrivateKey = priv; + } + Save(options); return options; } diff --git a/src/GsDChat.Server/Data/ChatDatabase.cs b/src/GsDChat.Server/Data/ChatDatabase.cs index 431983a..0a61a3d 100644 --- a/src/GsDChat.Server/Data/ChatDatabase.cs +++ b/src/GsDChat.Server/Data/ChatDatabase.cs @@ -155,6 +155,72 @@ public class ChatDatabase : IDisposable ); """); + // Create inbox, preferences, channel follows, and push subscriptions tables + await TryExecuteTableMigrationAsync(conn, """ + CREATE TABLE IF NOT EXISTS inbox_items ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + channel_id TEXT NOT NULL, + channel_name TEXT NOT NULL, + channel_type TEXT NOT NULL DEFAULT 'Channel', + message_id TEXT, + sender_id TEXT NOT NULL, + sender_username TEXT NOT NULL, + category TEXT NOT NULL, + content_preview TEXT NOT NULL, + is_encrypted INTEGER NOT NULL DEFAULT 0, + sender_public_key TEXT, + recipient_public_key TEXT, + is_read INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE, + FOREIGN KEY (channel_id) REFERENCES channels (id) ON DELETE CASCADE + ); + + CREATE INDEX IF NOT EXISTS idx_inbox_user_created + ON inbox_items(user_id, created_at DESC); + + CREATE INDEX IF NOT EXISTS idx_inbox_user_unread + ON inbox_items(user_id, is_read); + + CREATE TABLE IF NOT EXISTS inbox_preferences ( + user_id TEXT PRIMARY KEY, + mentions_enabled INTEGER NOT NULL DEFAULT 1, + announcements_enabled INTEGER NOT NULL DEFAULT 1, + direct_messages_enabled INTEGER NOT NULL DEFAULT 1, + followed_channels_enabled INTEGER NOT NULL DEFAULT 1, + push_notifications_enabled INTEGER NOT NULL DEFAULT 1, + FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE + ); + + CREATE TABLE IF NOT EXISTS channel_follows ( + user_id TEXT NOT NULL, + channel_id TEXT NOT NULL, + mode TEXT NOT NULL DEFAULT 'Followed', + updated_at TEXT NOT NULL, + PRIMARY KEY (user_id, channel_id), + FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE, + FOREIGN KEY (channel_id) REFERENCES channels (id) ON DELETE CASCADE + ); + + CREATE INDEX IF NOT EXISTS idx_channel_follows_user + ON channel_follows(user_id); + + CREATE TABLE IF NOT EXISTS push_subscriptions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + endpoint TEXT NOT NULL UNIQUE, + p256dh TEXT NOT NULL, + auth TEXT NOT NULL, + user_agent TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, + FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE + ); + + CREATE INDEX IF NOT EXISTS idx_push_subscriptions_user + ON push_subscriptions(user_id); + """); + // Seed default channels if none exist var channelsCountCmd = conn.CreateCommand(); channelsCountCmd.CommandText = "SELECT COUNT(*) FROM channels WHERE type = 'Channel';"; @@ -642,6 +708,8 @@ public class ChatDatabase : IDisposable using var cleanupCmd = conn.CreateCommand(); cleanupCmd.CommandText = """ + DELETE FROM inbox_items WHERE channel_id = @id; + DELETE FROM channel_follows WHERE channel_id = @id; DELETE FROM files WHERE channel_id = @id; DELETE FROM messages WHERE channel_id = @id; DELETE FROM channel_members WHERE channel_id = @id; @@ -1265,6 +1333,365 @@ public class ChatDatabase : IDisposable #endregion + #region Inbox, Preferences & Push Subscription Operations + + public async Task CreateInboxItemAsync(InboxItem item) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = """ + INSERT INTO inbox_items ( + id, user_id, channel_id, channel_name, channel_type, message_id, + sender_id, sender_username, category, content_preview, + is_encrypted, sender_public_key, recipient_public_key, is_read, created_at + ) + VALUES ( + @id, @user_id, @channel_id, @channel_name, @channel_type, @message_id, + @sender_id, @sender_username, @category, @content_preview, + @is_encrypted, @sender_public_key, @recipient_public_key, @is_read, @created_at + ); + """; + cmd.Parameters.AddWithValue("@id", item.Id); + cmd.Parameters.AddWithValue("@user_id", item.UserId); + cmd.Parameters.AddWithValue("@channel_id", item.ChannelId); + cmd.Parameters.AddWithValue("@channel_name", item.ChannelName ?? string.Empty); + cmd.Parameters.AddWithValue("@channel_type", string.IsNullOrWhiteSpace(item.ChannelType) ? ChannelTypes.Channel : item.ChannelType); + cmd.Parameters.AddWithValue("@message_id", (object?)item.MessageId ?? DBNull.Value); + cmd.Parameters.AddWithValue("@sender_id", item.SenderId ?? string.Empty); + cmd.Parameters.AddWithValue("@sender_username", item.SenderUsername ?? string.Empty); + cmd.Parameters.AddWithValue("@category", item.Category ?? InboxCategories.Mention); + cmd.Parameters.AddWithValue("@content_preview", item.ContentPreview ?? string.Empty); + cmd.Parameters.AddWithValue("@is_encrypted", item.IsEncrypted ? 1 : 0); + cmd.Parameters.AddWithValue("@sender_public_key", (object?)item.SenderPublicKey ?? DBNull.Value); + cmd.Parameters.AddWithValue("@recipient_public_key", (object?)item.RecipientPublicKey ?? DBNull.Value); + cmd.Parameters.AddWithValue("@is_read", item.IsRead ? 1 : 0); + cmd.Parameters.AddWithValue("@created_at", item.CreatedAt.ToString("O")); + + await cmd.ExecuteNonQueryAsync(); + } + + public async Task> GetInboxItemsForUserAsync(string userId, int limit = 100) + { + var items = new List(); + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = """ + SELECT id, user_id, channel_id, channel_name, channel_type, message_id, + sender_id, sender_username, category, content_preview, + is_encrypted, sender_public_key, recipient_public_key, is_read, created_at + FROM inbox_items + WHERE user_id = @uid + ORDER BY created_at DESC + LIMIT @limit; + """; + cmd.Parameters.AddWithValue("@uid", userId); + cmd.Parameters.AddWithValue("@limit", Math.Clamp(limit, 1, 500)); + + using var reader = await cmd.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + items.Add(new InboxItem + { + Id = reader.GetString(0), + UserId = reader.GetString(1), + ChannelId = reader.GetString(2), + ChannelName = reader.GetString(3), + ChannelType = reader.GetString(4), + MessageId = reader.IsDBNull(5) ? null : reader.GetString(5), + SenderId = reader.GetString(6), + SenderUsername = reader.GetString(7), + Category = reader.GetString(8), + ContentPreview = reader.GetString(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), + IsRead = !reader.IsDBNull(13) && reader.GetInt32(13) == 1, + CreatedAt = DateTime.Parse(reader.GetString(14)) + }); + } + return items; + } + + public async Task GetUnreadInboxCountAsync(string userId) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = "SELECT COUNT(*) FROM inbox_items WHERE user_id = @uid AND is_read = 0;"; + cmd.Parameters.AddWithValue("@uid", userId); + var res = await cmd.ExecuteScalarAsync(); + return Convert.ToInt32(res); + } + + public async Task MarkInboxItemReadAsync(string userId, string itemId) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = "UPDATE inbox_items SET is_read = 1 WHERE user_id = @uid AND id = @id;"; + cmd.Parameters.AddWithValue("@uid", userId); + cmd.Parameters.AddWithValue("@id", itemId); + return (await cmd.ExecuteNonQueryAsync()) > 0; + } + + public async Task MarkChannelInboxItemsReadAsync(string userId, string channelId) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = "UPDATE inbox_items SET is_read = 1 WHERE user_id = @uid AND channel_id = @cid AND is_read = 0;"; + cmd.Parameters.AddWithValue("@uid", userId); + cmd.Parameters.AddWithValue("@cid", channelId); + return await cmd.ExecuteNonQueryAsync(); + } + + public async Task MarkAllInboxItemsReadAsync(string userId) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = "UPDATE inbox_items SET is_read = 1 WHERE user_id = @uid AND is_read = 0;"; + cmd.Parameters.AddWithValue("@uid", userId); + return await cmd.ExecuteNonQueryAsync(); + } + + public async Task DeleteInboxItemAsync(string userId, string itemId) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = "DELETE FROM inbox_items WHERE user_id = @uid AND id = @id;"; + cmd.Parameters.AddWithValue("@uid", userId); + cmd.Parameters.AddWithValue("@id", itemId); + return (await cmd.ExecuteNonQueryAsync()) > 0; + } + + public async Task ClearInboxItemsAsync(string userId, bool onlyRead) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + if (onlyRead) + { + cmd.CommandText = "DELETE FROM inbox_items WHERE user_id = @uid AND is_read = 1;"; + } + else + { + cmd.CommandText = "DELETE FROM inbox_items WHERE user_id = @uid;"; + } + cmd.Parameters.AddWithValue("@uid", userId); + return await cmd.ExecuteNonQueryAsync(); + } + + public async Task GetInboxPreferencesAsync(string userId) + { + var prefs = new InboxPreferences + { + UserId = userId, + MentionsEnabled = true, + AnnouncementsEnabled = true, + DirectMessagesEnabled = true, + FollowedChannelsEnabled = true, + PushNotificationsEnabled = true + }; + + using var conn = CreateConnection(); + using (var cmd = conn.CreateCommand()) + { + cmd.CommandText = """ + SELECT mentions_enabled, announcements_enabled, direct_messages_enabled, followed_channels_enabled, push_notifications_enabled + FROM inbox_preferences + WHERE user_id = @uid + LIMIT 1; + """; + cmd.Parameters.AddWithValue("@uid", userId); + + using var reader = await cmd.ExecuteReaderAsync(); + if (await reader.ReadAsync()) + { + prefs.MentionsEnabled = reader.GetInt32(0) == 1; + prefs.AnnouncementsEnabled = reader.GetInt32(1) == 1; + prefs.DirectMessagesEnabled = reader.GetInt32(2) == 1; + prefs.FollowedChannelsEnabled = reader.GetInt32(3) == 1; + prefs.PushNotificationsEnabled = reader.GetInt32(4) == 1; + } + } + + using (var fCmd = conn.CreateCommand()) + { + fCmd.CommandText = "SELECT channel_id, mode FROM channel_follows WHERE user_id = @uid;"; + fCmd.Parameters.AddWithValue("@uid", userId); + using var fReader = await fCmd.ExecuteReaderAsync(); + while (await fReader.ReadAsync()) + { + string cid = fReader.GetString(0); + string mode = fReader.GetString(1); + if (string.Equals(mode, ConversationFollowModes.Followed, StringComparison.OrdinalIgnoreCase)) + { + prefs.FollowedChannelIds.Add(cid); + } + else if (string.Equals(mode, ConversationFollowModes.Muted, StringComparison.OrdinalIgnoreCase)) + { + prefs.MutedChannelIds.Add(cid); + } + } + } + + return prefs; + } + + public async Task SaveInboxPreferencesAsync(InboxPreferences prefs) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = """ + INSERT INTO inbox_preferences ( + user_id, mentions_enabled, announcements_enabled, direct_messages_enabled, followed_channels_enabled, push_notifications_enabled + ) + VALUES ( + @uid, @mentions, @announcements, @dms, @followed, @push + ) + ON CONFLICT(user_id) DO UPDATE SET + mentions_enabled = @mentions, + announcements_enabled = @announcements, + direct_messages_enabled = @dms, + followed_channels_enabled = @followed, + push_notifications_enabled = @push; + """; + cmd.Parameters.AddWithValue("@uid", prefs.UserId); + cmd.Parameters.AddWithValue("@mentions", prefs.MentionsEnabled ? 1 : 0); + cmd.Parameters.AddWithValue("@announcements", prefs.AnnouncementsEnabled ? 1 : 0); + cmd.Parameters.AddWithValue("@dms", prefs.DirectMessagesEnabled ? 1 : 0); + cmd.Parameters.AddWithValue("@followed", prefs.FollowedChannelsEnabled ? 1 : 0); + cmd.Parameters.AddWithValue("@push", prefs.PushNotificationsEnabled ? 1 : 0); + + await cmd.ExecuteNonQueryAsync(); + } + + public async Task SetChannelFollowModeAsync(string userId, string channelId, string mode) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + if (string.Equals(mode, ConversationFollowModes.Default, StringComparison.OrdinalIgnoreCase)) + { + cmd.CommandText = "DELETE FROM channel_follows WHERE user_id = @uid AND channel_id = @cid;"; + cmd.Parameters.AddWithValue("@uid", userId); + cmd.Parameters.AddWithValue("@cid", channelId); + } + else + { + cmd.CommandText = """ + INSERT INTO channel_follows (user_id, channel_id, mode, updated_at) + VALUES (@uid, @cid, @mode, @now) + ON CONFLICT(user_id, channel_id) DO UPDATE SET mode = @mode, updated_at = @now; + """; + cmd.Parameters.AddWithValue("@uid", userId); + cmd.Parameters.AddWithValue("@cid", channelId); + cmd.Parameters.AddWithValue("@mode", mode); + cmd.Parameters.AddWithValue("@now", DateTime.UtcNow.ToString("O")); + } + await cmd.ExecuteNonQueryAsync(); + } + + public async Task ToggleChannelFollowAsync(string userId, Channel channel, bool? explicitFollow = null) + { + var prefs = await GetInboxPreferencesAsync(userId); + bool isPublicChannel = channel.Type == ChannelTypes.Channel; + + if (isPublicChannel) + { + bool currentlyFollowed = prefs.FollowedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase); + bool nextFollow = explicitFollow ?? !currentlyFollowed; + await SetChannelFollowModeAsync( + userId, + channel.Id, + nextFollow ? ConversationFollowModes.Followed : ConversationFollowModes.Default); + return nextFollow; + } + else + { + // DMs & Group Chats are followed by default unless Muted + bool currentlyMuted = prefs.MutedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase); + bool currentlyFollowed = !currentlyMuted; + bool nextFollow = explicitFollow ?? !currentlyFollowed; + await SetChannelFollowModeAsync( + userId, + channel.Id, + nextFollow ? ConversationFollowModes.Default : ConversationFollowModes.Muted); + return nextFollow; + } + } + + public async Task SavePushSubscriptionAsync(PushSubscriptionRecord sub) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = """ + INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth, user_agent, created_at) + VALUES (@id, @uid, @endpoint, @p256dh, @auth, @ua, @created_at) + ON CONFLICT(endpoint) DO UPDATE SET + user_id = @uid, + p256dh = @p256dh, + auth = @auth, + user_agent = @ua, + created_at = @created_at; + """; + cmd.Parameters.AddWithValue("@id", sub.Id); + cmd.Parameters.AddWithValue("@uid", sub.UserId); + cmd.Parameters.AddWithValue("@endpoint", sub.Endpoint); + cmd.Parameters.AddWithValue("@p256dh", sub.P256dh); + cmd.Parameters.AddWithValue("@auth", sub.Auth); + cmd.Parameters.AddWithValue("@ua", sub.UserAgent ?? string.Empty); + cmd.Parameters.AddWithValue("@created_at", sub.CreatedAt.ToString("O")); + + await cmd.ExecuteNonQueryAsync(); + } + + public async Task RemovePushSubscriptionAsync(string userId, string endpoint) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = "DELETE FROM push_subscriptions WHERE user_id = @uid AND endpoint = @endpoint;"; + cmd.Parameters.AddWithValue("@uid", userId); + cmd.Parameters.AddWithValue("@endpoint", endpoint); + return (await cmd.ExecuteNonQueryAsync()) > 0; + } + + public async Task RemovePushSubscriptionByEndpointAsync(string endpoint) + { + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = "DELETE FROM push_subscriptions WHERE endpoint = @endpoint;"; + cmd.Parameters.AddWithValue("@endpoint", endpoint); + return (await cmd.ExecuteNonQueryAsync()) > 0; + } + + public async Task> GetPushSubscriptionsForUserAsync(string userId) + { + var subs = new List(); + using var conn = CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = """ + SELECT id, user_id, endpoint, p256dh, auth, user_agent, created_at + FROM push_subscriptions + WHERE user_id = @uid + ORDER BY created_at DESC; + """; + cmd.Parameters.AddWithValue("@uid", userId); + + using var reader = await cmd.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + subs.Add(new PushSubscriptionRecord + { + Id = reader.GetString(0), + UserId = reader.GetString(1), + Endpoint = reader.GetString(2), + P256dh = reader.GetString(3), + Auth = reader.GetString(4), + UserAgent = reader.GetString(5), + CreatedAt = DateTime.Parse(reader.GetString(6)) + }); + } + return subs; + } + + #endregion + public void Dispose() { // SQLite in-process connections are pooled and closed as needed diff --git a/src/GsDChat.Server/Program.cs b/src/GsDChat.Server/Program.cs index 77287a7..9ca1dce 100644 --- a/src/GsDChat.Server/Program.cs +++ b/src/GsDChat.Server/Program.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using GsDChat.Core.Models; using GsDChat.Core.Protocol; using GsDChat.Server.Configuration; using GsDChat.Server.Data; @@ -112,6 +113,7 @@ builder.WebHost.ConfigureKestrel(kestrel => builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory)); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -148,6 +150,8 @@ app.Use(async (context, next) => context.Response.Headers.Append("Content-Security-Policy", "default-src 'self'; " + "script-src 'self' 'unsafe-inline'; " + + "worker-src 'self'; " + + "manifest-src 'self'; " + "style-src 'self' 'unsafe-inline'; " + "img-src 'self' data:; " + "font-src 'self'; " + @@ -213,10 +217,74 @@ app.MapGet("/api/info", (ServerOptions opt, IAuthService auth, HttpRequest req) MaxFileSizeMb = opt.MaxFileSizeMb, AllowMemberChannelCreation = opt.AllowMemberChannelCreation, AllowDmE2ee = opt.AllowDmE2ee, - MaxGroupChatUsers = opt.MaxGroupChatUsers + MaxGroupChatUsers = opt.MaxGroupChatUsers, + VapidPublicKey = opt.VapidPublicKey }); }); +// Web Push Endpoints +app.MapGet("/api/push/vapid-public-key", (ServerOptions opt) => +{ + return Results.Ok(new { publicKey = opt.VapidPublicKey ?? string.Empty }); +}); + +app.MapPost("/api/push/subscribe", async (PushSubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) => +{ + string? token = ExtractBearerToken(httpReq); + var user = await auth.ValidateSessionTokenAsync(token ?? ""); + if (user == null) + { + return Results.Unauthorized(); + } + + if (string.IsNullOrWhiteSpace(req.Endpoint) || string.IsNullOrWhiteSpace(req.P256dh) || string.IsNullOrWhiteSpace(req.Auth)) + { + return Results.BadRequest(new { success = false, error = "Invalid push subscription parameters." }); + } + + await chatDb.SavePushSubscriptionAsync(new PushSubscriptionRecord + { + UserId = user.Id, + Endpoint = req.Endpoint.Trim(), + P256dh = req.P256dh.Trim(), + Auth = req.Auth.Trim(), + UserAgent = req.UserAgent ?? httpReq.Headers.UserAgent.ToString() + }); + + return Results.Ok(new { success = true }); +}); + +app.MapPost("/api/push/unsubscribe", async (PushUnsubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) => +{ + string? token = ExtractBearerToken(httpReq); + var user = await auth.ValidateSessionTokenAsync(token ?? ""); + if (user == null) + { + return Results.Unauthorized(); + } + + if (string.IsNullOrWhiteSpace(req.Endpoint)) + { + return Results.BadRequest(new { success = false, error = "Endpoint required." }); + } + + await chatDb.RemovePushSubscriptionAsync(user.Id, req.Endpoint.Trim()); + return Results.Ok(new { success = true }); +}); + +app.MapPost("/api/push/test", async (HttpRequest httpReq, IAuthService auth, WebPushService webPush) => +{ + string? token = ExtractBearerToken(httpReq); + var user = await auth.ValidateSessionTokenAsync(token ?? ""); + if (user == null) + { + return Results.Unauthorized(); + } + + bool sent = await webPush.SendTestPushAsync(user.Id, user.Username); + return Results.Ok(new { success = sent }); +}); + app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, RateLimitService rateLimiter, CsrfProtectionService csrf, HttpContext context) => { string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown"; diff --git a/src/GsDChat.Server/Services/WebPushService.cs b/src/GsDChat.Server/Services/WebPushService.cs new file mode 100644 index 0000000..8731e2c --- /dev/null +++ b/src/GsDChat.Server/Services/WebPushService.cs @@ -0,0 +1,209 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using GsDChat.Core.Models; +using GsDChat.Core.Security; +using GsDChat.Server.Configuration; +using GsDChat.Server.Data; + +namespace GsDChat.Server.Services; + +public class WebPushNotificationPayload +{ + public string Title { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + public string ChannelId { get; set; } = string.Empty; + public string ChannelName { get; set; } = string.Empty; + public string Category { get; set; } = string.Empty; + public string ItemId { get; set; } = string.Empty; + public string SenderUsername { get; set; } = string.Empty; + public string Timestamp { get; set; } = string.Empty; +} + +public class WebPushService : IDisposable +{ + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + private readonly ChatDatabase _db; + private readonly ServerOptions _options; + private readonly ILogger _logger; + private readonly HttpClient _httpClient; + + public WebPushService( + ChatDatabase db, + ServerOptions options, + ILogger logger, + HttpMessageHandler? customHandler = null) + { + _db = db; + _options = options; + _logger = logger; + + if (string.IsNullOrWhiteSpace(_options.VapidPublicKey) || string.IsNullOrWhiteSpace(_options.VapidPrivateKey)) + { + var (pub, priv) = WebPushCrypto.GenerateVapidKeys(); + _options.VapidPublicKey = pub; + _options.VapidPrivateKey = priv; + } + + _httpClient = customHandler != null + ? new HttpClient(customHandler) { Timeout = TimeSpan.FromSeconds(10) } + : new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; + } + + public string VapidPublicKey => _options.VapidPublicKey ?? string.Empty; + + public static WebPushNotificationPayload BuildNotificationPayload(InboxItem item, string serverName) + { + string sender = string.IsNullOrWhiteSpace(item.SenderUsername) ? "System" : item.SenderUsername; + string chName = string.IsNullOrWhiteSpace(item.ChannelName) ? "chat" : item.ChannelName; + + string title = item.Category switch + { + InboxCategories.Mention => $"@{sender} mentioned you in {(item.ChannelType == ChannelTypes.Channel ? "#" + chName : chName)}", + InboxCategories.Announcement => $"📢 Announcement from @{sender}", + InboxCategories.DirectMessage => $"Direct Message from @{sender}", + InboxCategories.GroupMessage => $"@{sender} in [Group] {chName}", + InboxCategories.GroupInvite => $"Group Chat Invitation: {chName}", + _ => $"@{sender} in #{chName}" + }; + + bool isEncrypted = item.IsEncrypted || E2eeCrypto.IsEncryptedPayload(item.ContentPreview); + string body; + if (isEncrypted) + { + body = $"🔒 New encrypted message from @{sender}"; + } + else + { + string raw = item.ContentPreview ?? string.Empty; + body = raw.Length > 180 ? raw[..177] + "..." : raw; + } + + return new WebPushNotificationPayload + { + Title = title, + Body = body, + ChannelId = item.ChannelId, + ChannelName = chName, + Category = item.Category, + ItemId = item.Id, + SenderUsername = sender, + Timestamp = item.CreatedAt.ToString("O") + }; + } + + public async Task SendPushForInboxItemAsync(InboxItem item, InboxPreferences? prefs = null, CancellationToken ct = default) + { + try + { + var effectivePrefs = prefs ?? await _db.GetInboxPreferencesAsync(item.UserId); + if (!effectivePrefs.PushNotificationsEnabled) + { + return; + } + + var subscriptions = await _db.GetPushSubscriptionsForUserAsync(item.UserId); + if (subscriptions.Count == 0) + { + return; + } + + var payload = BuildNotificationPayload(item, _options.ServerName); + byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(payload, s_jsonOptions); + + var sendTasks = new List(subscriptions.Count); + foreach (var sub in subscriptions) + { + sendTasks.Add(DeliverToSubscriptionAsync(sub, jsonBytes, ct)); + } + + await Task.WhenAll(sendTasks); + } + catch (Exception ex) + { + SafeLogger.LogWarning(_logger, "Error sending Web Push notifications for user {UserId}: {Msg}", item.UserId, ex.Message); + } + } + + public async Task SendTestPushAsync(string userId, string username, CancellationToken ct = default) + { + var subscriptions = await _db.GetPushSubscriptionsForUserAsync(userId); + if (subscriptions.Count == 0) + { + return false; + } + + var payload = new WebPushNotificationPayload + { + Title = $"{_options.ServerName} Push Active", + Body = $"Push notifications are configured for @{username}!", + ChannelId = string.Empty, + ChannelName = "inbox", + Category = InboxCategories.Announcement, + ItemId = Guid.NewGuid().ToString("N"), + SenderUsername = "System", + Timestamp = DateTime.UtcNow.ToString("O") + }; + + byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(payload, s_jsonOptions); + foreach (var sub in subscriptions) + { + await DeliverToSubscriptionAsync(sub, jsonBytes, ct); + } + return true; + } + + private async Task DeliverToSubscriptionAsync(PushSubscriptionRecord sub, byte[] plaintextBytes, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(_options.VapidPublicKey) || string.IsNullOrWhiteSpace(_options.VapidPrivateKey)) + { + return; + } + + try + { + byte[] encrypted = WebPushCrypto.EncryptPayload(plaintextBytes, sub.P256dh, sub.Auth); + string vapidHeader = WebPushCrypto.CreateVapidAuthorizationHeader( + sub.Endpoint, + _options.VapidSubject, + _options.VapidPublicKey, + _options.VapidPrivateKey); + + using var request = new HttpRequestMessage(HttpMethod.Post, sub.Endpoint); + request.Headers.TryAddWithoutValidation("Authorization", vapidHeader); + request.Headers.TryAddWithoutValidation("TTL", "86400"); + request.Headers.TryAddWithoutValidation("Urgency", "high"); + + var content = new ByteArrayContent(encrypted); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + content.Headers.ContentEncoding.Add("aes128gcm"); + request.Content = content; + + using var response = await _httpClient.SendAsync(request, ct); + if (response.StatusCode == HttpStatusCode.Gone || response.StatusCode == HttpStatusCode.NotFound) + { + await _db.RemovePushSubscriptionByEndpointAsync(sub.Endpoint); + } + } + catch (Exception ex) + { + SafeLogger.LogDebug(_logger, "Web Push delivery failed for endpoint: {Msg}", ex.Message); + } + } + + public void Dispose() + { + _httpClient.Dispose(); + } +} diff --git a/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs b/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs index 16a87c5..e4b770b 100644 --- a/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs +++ b/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Net.WebSockets; using System.Text; using System.Text.Json; +using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -23,17 +24,23 @@ public class ChatWebSocketManager private readonly ChatDatabase _db; private readonly ServerOptions _options; private readonly ILogger _logger; + private readonly WebPushService? _webPush; // Extensibility hooks for mod system public Func>? MessagePipelineInterceptor { get; set; } public Func>? CommandInterceptor { get; set; } public Func? UiSyncProvider { get; set; } - public ChatWebSocketManager(ChatDatabase db, ServerOptions options, ILogger logger) + public ChatWebSocketManager( + ChatDatabase db, + ServerOptions options, + ILogger logger, + WebPushService? webPush = null) { _db = db; _options = options; _logger = logger; + _webPush = webPush; } public int ConnectedCount => _clients.Count; @@ -92,6 +99,9 @@ public class ChatWebSocketManager // Send Files List (filtered for user access) await SendFileListToClientAsync(client, cancellationToken); + // Send Initial Inbox & Preferences Sync + await SendInboxSyncToClientAsync(client, cancellationToken); + // Send Initial User List var initialUsers = await _db.GetAllUsersAsync(); var onlineIds = new HashSet(_clients.Values.Select(c => c.User.Id), StringComparer.OrdinalIgnoreCase); @@ -280,6 +290,34 @@ public class ChatWebSocketManager } break; + case MessageTypes.InboxSync: + await SendInboxSyncToClientAsync(client, ct); + break; + + case MessageTypes.InboxAction: + var inboxAct = envelope.Unpack(); + if (inboxAct != null) + { + await HandleInboxActionAsync(client, inboxAct, ct); + } + break; + + case MessageTypes.UpdateInboxPreferences: + var prefsPkg = envelope.Unpack(); + if (prefsPkg != null) + { + await HandleUpdateInboxPreferencesAsync(client, prefsPkg, ct); + } + break; + + case MessageTypes.ToggleFollowChannel: + var followPkg = envelope.Unpack(); + if (followPkg != null) + { + await HandleToggleFollowChannelAsync(client, followPkg, ct); + } + break; + case MessageTypes.UserListSync: case "GET_USERS": await BroadcastUserListAsync(); @@ -515,6 +553,13 @@ public class ChatWebSocketManager await _db.SaveMessageAsync(message); + // If sender had unread inbox items in this conversation, mark them read + int senderMarked = await _db.MarkChannelInboxItemsReadAsync(client.User.Id, channelId); + if (senderMarked > 0) + { + await SyncInboxForUserAsync(client.User.Id, ct); + } + if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group) { await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message }); @@ -523,6 +568,8 @@ public class ChatWebSocketManager { await BroadcastToChannelAsync(channelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message }); } + + await ProcessMessageInboxNotificationsAsync(channel, message, ct); } private async Task HandleJoinChannelAsync(ConnectedClient client, string channelId, CancellationToken ct) @@ -546,6 +593,12 @@ public class ChatWebSocketManager client.ActiveChannelId = channelId; + int markedRead = await _db.MarkChannelInboxItemsReadAsync(client.User.Id, channelId); + if (markedRead > 0) + { + await SyncInboxForUserAsync(client.User.Id, ct); + } + await SendChannelListToClientAsync(client, ct); await SendHistoryPageAsync(client, channelId, offset: 0, limit: 50, prepend: false, ct); } @@ -662,6 +715,12 @@ public class ChatWebSocketManager Text = $"Group chat '{InputSanitizer.SanitizeChannelName(group.Name)}' created by @{InputSanitizer.SanitizeUsername(client.User.Username)} ({group.MemberIds.Count}/{group.MaxUsers} members).", Level = "Success" }); + + // Notify initial invited members via Inbox & Web Push + foreach (var invitedUserId in group.MemberIds.Where(id => !string.Equals(id, client.User.Id, StringComparison.OrdinalIgnoreCase))) + { + await CreateGroupInviteInboxItemAsync(group, client.User, invitedUserId, ct); + } } private async Task HandleInviteToGroupAsync(ConnectedClient client, InviteToGroupPacket packet, CancellationToken ct) @@ -723,6 +782,8 @@ public class ChatWebSocketManager Text = $"@{InputSanitizer.SanitizeUsername(targetUser.Username)} was added to group '{InputSanitizer.SanitizeChannelName(group.Name)}' by @{InputSanitizer.SanitizeUsername(client.User.Username)}.", Level = "Info" }); + + await CreateGroupInviteInboxItemAsync(updatedGroup ?? group, client.User, targetUser.Id, ct); } private async Task HandleLeaveGroupAsync(ConnectedClient client, LeaveGroupPacket packet, CancellationToken ct) @@ -854,6 +915,10 @@ public class ChatWebSocketManager if (modResult != null) { await client.SendMessageAsync(MessageTypes.CommandResult, modResult, ct); + if (cmd == "announce" && modResult.Success && !string.IsNullOrWhiteSpace(packet.Args)) + { + await CreateAnnouncementInboxItemsAsync(client.User, packet.Args.Trim(), packet.ChannelId, ct); + } return; } } @@ -877,11 +942,140 @@ public class ChatWebSocketManager $" /group create [users] - Create a group chat (max {_options.MaxGroupChatUsers} users)\n" + " /group invite - Invite a user to the active group chat\n" + " /group leave - Leave the active group chat\n" + + " /follow [channel] - Follow/unfollow a conversation for Inbox notifications\n" + + " /inbox [readall|clear] - Manage Inbox notifications & preferences\n" + + " /announce - Broadcast an official announcement (Admin/Owner)\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 "announce": + if (client.User.Role != UserRoles.Owner && client.User.Role != UserRoles.Admin) + { + await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket + { + Success = false, + Output = "Only Admins and Owners can use /announce.", + ChannelId = packet.ChannelId + }, ct); + break; + } + if (string.IsNullOrWhiteSpace(packet.Args)) + { + await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket + { + Success = false, + Output = "Usage: /announce ", + ChannelId = packet.ChannelId + }, ct); + break; + } + string announceText = packet.Args.Trim(); + await BroadcastSystemNoticeAsync($"📢 OFFICIAL ANNOUNCEMENT by @{InputSanitizer.SanitizeUsername(client.User.Username)}: {announceText}", "Warning"); + await CreateAnnouncementInboxItemsAsync(client.User, announceText, packet.ChannelId, ct); + await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket + { + Success = true, + Output = $"📢 Announcement broadcast: {announceText}", + ChannelId = packet.ChannelId + }, ct); + break; + + case "follow": + case "unfollow": + case "mute": + string targetChArg = (packet.Args ?? string.Empty).Trim().TrimStart('#', '@'); + string resolvedChId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId; + if (!string.IsNullOrWhiteSpace(targetChArg)) + { + var byName = await _db.GetChannelByNameAsync(targetChArg); + if (byName != null) + { + resolvedChId = byName.Id; + } + else + { + var userGroups = await _db.GetGroupChatsForUserAsync(client.User.Id); + var userDms = await _db.GetDirectMessagesForUserAsync(client.User.Id, _options.AllowDmE2ee); + var matched = userGroups.FirstOrDefault(g => g.Name.Equals(targetChArg, StringComparison.OrdinalIgnoreCase)) + ?? userDms.FirstOrDefault(d => d.Name.TrimStart('@').Equals(targetChArg, StringComparison.OrdinalIgnoreCase)); + if (matched != null) + { + resolvedChId = matched.Id; + } + } + } + bool? explicitFollow = cmd == "unfollow" || cmd == "mute" ? false : (cmd == "follow" && !string.IsNullOrWhiteSpace(targetChArg) ? true : null); + await HandleToggleFollowChannelAsync(client, new ToggleFollowChannelPacket + { + ChannelId = resolvedChId, + Follow = explicitFollow + }, ct); + break; + + case "inbox": + var inboxArgs = (packet.Args ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (inboxArgs.Length == 0) + { + await SendInboxSyncToClientAsync(client, ct); + int unread = await _db.GetUnreadInboxCountAsync(client.User.Id); + await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket + { + Success = true, + Output = $"Inbox synced ({unread} unread). Usage: /inbox readall | /inbox clear [all] | /inbox ", + ChannelId = packet.ChannelId + }, ct); + break; + } + string inboxSub = inboxArgs[0].ToLowerInvariant(); + if (inboxSub == "readall" || inboxSub == "read") + { + await HandleInboxActionAsync(client, new InboxActionPacket { Action = "mark_all_read" }, ct); + await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket + { + Success = true, + Output = "All Inbox items marked as read.", + ChannelId = packet.ChannelId + }, ct); + } + else if (inboxSub == "clear") + { + bool clearAll = inboxArgs.Length > 1 && inboxArgs[1].Equals("all", StringComparison.OrdinalIgnoreCase); + await HandleInboxActionAsync(client, new InboxActionPacket { Action = clearAll ? "clear_all" : "clear_read" }, ct); + await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket + { + Success = true, + Output = clearAll ? "Cleared all Inbox items." : "Cleared read Inbox items.", + ChannelId = packet.ChannelId + }, ct); + } + else if (inboxArgs.Length >= 2) + { + bool enablePref = inboxArgs[1].Equals("on", StringComparison.OrdinalIgnoreCase) || + inboxArgs[1].Equals("true", StringComparison.OrdinalIgnoreCase) || + inboxArgs[1].Equals("1", StringComparison.OrdinalIgnoreCase); + var prefUpdate = new UpdateInboxPreferencesPacket(); + switch (inboxSub) + { + case "mentions": prefUpdate.MentionsEnabled = enablePref; break; + case "announcements": prefUpdate.AnnouncementsEnabled = enablePref; break; + case "dms": + case "dm": prefUpdate.DirectMessagesEnabled = enablePref; break; + case "channels": + case "followed": prefUpdate.FollowedChannelsEnabled = enablePref; break; + case "push": prefUpdate.PushNotificationsEnabled = enablePref; break; + } + await HandleUpdateInboxPreferencesAsync(client, prefUpdate, ct); + await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket + { + Success = true, + Output = $"Updated Inbox setting '{inboxSub}' to {(enablePref ? "ON" : "OFF")}.", + ChannelId = packet.ChannelId + }, ct); + } + break; + case "motd": await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}", ChannelId = packet.ChannelId }, ct); break; @@ -1126,5 +1320,349 @@ public class ChatWebSocketManager { await BroadcastToChannelAsync(file.ChannelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = msg }); } + + if (channel != null) + { + await ProcessMessageInboxNotificationsAsync(channel, msg); + } } + + #region Inbox & Notification Processing + + public async Task SendInboxSyncToClientAsync(ConnectedClient client, CancellationToken ct = default) + { + var items = await _db.GetInboxItemsForUserAsync(client.User.Id, 100); + int unreadCount = await _db.GetUnreadInboxCountAsync(client.User.Id); + var prefs = await _db.GetInboxPreferencesAsync(client.User.Id); + + await client.SendMessageAsync(MessageTypes.InboxSync, new InboxSyncPacket + { + Items = items, + UnreadCount = unreadCount, + Preferences = prefs + }, ct); + } + + public async Task SyncInboxForUserAsync(string userId, CancellationToken ct = default) + { + var userClients = _clients.Values + .Where(c => string.Equals(c.User.Id, userId, StringComparison.OrdinalIgnoreCase)) + .ToList(); + if (userClients.Count == 0) return; + + var items = await _db.GetInboxItemsForUserAsync(userId, 100); + int unreadCount = await _db.GetUnreadInboxCountAsync(userId); + var prefs = await _db.GetInboxPreferencesAsync(userId); + + var packet = new InboxSyncPacket + { + Items = items, + UnreadCount = unreadCount, + Preferences = prefs + }; + + var envelope = NetworkEnvelope.Create(MessageTypes.InboxSync, packet); + await Task.WhenAll(userClients.Select(c => c.SendEnvelopeAsync(envelope, ct))); + } + + private async Task HandleInboxActionAsync(ConnectedClient client, InboxActionPacket packet, CancellationToken ct) + { + string action = (packet.Action ?? string.Empty).Trim().ToLowerInvariant(); + switch (action) + { + case "mark_read": + if (!string.IsNullOrWhiteSpace(packet.ItemId)) + { + await _db.MarkInboxItemReadAsync(client.User.Id, packet.ItemId); + } + if (!string.IsNullOrWhiteSpace(packet.ChannelId)) + { + await _db.MarkChannelInboxItemsReadAsync(client.User.Id, packet.ChannelId); + } + break; + + case "mark_all_read": + await _db.MarkAllInboxItemsReadAsync(client.User.Id); + break; + + case "dismiss": + case "delete": + if (!string.IsNullOrWhiteSpace(packet.ItemId)) + { + await _db.DeleteInboxItemAsync(client.User.Id, packet.ItemId); + } + break; + + case "clear_read": + await _db.ClearInboxItemsAsync(client.User.Id, onlyRead: true); + break; + + case "clear_all": + await _db.ClearInboxItemsAsync(client.User.Id, onlyRead: false); + break; + } + + await SyncInboxForUserAsync(client.User.Id, ct); + } + + private async Task HandleUpdateInboxPreferencesAsync(ConnectedClient client, UpdateInboxPreferencesPacket packet, CancellationToken ct) + { + var prefs = await _db.GetInboxPreferencesAsync(client.User.Id); + + if (packet.MentionsEnabled.HasValue) prefs.MentionsEnabled = packet.MentionsEnabled.Value; + if (packet.AnnouncementsEnabled.HasValue) prefs.AnnouncementsEnabled = packet.AnnouncementsEnabled.Value; + if (packet.DirectMessagesEnabled.HasValue) prefs.DirectMessagesEnabled = packet.DirectMessagesEnabled.Value; + if (packet.FollowedChannelsEnabled.HasValue) prefs.FollowedChannelsEnabled = packet.FollowedChannelsEnabled.Value; + if (packet.PushNotificationsEnabled.HasValue) prefs.PushNotificationsEnabled = packet.PushNotificationsEnabled.Value; + + await _db.SaveInboxPreferencesAsync(prefs); + await SyncInboxForUserAsync(client.User.Id, ct); + } + + private async Task HandleToggleFollowChannelAsync(ConnectedClient client, ToggleFollowChannelPacket packet, CancellationToken ct) + { + string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId; + if (string.IsNullOrWhiteSpace(channelId)) + { + await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "No conversation selected to follow/unfollow." }, ct); + return; + } + + var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee); + if (channel == null) + { + await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Conversation 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 do not have access to this conversation." }, ct); + return; + } + } + + bool isNowFollowed = await _db.ToggleChannelFollowAsync(client.User.Id, channel, packet.Follow); + await SyncInboxForUserAsync(client.User.Id, ct); + + string displayConv = channel.Type == ChannelTypes.Channel + ? $"#{channel.Name}" + : channel.Name; + string statusText = isNowFollowed + ? $"🔔 Following {displayConv} for Inbox & Push notifications." + : $"🔕 Muted / unfollowed {displayConv} notifications."; + + await client.SendMessageAsync(MessageTypes.SystemNotice, new SystemNoticePacket + { + Text = statusText, + Level = isNowFollowed ? "Success" : "Info" + }, ct); + } + + public static bool IsUserMentioned(string content, string username) + { + if (string.IsNullOrWhiteSpace(content) || string.IsNullOrWhiteSpace(username)) + { + return false; + } + + if (E2eeCrypto.IsEncryptedPayload(content)) + { + return false; + } + + if (Regex.IsMatch(content, @"(^|[^\w])@(everyone|here)(?=$|[^\w])", RegexOptions.IgnoreCase)) + { + return true; + } + + string pattern = $@"(^|[^\w])@{Regex.Escape(username.Trim().TrimStart('@'))}(?=$|[^\w])"; + return Regex.IsMatch(content, pattern, RegexOptions.IgnoreCase); + } + + private async Task ProcessMessageInboxNotificationsAsync(Channel channel, ChatMessage message, CancellationToken ct = default) + { + var allUsers = await _db.GetAllUsersAsync(); + var userById = allUsers.ToDictionary(u => u.Id, StringComparer.OrdinalIgnoreCase); + + IEnumerable candidateUsers; + if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group) + { + candidateUsers = channel.MemberIds + .Where(id => !string.Equals(id, message.SenderId, StringComparison.OrdinalIgnoreCase)) + .Select(id => userById.GetValueOrDefault(id)) + .Where(u => u != null)!; + } + else + { + candidateUsers = allUsers + .Where(u => !string.Equals(u.Id, message.SenderId, StringComparison.OrdinalIgnoreCase)); + } + + bool isAnnouncementChannel = channel.Type == ChannelTypes.Channel && + string.Equals(channel.Name, "announcements", StringComparison.OrdinalIgnoreCase); + + foreach (var recipient in candidateUsers) + { + var prefs = await _db.GetInboxPreferencesAsync(recipient.Id); + string? matchedCategory = null; + + bool isMention = !message.IsEncrypted && IsUserMentioned(message.Content, recipient.Username); + if (isMention && prefs.MentionsEnabled) + { + matchedCategory = InboxCategories.Mention; + } + else if (isAnnouncementChannel && prefs.AnnouncementsEnabled) + { + matchedCategory = InboxCategories.Announcement; + } + else if (channel.Type == ChannelTypes.DirectMessage) + { + bool isMuted = prefs.MutedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase); + if (prefs.DirectMessagesEnabled && !isMuted) + { + matchedCategory = InboxCategories.DirectMessage; + } + } + else if (channel.Type == ChannelTypes.Group) + { + bool isMuted = prefs.MutedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase); + if (prefs.DirectMessagesEnabled && !isMuted) + { + matchedCategory = InboxCategories.GroupMessage; + } + } + else if (channel.Type == ChannelTypes.Channel) + { + bool isFollowed = prefs.FollowedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase); + if (prefs.FollowedChannelsEnabled && isFollowed) + { + matchedCategory = InboxCategories.FollowedChannel; + } + } + + if (matchedCategory == null) + { + continue; + } + + string channelDisplayName = channel.Type == ChannelTypes.DirectMessage + ? message.SenderUsername + : channel.Name; + + var inboxItem = new InboxItem + { + UserId = recipient.Id, + ChannelId = channel.Id, + ChannelName = channelDisplayName, + ChannelType = channel.Type, + MessageId = message.Id, + SenderId = message.SenderId, + SenderUsername = message.SenderUsername, + Category = matchedCategory, + ContentPreview = message.Content, + IsEncrypted = message.IsEncrypted, + SenderPublicKey = message.SenderPublicKey, + RecipientPublicKey = message.RecipientPublicKey, + IsRead = false, + CreatedAt = message.CreatedAt + }; + + await DeliverInboxItemAsync(inboxItem, prefs, ct); + } + } + + private async Task CreateGroupInviteInboxItemAsync(Channel group, User inviter, string targetUserId, CancellationToken ct) + { + if (string.Equals(inviter.Id, targetUserId, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + var prefs = await _db.GetInboxPreferencesAsync(targetUserId); + if (!prefs.DirectMessagesEnabled) + { + return; + } + + var item = new InboxItem + { + UserId = targetUserId, + ChannelId = group.Id, + ChannelName = group.Name, + ChannelType = ChannelTypes.Group, + SenderId = inviter.Id, + SenderUsername = inviter.Username, + Category = InboxCategories.GroupInvite, + ContentPreview = $"@{inviter.Username} added you to group chat '{group.Name}'.", + IsEncrypted = false, + IsRead = false, + CreatedAt = DateTime.UtcNow + }; + + await DeliverInboxItemAsync(item, prefs, ct); + } + + private async Task CreateAnnouncementInboxItemsAsync(User sender, string announcementText, string fallbackChannelId, CancellationToken ct) + { + var announcementsCh = await _db.GetChannelByNameAsync("announcements"); + string channelId = announcementsCh?.Id ?? fallbackChannelId; + string channelName = announcementsCh?.Name ?? "announcements"; + + var allUsers = await _db.GetAllUsersAsync(); + foreach (var recipient in allUsers.Where(u => !string.Equals(u.Id, sender.Id, StringComparison.OrdinalIgnoreCase))) + { + var prefs = await _db.GetInboxPreferencesAsync(recipient.Id); + if (!prefs.AnnouncementsEnabled) continue; + + var item = new InboxItem + { + UserId = recipient.Id, + ChannelId = channelId, + ChannelName = channelName, + ChannelType = ChannelTypes.Channel, + SenderId = sender.Id, + SenderUsername = sender.Username, + Category = InboxCategories.Announcement, + ContentPreview = announcementText, + IsEncrypted = false, + IsRead = false, + CreatedAt = DateTime.UtcNow + }; + + await DeliverInboxItemAsync(item, prefs, ct); + } + } + + private async Task DeliverInboxItemAsync(InboxItem item, InboxPreferences prefs, CancellationToken ct) + { + await _db.CreateInboxItemAsync(item); + int unreadCount = await _db.GetUnreadInboxCountAsync(item.UserId); + + var newPacket = new InboxNewItemPacket + { + Item = item, + UnreadCount = unreadCount + }; + var envelope = NetworkEnvelope.Create(MessageTypes.InboxNewItem, newPacket); + + var targetClients = _clients.Values + .Where(c => string.Equals(c.User.Id, item.UserId, StringComparison.OrdinalIgnoreCase)) + .ToList(); + + if (targetClients.Count > 0) + { + await Task.WhenAll(targetClients.Select(c => c.SendEnvelopeAsync(envelope, ct))); + } + + if (_webPush != null && prefs.PushNotificationsEnabled) + { + await _webPush.SendPushForInboxItemAsync(item, prefs, ct); + } + } + + #endregion } diff --git a/src/GsDChat.Server/wwwroot/app.css b/src/GsDChat.Server/wwwroot/app.css index eb3263d..8f0bfb6 100644 --- a/src/GsDChat.Server/wwwroot/app.css +++ b/src/GsDChat.Server/wwwroot/app.css @@ -704,7 +704,8 @@ html, body { .channel-list, .user-list, -.files-list { +.files-list, +.inbox-list { overflow-y: auto; padding: 10px; display: flex; @@ -714,10 +715,139 @@ html, body { } .user-list, -.files-list { +.files-list, +.inbox-list { flex: 1; } +.inbox-badge { + display: inline-block; + padding: 0 5px; + margin-left: 3px; + font-size: 0.72rem; + font-weight: 700; + background-color: var(--ctp-red); + color: var(--ctp-crust); +} + +.inbox-settings-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 8px 14px; + background-color: var(--ctp-crust); + border-bottom: 1px solid var(--ctp-surface1); + flex-shrink: 0; +} + +.inbox-prefs-group, +.inbox-push-group { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.inbox-prefs-label { + font-size: 0.74rem; + font-weight: 700; + color: var(--ctp-subtext0); + letter-spacing: 0.04em; +} + +.inbox-item { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 10px; + padding: 8px 12px; + background-color: var(--ctp-mantle); + border: 1px solid var(--ctp-surface1); + border-left: 3px solid var(--ctp-surface1); + cursor: pointer; + transition: border-color 0.1s, background-color 0.1s; +} + +.inbox-item:hover { + background-color: var(--ctp-surface0); + border-color: var(--ctp-mauve); +} + +.inbox-item.unread { + border-left-color: var(--ctp-mauve); + background-color: #1c1c2e; +} + +.inbox-item-main { + display: flex; + flex-direction: column; + gap: 4px; + flex: 1; + min-width: 0; +} + +.inbox-item-top { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + font-size: 0.82rem; +} + +.inbox-category-badge { + font-size: 0.68rem; + font-weight: 700; + padding: 1px 5px; + border: 1px solid var(--ctp-surface2); + text-transform: uppercase; +} + +.inbox-category-badge.cat-mention { + color: var(--ctp-yellow); + border-color: var(--ctp-yellow); + background-color: rgba(249, 226, 175, 0.12); +} + +.inbox-category-badge.cat-announcement { + color: var(--ctp-red); + border-color: var(--ctp-red); + background-color: rgba(243, 139, 168, 0.12); +} + +.inbox-category-badge.cat-dm { + color: var(--ctp-green); + border-color: var(--ctp-green); + background-color: rgba(166, 227, 161, 0.12); +} + +.inbox-category-badge.cat-followed, +.inbox-category-badge.cat-group_invite { + color: var(--ctp-sapphire); + border-color: var(--ctp-sapphire); + background-color: rgba(116, 199, 236, 0.12); +} + +.inbox-unread-dot { + color: var(--ctp-mauve); + font-weight: 700; +} + +.inbox-item-preview { + font-size: 0.86rem; + color: var(--ctp-text); + word-break: break-word; + white-space: pre-wrap; +} + +.inbox-item-actions { + display: flex; + align-items: center; + gap: 4px; + flex-shrink: 0; +} + .channel-item, .user-item, .file-item { diff --git a/src/GsDChat.Server/wwwroot/app.js b/src/GsDChat.Server/wwwroot/app.js index 4156426..ddabb4c 100644 --- a/src/GsDChat.Server/wwwroot/app.js +++ b/src/GsDChat.Server/wwwroot/app.js @@ -21,6 +21,20 @@ e2eePromptedDms: {}, // dmChannelId -> bool (prevent repeated intrusive prompts after dismiss) users: [], files: [], + inboxItems: [], + unreadInboxCount: 0, + inboxPreferences: { + mentionsEnabled: true, + announcementsEnabled: true, + directMessagesEnabled: true, + followedChannelsEnabled: true, + pushNotificationsEnabled: true, + followedChannelIds: [], + mutedChannelIds: [] + }, + vapidPublicKey: null, + swRegistration: null, + pushSubscribed: false, socket: null, isRegister: false, reconnectTimer: null @@ -31,6 +45,8 @@ serverTitle: document.getElementById('serverTitle'), connIndicator: document.getElementById('connIndicator'), navTabs: document.querySelectorAll('.nav-tab'), + navTabInbox: document.getElementById('navTabInbox'), + inboxUnreadBadge: document.getElementById('inboxUnreadBadge'), tabViews: document.querySelectorAll('.tab-view'), currentUsername: document.getElementById('currentUsername'), currentUserRole: document.getElementById('currentUserRole'), @@ -43,6 +59,7 @@ channelSelectDropdown: document.getElementById('channelSelectDropdown'), chatSecurityBadge: document.getElementById('chatSecurityBadge'), activeChannelTopic: document.getElementById('activeChannelTopic'), + toggleFollowBtn: document.getElementById('toggleFollowBtn'), toggleDmE2eeBtn: document.getElementById('toggleDmE2eeBtn'), inviteGroupBtn: document.getElementById('inviteGroupBtn'), leaveGroupBtn: document.getElementById('leaveGroupBtn'), @@ -93,6 +110,19 @@ filesList: document.getElementById('filesList'), filesViewUploadInput: document.getElementById('filesViewUploadInput'), + // Inbox View + inboxHeaderCount: document.getElementById('inboxHeaderCount'), + markAllReadInboxBtn: document.getElementById('markAllReadInboxBtn'), + clearReadInboxBtn: document.getElementById('clearReadInboxBtn'), + clearAllInboxBtn: document.getElementById('clearAllInboxBtn'), + prefMentionsBtn: document.getElementById('prefMentionsBtn'), + prefAnnouncementsBtn: document.getElementById('prefAnnouncementsBtn'), + prefDmsBtn: document.getElementById('prefDmsBtn'), + prefFollowedBtn: document.getElementById('prefFollowedBtn'), + toggleWebPushBtn: document.getElementById('toggleWebPushBtn'), + testWebPushBtn: document.getElementById('testWebPushBtn'), + inboxList: document.getElementById('inboxList'), + // E2EE Vault Modal e2eeModal: document.getElementById('e2eeModal'), e2eeModalTitle: document.getElementById('e2eeModalTitle'), @@ -466,6 +496,53 @@ return msg; } + async function decryptInboxItemIfNeeded(item) { + if (!item) return item; + const rawPreview = item._rawCiphertext || item.contentPreview || item.ContentPreview || ''; + const isEnc = item.isEncrypted || item.IsEncrypted || rawPreview.startsWith(E2EE_PREFIX); + if (!isEnc) return item; + + item.isEncrypted = true; + if (rawPreview.startsWith(E2EE_PREFIX)) { + item._rawCiphertext = rawPreview; + } else { + return item; + } + + if (!state.privateKey) { + const lockedPlaceholder = '[🔒 Encrypted DM - Click [🔒 E2EE Vault] and enter PIN to unlock]'; + item.contentPreview = lockedPlaceholder; + item.ContentPreview = lockedPlaceholder; + return item; + } + + const senderId = item.senderId || item.SenderId || ''; + const senderPubKey = item.senderPublicKey || item.SenderPublicKey || ''; + const recipientPubKey = item.recipientPublicKey || item.RecipientPublicKey || ''; + const chId = item.channelId || item.ChannelId || ''; + const isSentByMe = state.user && senderId.toLowerCase() === (state.user.id || '').toLowerCase(); + + let peerKey = isSentByMe ? recipientPubKey : senderPubKey; + if (!peerKey) { + const conv = getConversationById(chId); + if (conv) peerKey = getPeerPublicKeyForDm(conv); + } + if (!peerKey && senderId) { + const u = state.users.find(user => (user.id || user.Id || '').toLowerCase() === senderId.toLowerCase()); + if (u && (u.publicKey || u.PublicKey)) peerKey = u.publicKey || u.PublicKey; + } + if (!peerKey) { + peerKey = senderPubKey || recipientPubKey || null; + } + + if (peerKey && state.privateKey) { + const decrypted = await decryptDmMessage(rawPreview, state.privateKey, peerKey); + item.contentPreview = decrypted; + item.ContentPreview = decrypted; + } + return item; + } + async function reDecryptAllLoadedMessages() { for (const chId of Object.keys(state.messages)) { const list = state.messages[chId] || []; @@ -475,9 +552,15 @@ } } } + for (const item of state.inboxItems) { + if (item._rawCiphertext || ((item.contentPreview || item.ContentPreview || '').startsWith(E2EE_PREFIX))) { + await decryptInboxItemIfNeeded(item); + } + } if (state.activeChannelId) { renderMessages(); } + renderInbox(); } async function unlockOrInitE2eeWithPin(pin, resetKeys = false) { @@ -546,6 +629,216 @@ }; } + // ========================================== + // Service Worker & Web Push Notifications + // ========================================== + function urlBase64ToUint8Array(base64String) { + const padding = '='.repeat((4 - (base64String.length % 4)) % 4); + const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); + const rawData = window.atob(base64); + const outputArray = new Uint8Array(rawData.length); + for (let i = 0; i < rawData.length; ++i) { + outputArray[i] = rawData.charCodeAt(i); + } + return outputArray; + } + + async function initServiceWorkerAndPush() { + if (!('serviceWorker' in navigator)) return; + try { + const reg = await navigator.serviceWorker.register('/sw.js'); + state.swRegistration = reg; + + navigator.serviceWorker.addEventListener('message', (event) => { + const data = event.data || {}; + if (data.type === 'OPEN_CONVERSATION') { + if (data.itemId) { + sendInboxAction('mark_read', data.itemId); + } + if (data.channelId) { + joinChannel(data.channelId); + switchTab('chat'); + } else { + switchTab('inbox'); + } + } + }); + + if (reg.pushManager) { + const existingSub = await reg.pushManager.getSubscription(); + state.pushSubscribed = !!existingSub; + updateInboxPreferencesUI(); + if (existingSub && state.token) { + await syncSubscriptionToServer(existingSub); + } + } + } catch (err) { + console.warn('Service Worker registration skipped or failed:', err); + } + } + + async function syncSubscriptionToServer(subscription) { + if (!subscription || !state.token) return false; + try { + const subJson = subscription.toJSON(); + const endpoint = subJson.endpoint; + const p256dh = subJson.keys ? subJson.keys.p256dh : ''; + const auth = subJson.keys ? subJson.keys.auth : ''; + if (!endpoint || !p256dh || !auth) return false; + + const csrfRes = await fetch('/api/csrf-token'); + const csrfData = await csrfRes.json(); + const csrfToken = csrfData.token || ''; + + const res = await fetch('/api/push/subscribe', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${state.token}`, + 'X-CSRF-Token': csrfToken + }, + body: JSON.stringify({ + endpoint, + p256dh, + auth, + userAgent: navigator.userAgent || '' + }) + }); + return res.ok; + } catch { + return false; + } + } + + async function fetchVapidPublicKey() { + if (state.vapidPublicKey) return state.vapidPublicKey; + try { + const res = await fetch('/api/push/vapid-public-key'); + if (res.ok) { + const data = await res.json(); + state.vapidPublicKey = data.publicKey || data.PublicKey || ''; + } + } catch { + // ignore + } + return state.vapidPublicKey; + } + + async function toggleWebPushSubscription() { + if (!('serviceWorker' in navigator) || !('PushManager' in window)) { + showToast('Web Push is not supported in this browser.'); + return; + } + + if (state.pushSubscribed) { + await unsubscribeWebPush(); + } else { + await subscribeWebPush(); + } + } + + async function subscribeWebPush() { + try { + if ('Notification' in window) { + const perm = await Notification.requestPermission(); + if (perm !== 'granted') { + showToast('Notification permission denied by browser.'); + return; + } + } + + if (!state.swRegistration) { + state.swRegistration = await navigator.serviceWorker.register('/sw.js'); + } + await navigator.serviceWorker.ready; + + const vapidKey = await fetchVapidPublicKey(); + if (!vapidKey) { + showToast('Server VAPID public key is unavailable.'); + return; + } + + const sub = await state.swRegistration.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: urlBase64ToUint8Array(vapidKey) + }); + + const ok = await syncSubscriptionToServer(sub); + if (ok) { + state.pushSubscribed = true; + state.inboxPreferences.pushNotificationsEnabled = true; + sendEnvelope('UPDATE_INBOX_PREFERENCES', { + mentionsEnabled: state.inboxPreferences.mentionsEnabled, + announcementsEnabled: state.inboxPreferences.announcementsEnabled, + directMessagesEnabled: state.inboxPreferences.directMessagesEnabled, + followedChannelsEnabled: state.inboxPreferences.followedChannelsEnabled, + pushNotificationsEnabled: true + }); + updateInboxPreferencesUI(); + showToast('🔔 Background Web Push notifications enabled on this browser!'); + } else { + showToast('Failed to register Web Push subscription with server.'); + } + } catch (err) { + showToast(`Web Push setup failed: ${err.message || err}`); + } + } + + async function unsubscribeWebPush() { + try { + if (state.swRegistration && state.swRegistration.pushManager) { + const sub = await state.swRegistration.pushManager.getSubscription(); + if (sub) { + if (state.token) { + const csrfRes = await fetch('/api/csrf-token'); + const csrfData = await csrfRes.json(); + await fetch('/api/push/unsubscribe', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${state.token}`, + 'X-CSRF-Token': csrfData.token || '' + }, + body: JSON.stringify({ endpoint: sub.endpoint }) + }); + } + await sub.unsubscribe(); + } + } + state.pushSubscribed = false; + updateInboxPreferencesUI(); + showToast('🔕 Web Push notifications disabled on this browser.'); + } catch (err) { + showToast(`Unsubscribe error: ${err.message || err}`); + } + } + + async function sendTestWebPush() { + if (!state.token) { + showToast('Login required'); + return; + } + try { + const csrfRes = await fetch('/api/csrf-token'); + const csrfData = await csrfRes.json(); + const res = await fetch('/api/push/test', { + method: 'POST', + headers: { + 'Authorization': `Bearer ${state.token}`, + 'X-CSRF-Token': csrfData.token || '' + } + }); + const data = await res.json(); + if (res.ok && data.success) { + showToast('🔔 Test Web Push sent! Check your OS notification tray.'); + } else { + showToast(data.message || 'Enable Web Push first before testing.'); + } + } catch (err) { + showToast(`Test push failed: ${err.message || err}`); + } + } + // ========================================== // Initialization // ========================================== @@ -553,6 +846,7 @@ initElements(); setupEventListeners(); await fetchServerInfo(); + await initServiceWorkerAndPush(); if (state.token && state.user) { loadCachedKeysForCurrentUser(); @@ -581,6 +875,9 @@ ? state.serverInfo.allowDmE2ee : (state.serverInfo.AllowDmE2ee !== undefined ? state.serverInfo.AllowDmE2ee : true); state.maxGroupChatUsers = state.serverInfo.maxGroupChatUsers || state.serverInfo.MaxGroupChatUsers || 10; + if (state.serverInfo.vapidPublicKey || state.serverInfo.VapidPublicKey) { + state.vapidPublicKey = state.serverInfo.vapidPublicKey || state.serverInfo.VapidPublicKey; + } el.serverTitle.textContent = state.serverInfo.serverName || 'GsDChat'; el.modalServerName.textContent = state.serverInfo.serverName || 'GsDChat'; @@ -839,6 +1136,23 @@ const first = state.channels[0]; state.activeChannelId = first.id || first.Id; } + + // Check if opened from an OS push notification deep link (?channel=...) + try { + const params = new URLSearchParams(window.location.search); + const deepChannel = params.get('channel'); + const deepInboxItem = params.get('inboxItem'); + if (deepInboxItem) { + sendInboxAction('mark_read', deepInboxItem); + } + if (deepChannel && getConversationById(deepChannel)) { + state.activeChannelId = deepChannel; + window.history.replaceState({}, document.title, window.location.pathname); + } + } catch { + // Ignore URL parse issues + } + renderChannels(); updateActiveChannelHeader(); checkLazyDmE2eePrompt(); @@ -909,6 +1223,82 @@ renderFiles(); break; + case 'INBOX_SYNC': { + const rawItems = payload.items || payload.Items || []; + const decryptedItems = []; + for (const item of rawItems) { + decryptedItems.push(await decryptInboxItemIfNeeded(item)); + } + state.inboxItems = decryptedItems; + state.unreadInboxCount = payload.unreadCount ?? payload.UnreadCount ?? decryptedItems.filter(i => !(i.isRead ?? i.IsRead)).length; + const prefs = payload.preferences || payload.Preferences; + if (prefs) { + state.inboxPreferences = { + mentionsEnabled: prefs.mentionsEnabled ?? prefs.MentionsEnabled ?? true, + announcementsEnabled: prefs.announcementsEnabled ?? prefs.AnnouncementsEnabled ?? true, + directMessagesEnabled: prefs.directMessagesEnabled ?? prefs.DirectMessagesEnabled ?? true, + followedChannelsEnabled: prefs.followedChannelsEnabled ?? prefs.FollowedChannelsEnabled ?? true, + pushNotificationsEnabled: prefs.pushNotificationsEnabled ?? prefs.PushNotificationsEnabled ?? true, + followedChannelIds: prefs.followedChannelIds || prefs.FollowedChannelIds || [], + mutedChannelIds: prefs.mutedChannelIds || prefs.MutedChannelIds || [] + }; + } + updateInboxBadge(); + updateInboxPreferencesUI(); + renderInbox(); + updateActiveChannelHeader(); + renderChannels(); + break; + } + + case 'INBOX_NEW_ITEM': { + const rawItem = payload.item || payload.Item; + if (rawItem) { + const item = await decryptInboxItemIfNeeded(rawItem); + const itemId = item.id || item.Id; + state.inboxItems = [item, ...state.inboxItems.filter(x => (x.id || x.Id) !== itemId)]; + state.unreadInboxCount = payload.unreadCount ?? payload.UnreadCount ?? state.inboxItems.filter(i => !(i.isRead ?? i.IsRead)).length; + updateInboxBadge(); + renderInbox(); + + const itemChId = item.channelId || item.ChannelId; + const itemCategory = (item.category || item.Category || 'mention').toLowerCase(); + const itemSender = item.senderUsername || item.SenderUsername || 'System'; + const itemChName = item.channelName || item.ChannelName || 'chat'; + const isViewingSameChannel = state.activeChannelId === itemChId && !document.hidden; + + if (!isViewingSameChannel) { + showToast(`🔔 [${itemCategory.toUpperCase()}] @${itemSender} in ${itemChName}`); + } + + // Fallback desktop Notification when tab is in background and Service Worker Push isn't active + if (document.hidden && !state.pushSubscribed && 'Notification' in window && Notification.permission === 'granted') { + try { + const isEnc = item.isEncrypted || item.IsEncrypted; + const notifBody = isEnc && !state.privateKey + ? `🔒 New encrypted message from @${itemSender}` + : `@${itemSender}: ${item.contentPreview || item.ContentPreview || ''}`; + const n = new Notification(`GsDChat (${itemChName})`, { + body: notifBody, + tag: `gsdchat-ws-${itemChId || itemId}` + }); + n.onclick = () => { + window.focus(); + sendInboxAction('mark_read', itemId); + if (itemChId) { + joinChannel(itemChId); + switchTab('chat'); + } + n.close(); + }; + } catch { + // Ignore Notification constructor errors on restricted environments + } + } + } + break; + } + case 'SYSTEM_NOTICE': const noticeText = payload.text || payload.Text; if (noticeText) { @@ -953,6 +1343,200 @@ return conv.type || conv.Type || 'Channel'; } + function isConversationFollowed(conv) { + if (!conv) return false; + const chId = (conv.id || conv.Id || '').toLowerCase(); + const followedIds = (state.inboxPreferences && state.inboxPreferences.followedChannelIds) || []; + const mutedIds = (state.inboxPreferences && state.inboxPreferences.mutedChannelIds) || []; + if (followedIds.some(id => (id || '').toLowerCase() === chId)) return true; + if (mutedIds.some(id => (id || '').toLowerCase() === chId)) return false; + const cType = getConversationType(conv); + return cType === 'DM' || cType === 'Group'; + } + + function toggleFollowConversation(channelId, explicitFollow) { + const conv = getConversationById(channelId || state.activeChannelId); + if (!conv) return; + const chId = conv.id || conv.Id; + const currentlyFollowed = isConversationFollowed(conv); + const nextFollow = explicitFollow !== undefined ? explicitFollow : !currentlyFollowed; + sendEnvelope('TOGGLE_FOLLOW_CHANNEL', { + channelId: chId, + follow: nextFollow + }); + } + + function sendInboxAction(action, itemId = null, channelId = null) { + sendEnvelope('INBOX_ACTION', { + action: action, + itemId: itemId, + channelId: channelId + }); + } + + function toggleInboxPreference(prefKey) { + const prefs = state.inboxPreferences; + if (prefKey in prefs) { + prefs[prefKey] = !prefs[prefKey]; + sendEnvelope('UPDATE_INBOX_PREFERENCES', { + mentionsEnabled: prefs.mentionsEnabled, + announcementsEnabled: prefs.announcementsEnabled, + directMessagesEnabled: prefs.directMessagesEnabled, + followedChannelsEnabled: prefs.followedChannelsEnabled, + pushNotificationsEnabled: prefs.pushNotificationsEnabled + }); + updateInboxPreferencesUI(); + } + } + + function updateInboxBadge() { + initElements(); + const count = state.unreadInboxCount || 0; + if (el.inboxUnreadBadge) { + if (count > 0) { + el.inboxUnreadBadge.style.display = 'inline-block'; + el.inboxUnreadBadge.textContent = count > 99 ? '99+' : String(count); + } else { + el.inboxUnreadBadge.style.display = 'none'; + el.inboxUnreadBadge.textContent = '0'; + } + } + if (el.inboxHeaderCount) { + el.inboxHeaderCount.textContent = `(${count} Unread / ${state.inboxItems.length} Total)`; + } + } + + function updateInboxPreferencesUI() { + initElements(); + const p = state.inboxPreferences; + if (el.prefMentionsBtn) { + el.prefMentionsBtn.textContent = `[Mentions: ${p.mentionsEnabled ? 'ON' : 'OFF'}]`; + } + if (el.prefAnnouncementsBtn) { + el.prefAnnouncementsBtn.textContent = `[Announcements: ${p.announcementsEnabled ? 'ON' : 'OFF'}]`; + } + if (el.prefDmsBtn) { + el.prefDmsBtn.textContent = `[DMs & Groups: ${p.directMessagesEnabled ? 'ON' : 'OFF'}]`; + } + if (el.prefFollowedBtn) { + el.prefFollowedBtn.textContent = `[Followed Channels: ${p.followedChannelsEnabled ? 'ON' : 'OFF'}]`; + } + if (el.toggleWebPushBtn) { + const activePush = state.pushSubscribed && p.pushNotificationsEnabled; + el.toggleWebPushBtn.textContent = activePush ? '[🔔 Web Push: ON]' : '[🔕 Enable Web Push]'; + el.toggleWebPushBtn.className = activePush ? 'btn btn-sm btn-primary' : 'btn btn-sm btn-secondary'; + } + } + + function renderInbox() { + initElements(); + updateInboxBadge(); + updateInboxPreferencesUI(); + if (!el.inboxList) return; + + el.inboxList.innerHTML = ''; + if (state.inboxItems.length === 0) { + el.inboxList.innerHTML = '
Inbox is empty! Mentions (@username, @everyone, @here), #announcements, DMs, and followed channel messages will appear here.
'; + return; + } + + state.inboxItems.forEach(item => { + const itemId = item.id || item.Id; + const chId = item.channelId || item.ChannelId; + const chName = item.channelName || item.ChannelName || 'general'; + const chType = item.channelType || item.ChannelType || 'Channel'; + const sender = item.senderUsername || item.SenderUsername || 'User'; + const category = (item.category || item.Category || 'mention').toLowerCase(); + const preview = item.contentPreview || item.ContentPreview || ''; + const isRead = !!(item.isRead ?? item.IsRead); + const isEnc = !!(item.isEncrypted ?? item.IsEncrypted); + const createdAt = item.createdAt || item.CreatedAt; + const timeStr = createdAt ? new Date(createdAt).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : ''; + + let catLabel = 'MENTION'; + let catCss = 'mention'; + if (category === 'announcement') { + catLabel = 'ANNOUNCEMENT'; + catCss = 'announcement'; + } else if (category === 'dm' || category === 'directmessage') { + catLabel = 'DIRECT MSG'; + catCss = 'dm'; + } else if (category === 'groupmessage') { + catLabel = 'GROUP MSG'; + catCss = 'followed'; + } else if (category === 'followed' || category === 'followedchannel') { + catLabel = 'FOLLOWED'; + catCss = 'followed'; + } else if (category === 'group_invite' || category === 'groupinvite') { + catLabel = 'GROUP INVITE'; + catCss = 'group_invite'; + } + + let convDisplay = `#${chName}`; + if (chType === 'DM') convDisplay = `DM @${chName.replace(/^@/, '')}`; + else if (chType === 'Group') convDisplay = `[Group] ${chName}`; + + const div = document.createElement('div'); + div.className = 'inbox-item' + (isRead ? '' : ' unread'); + div.innerHTML = ` +
+
+ ${isRead ? '' : '●'} + [${catLabel}] + ${escapeHtml(convDisplay)} + from @${escapeHtml(sender)} + ${isEnc ? '🔒 E2EE' : ''} + ${escapeHtml(timeStr)} +
+
${escapeHtml(preview)}
+
+
+ + + +
+ `; + + const openAction = () => { + if (!isRead) { + sendInboxAction('mark_read', itemId); + } + if (chId) { + joinChannel(chId); + switchTab('chat'); + } + }; + + div.addEventListener('click', openAction); + + const openBtn = div.querySelector('.btn-inbox-open'); + if (openBtn) { + openBtn.addEventListener('click', (e) => { + e.stopPropagation(); + openAction(); + }); + } + + const readBtn = div.querySelector('.btn-inbox-toggle-read'); + if (readBtn) { + readBtn.addEventListener('click', (e) => { + e.stopPropagation(); + sendInboxAction(isRead ? 'mark_unread' : 'mark_read', itemId); + }); + } + + const dismissBtn = div.querySelector('.btn-inbox-dismiss'); + if (dismissBtn) { + dismissBtn.addEventListener('click', (e) => { + e.stopPropagation(); + sendInboxAction('dismiss', itemId); + }); + } + + el.inboxList.appendChild(div); + }); + } + function checkLazyDmE2eePrompt() { const active = getConversationById(state.activeChannelId); if (!active || getConversationType(active) !== 'DM') return; @@ -1061,6 +1645,8 @@ renderChannels(); } else if (tabName === 'files') { renderFiles(); + } else if (tabName === 'inbox') { + renderInbox(); } else if (tabName === 'chat') { renderMessages(); } @@ -1079,6 +1665,21 @@ el.channelSelectDropdown.value = chId; } + if (el.toggleFollowBtn) { + const isFollowed = isConversationFollowed(active); + if (chType === 'Channel') { + el.toggleFollowBtn.textContent = isFollowed ? '[🔔 Following]' : '[🔔 Follow]'; + el.toggleFollowBtn.title = isFollowed + ? 'Receiving Inbox & Push notifications for this channel (click to unfollow)' + : 'Follow this channel to receive Inbox & Push notifications for all messages'; + } else { + el.toggleFollowBtn.textContent = isFollowed ? '[🔔 Following]' : '[🔕 Muted]'; + el.toggleFollowBtn.title = isFollowed + ? 'Receiving Inbox & Push notifications for this conversation (click to mute)' + : 'Notifications muted for this conversation (click to unmute)'; + } + } + if (chType === 'DM') { if (el.activeConvPrefix) el.activeConvPrefix.textContent = '@'; const dmIsE2ee = (active.isE2ee ?? active.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled; @@ -1147,6 +1748,7 @@ const chName = ch.name || ch.Name; const chTopic = ch.topic || ch.Topic || ''; const isActive = chId === state.activeChannelId; + const isFollowed = isConversationFollowed(ch); const item = document.createElement('div'); item.className = 'channel-item' + (isActive ? ' active' : ''); @@ -1155,8 +1757,18 @@ #${escapeHtml(chName)} ${escapeHtml(chTopic)} - ${isActive ? '[ACTIVE]' : ''} +
+ + ${isActive ? '[ACTIVE]' : ''} +
`; + const followBtn = item.querySelector('.btn-follow-conv'); + if (followBtn) { + followBtn.addEventListener('click', (e) => { + e.stopPropagation(); + toggleFollowConversation(chId, !isFollowed); + }); + } item.addEventListener('click', () => { joinChannel(chId); switchTab('chat'); @@ -1178,6 +1790,7 @@ const members = grp.memberUsernames || grp.MemberUsernames || []; const maxU = grp.maxUsers || grp.MaxUsers || state.maxGroupChatUsers; const isActive = gId === state.activeChannelId; + const isFollowed = isConversationFollowed(grp); const item = document.createElement('div'); item.className = 'channel-item' + (isActive ? ' active' : ''); @@ -1187,8 +1800,18 @@ [Group] ${escapeHtml(gName)} (${members.length}/${maxU}) ${escapeHtml(gTopic || membersText)} - ${isActive ? '[ACTIVE]' : ''} +
+ + ${isActive ? '[ACTIVE]' : ''} +
`; + const followBtn = item.querySelector('.btn-follow-conv'); + if (followBtn) { + followBtn.addEventListener('click', (e) => { + e.stopPropagation(); + toggleFollowConversation(gId, !isFollowed); + }); + } item.addEventListener('click', () => { joinChannel(gId); switchTab('chat'); @@ -1210,6 +1833,7 @@ const isE2ee = (dm.isE2ee ?? dm.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled; const peerReady = isDmPeerE2eeReady(dm); const isActive = dmId === state.activeChannelId; + const isFollowed = isConversationFollowed(dm); let descText = 'Plaintext (Server-Visible)'; let badgeLabel = 'Plain'; @@ -1236,10 +1860,18 @@ ${descText}
+ ${isActive ? '[ACTIVE]' : `${badgeLabel}`}
`; + const followBtn = item.querySelector('.btn-follow-conv'); + if (followBtn) { + followBtn.addEventListener('click', (e) => { + e.stopPropagation(); + toggleFollowConversation(dmId, !isFollowed); + }); + } const toggleBtn = item.querySelector('.btn-toggle-dm-e2ee'); if (toggleBtn) { toggleBtn.addEventListener('click', (e) => { @@ -1863,6 +2495,20 @@ return; } + if (cmd === 'inbox') { + if (!args) { + switchTab('inbox'); + return; + } + sendEnvelope('EXECUTE_COMMAND', { + command: cmd, + args: args, + channelId: state.activeChannelId || '' + }); + switchTab('inbox'); + return; + } + sendEnvelope('EXECUTE_COMMAND', { command: cmd, args: args, @@ -2015,6 +2661,38 @@ if (el.toggleDmE2eeBtn) { el.toggleDmE2eeBtn.addEventListener('click', () => toggleDmE2ee(state.activeChannelId)); } + if (el.toggleFollowBtn) { + el.toggleFollowBtn.addEventListener('click', () => toggleFollowConversation(state.activeChannelId)); + } + + // Inbox & Web Push Controls + if (el.markAllReadInboxBtn) { + el.markAllReadInboxBtn.addEventListener('click', () => sendInboxAction('mark_all_read')); + } + if (el.clearReadInboxBtn) { + el.clearReadInboxBtn.addEventListener('click', () => sendInboxAction('clear_read')); + } + if (el.clearAllInboxBtn) { + el.clearAllInboxBtn.addEventListener('click', () => sendInboxAction('clear_all')); + } + if (el.prefMentionsBtn) { + el.prefMentionsBtn.addEventListener('click', () => toggleInboxPreference('mentionsEnabled')); + } + if (el.prefAnnouncementsBtn) { + el.prefAnnouncementsBtn.addEventListener('click', () => toggleInboxPreference('announcementsEnabled')); + } + if (el.prefDmsBtn) { + el.prefDmsBtn.addEventListener('click', () => toggleInboxPreference('directMessagesEnabled')); + } + if (el.prefFollowedBtn) { + el.prefFollowedBtn.addEventListener('click', () => toggleInboxPreference('followedChannelsEnabled')); + } + if (el.toggleWebPushBtn) { + el.toggleWebPushBtn.addEventListener('click', toggleWebPushSubscription); + } + if (el.testWebPushBtn) { + el.testWebPushBtn.addEventListener('click', sendTestWebPush); + } if (el.e2eePinForm) { el.e2eePinForm.addEventListener('submit', async (e) => { e.preventDefault(); diff --git a/src/GsDChat.Server/wwwroot/index.html b/src/GsDChat.Server/wwwroot/index.html index 905376a..d9c7aa3 100644 --- a/src/GsDChat.Server/wwwroot/index.html +++ b/src/GsDChat.Server/wwwroot/index.html @@ -6,6 +6,7 @@ GsDChat - Web Client + @@ -49,6 +50,7 @@ +
@@ -76,6 +78,7 @@
+ @@ -228,6 +231,37 @@
+ +
+
+

== INBOX & NOTIFICATIONS (0 Unread) ==

+
+ + + +
+
+ +
+
+ TRIGGERS: + + + + +
+
+ WEB PUSH: + + +
+
+ +
+ +
+
+ diff --git a/src/GsDChat.Server/wwwroot/manifest.json b/src/GsDChat.Server/wwwroot/manifest.json new file mode 100644 index 0000000..8f2fb3b --- /dev/null +++ b/src/GsDChat.Server/wwwroot/manifest.json @@ -0,0 +1,10 @@ +{ + "name": "GsDChat - Terminal Hybrid Chat", + "short_name": "GsDChat", + "description": "High-performance terminal-inspired hybrid chat with End-to-End Encryption, Inbox, and Web Push Notifications.", + "start_url": "/", + "display": "standalone", + "background_color": "#0d1117", + "theme_color": "#00d4ff", + "icons": [] +} diff --git a/src/GsDChat.Server/wwwroot/sw.js b/src/GsDChat.Server/wwwroot/sw.js new file mode 100644 index 0000000..decab58 --- /dev/null +++ b/src/GsDChat.Server/wwwroot/sw.js @@ -0,0 +1,104 @@ +// ============================================================================ +// GsDChat Service Worker (Web Push Notifications & Background Deep-Linking) +// ============================================================================ + +self.addEventListener('install', (event) => { + event.waitUntil(self.skipWaiting()); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil(self.clients.claim()); +}); + +self.addEventListener('push', (event) => { + let payload = { + title: 'GsDChat Notification', + body: 'You have a new notification in your Inbox.', + channelId: '', + channelName: '', + category: 'mention', + itemId: '', + timestamp: new Date().toISOString() + }; + + if (event.data) { + try { + const parsed = event.data.json(); + payload = Object.assign(payload, parsed); + } catch (err) { + try { + payload.body = event.data.text(); + } catch (_) { + // Keep default body + } + } + } + + event.waitUntil((async () => { + const windowClients = await self.clients.matchAll({ + type: 'window', + includeUncontrolled: true + }); + + // Check if any open client window is currently focused in the foreground + let focusedClient = null; + for (const client of windowClients) { + if (client.focused || client.visibilityState === 'visible') { + focusedClient = client; + break; + } + } + + if (focusedClient && focusedClient.focused) { + // Suppress duplicate OS popup if the user is actively focused on the app; + // notify the foreground window so it can play an indicator if desired. + focusedClient.postMessage({ + type: 'PUSH_RECEIVED_FOREGROUND', + payload: payload + }); + return; + } + + const tag = payload.channelId + ? `gsdchat-${payload.category || 'notif'}-${payload.channelId}` + : `gsdchat-item-${payload.itemId || Date.now()}`; + + await self.registration.showNotification(payload.title || 'GsDChat', { + body: payload.body || 'New activity in GsDChat', + tag: tag, + renotify: true, + data: payload + }); + })()); +}); + +self.addEventListener('notificationclick', (event) => { + event.notification.close(); + const data = event.notification.data || {}; + + event.waitUntil((async () => { + const windowClients = await self.clients.matchAll({ + type: 'window', + includeUncontrolled: true + }); + + for (const client of windowClients) { + if ('focus' in client) { + await client.focus(); + client.postMessage({ + type: 'OPEN_CONVERSATION', + channelId: data.channelId || '', + itemId: data.itemId || '' + }); + return; + } + } + + if (self.clients.openWindow) { + const targetUrl = data.channelId + ? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}` + : '/'; + await self.clients.openWindow(targetUrl); + } + })()); +}); diff --git a/tests/GsDChat.Tests/CryptoTests.cs b/tests/GsDChat.Tests/CryptoTests.cs index 8d9162b..9aa34a5 100644 --- a/tests/GsDChat.Tests/CryptoTests.cs +++ b/tests/GsDChat.Tests/CryptoTests.cs @@ -113,4 +113,55 @@ public class CryptoTests string? wrongPassword = E2eeCrypto.UnwrapPrivateKey(wrapped, "WrongPassword", "Alice"); Assert.Null(wrongPassword); } + + [Fact] + public void WebPushCrypto_GenerateVapidKeys_And_SignVerifyJwt_ShouldSucceed() + { + var (publicKey, privateKey) = WebPushCrypto.GenerateVapidKeys(); + Assert.False(string.IsNullOrWhiteSpace(publicKey)); + Assert.False(string.IsNullOrWhiteSpace(privateKey)); + + var pubBytes = WebPushCrypto.Base64UrlDecode(publicKey); + var privBytes = WebPushCrypto.Base64UrlDecode(privateKey); + Assert.Equal(65, pubBytes.Length); + Assert.Equal(0x04, pubBytes[0]); + Assert.Equal(32, privBytes.Length); + + string authHeader = WebPushCrypto.CreateVapidAuthorizationHeader( + "https://fcm.googleapis.com/fcm/send/example123", + "mailto:admin@gsdchat.local", + publicKey, + privateKey); + + Assert.StartsWith("vapid t=", authHeader); + Assert.Contains($", k={publicKey}", authHeader); + + // Extract JWT token and verify ES256 signature + int tStart = authHeader.IndexOf("t=", StringComparison.Ordinal) + 2; + int tEnd = authHeader.IndexOf(", k=", StringComparison.Ordinal); + string jwt = authHeader.Substring(tStart, tEnd - tStart); + + Assert.True(WebPushCrypto.VerifyVapidJwt(jwt, publicKey)); + } + + [Fact] + public void WebPushCrypto_Rfc8291Aes128GcmPayloadEncryption_ShouldRoundTrip() + { + // Generate simulated browser push subscription keypair (p256dh) and 16-byte auth secret + var (subPub, subPriv) = WebPushCrypto.GenerateVapidKeys(); + byte[] authSecretBytes = new byte[16]; + System.Security.Cryptography.RandomNumberGenerator.Fill(authSecretBytes); + string authSecret = WebPushCrypto.Base64UrlEncode(authSecretBytes); + + string jsonPayload = "{\"title\":\"GsDChat (@Alice)\",\"body\":\"Hey @Bob check #announcements!\",\"channelId\":\"ch_1\"}"; + byte[] encryptedBody = WebPushCrypto.EncryptPayload(System.Text.Encoding.UTF8.GetBytes(jsonPayload), subPub, authSecret); + + Assert.NotNull(encryptedBody); + // Header is 86 bytes (16 salt + 4 rs + 1 idlen + 65 pubkey) + ciphertext + 16 tag + Assert.True(encryptedBody.Length > 86 + 16); + + byte[] decryptedBytes = WebPushCrypto.DecryptPayload(encryptedBody, subPub, subPriv, authSecret); + string decrypted = System.Text.Encoding.UTF8.GetString(decryptedBytes); + Assert.Equal(jsonPayload, decrypted); + } } diff --git a/tests/GsDChat.Tests/DatabaseTests.cs b/tests/GsDChat.Tests/DatabaseTests.cs index 997dae3..cdebd4c 100644 --- a/tests/GsDChat.Tests/DatabaseTests.cs +++ b/tests/GsDChat.Tests/DatabaseTests.cs @@ -135,6 +135,8 @@ public class DatabaseTests : IDisposable Assert.True(File.Exists(settingsPath)); Assert.True(options.AllowDmE2ee); Assert.Equal(10, options.MaxGroupChatUsers); + Assert.False(string.IsNullOrWhiteSpace(options.VapidPublicKey)); + Assert.False(string.IsNullOrWhiteSpace(options.VapidPrivateKey)); options.ServerName = "Custom JSON Server"; options.AllowDmE2ee = false; @@ -215,4 +217,108 @@ public class DatabaseTests : IDisposable Assert.Null(await _db.GetFileRecordAsync("file_grp_1")); Assert.False(File.Exists(tempFilePath)); } + + [Fact] + public async Task InboxAndWebPushSubscriptions_DatabaseCrudOperations_ShouldSucceed() + { + var bob = new User { Username = "BobInbox", PasswordHash = "h", PasswordSalt = "s" }; + await _db.CreateUserAsync(bob); + + // 1. Default preferences & channel follow overrides + var prefs = await _db.GetInboxPreferencesAsync(bob.Id); + Assert.True(prefs.MentionsEnabled); + Assert.True(prefs.AnnouncementsEnabled); + Assert.True(prefs.DirectMessagesEnabled); + Assert.True(prefs.FollowedChannelsEnabled); + Assert.True(prefs.PushNotificationsEnabled); + Assert.Empty(prefs.FollowedChannelIds); + Assert.Empty(prefs.MutedChannelIds); + + var channels = await _db.GetChannelsAsync(); + var general = channels.First(c => c.Name == "general"); + var announcements = channels.First(c => c.Name == "announcements"); + + await _db.SetChannelFollowModeAsync(bob.Id, general.Id, ConversationFollowModes.Followed); + await _db.SetChannelFollowModeAsync(bob.Id, announcements.Id, ConversationFollowModes.Muted); + + prefs.MentionsEnabled = false; + await _db.SaveInboxPreferencesAsync(prefs); + + var reloadedPrefs = await _db.GetInboxPreferencesAsync(bob.Id); + Assert.False(reloadedPrefs.MentionsEnabled); + Assert.Contains(general.Id, reloadedPrefs.FollowedChannelIds); + Assert.Contains(announcements.Id, reloadedPrefs.MutedChannelIds); + + // 2. Inbox Items CRUD + var item1 = new InboxItem + { + UserId = bob.Id, + MessageId = "msg_1", + ChannelId = general.Id, + ChannelName = "general", + ChannelType = ChannelTypes.Channel, + SenderId = "u_alice", + SenderUsername = "Alice", + Category = InboxCategories.Mention, + ContentPreview = "Hey @BobInbox!", + IsRead = false, + CreatedAt = DateTime.UtcNow.AddMinutes(-2) + }; + var item2 = new InboxItem + { + UserId = bob.Id, + MessageId = "msg_2", + ChannelId = announcements.Id, + ChannelName = "announcements", + ChannelType = ChannelTypes.Channel, + SenderId = "u_alice", + SenderUsername = "Alice", + Category = InboxCategories.Announcement, + ContentPreview = "Server maintenance tonight", + IsRead = false, + CreatedAt = DateTime.UtcNow + }; + + await _db.CreateInboxItemAsync(item1); + await _db.CreateInboxItemAsync(item2); + + Assert.Equal(2, await _db.GetUnreadInboxCountAsync(bob.Id)); + var items = await _db.GetInboxItemsForUserAsync(bob.Id); + Assert.Equal(2, items.Count); + Assert.Equal(item2.Id, items[0].Id); // Ordered newest first + + // Mark channel read + await _db.MarkChannelInboxItemsReadAsync(bob.Id, general.Id); + Assert.Equal(1, await _db.GetUnreadInboxCountAsync(bob.Id)); + + // Clear read items + await _db.ClearInboxItemsAsync(bob.Id, onlyRead: true); + items = await _db.GetInboxItemsForUserAsync(bob.Id); + Assert.Single(items); + Assert.Equal(item2.Id, items[0].Id); + + // Mark all read & clear all + await _db.MarkAllInboxItemsReadAsync(bob.Id); + Assert.Equal(0, await _db.GetUnreadInboxCountAsync(bob.Id)); + await _db.ClearInboxItemsAsync(bob.Id, onlyRead: false); + Assert.Empty(await _db.GetInboxItemsForUserAsync(bob.Id)); + + // 3. Web Push Subscriptions CRUD + var sub = new PushSubscriptionRecord + { + UserId = bob.Id, + Endpoint = "https://push.example.org/send/sub_1", + P256dh = "p256dh_key_value", + Auth = "auth_secret_value", + UserAgent = "Mozilla/5.0 Test" + }; + await _db.SavePushSubscriptionAsync(sub); + + var subs = await _db.GetPushSubscriptionsForUserAsync(bob.Id); + Assert.Single(subs); + Assert.Equal("https://push.example.org/send/sub_1", subs[0].Endpoint); + + await _db.RemovePushSubscriptionByEndpointAsync("https://push.example.org/send/sub_1"); + Assert.Empty(await _db.GetPushSubscriptionsForUserAsync(bob.Id)); + } } diff --git a/tests/GsDChat.Tests/EndToEndChatTests.cs b/tests/GsDChat.Tests/EndToEndChatTests.cs index caacdc3..508e821 100644 --- a/tests/GsDChat.Tests/EndToEndChatTests.cs +++ b/tests/GsDChat.Tests/EndToEndChatTests.cs @@ -50,6 +50,7 @@ public class EndToEndChatTests : IAsyncLifetime builder.WebHost.UseUrls(_serverUrl); builder.Logging.ClearProviders(); // Keep test output clean + var (vapidPub, vapidPriv) = GsDChat.Core.Security.WebPushCrypto.GenerateVapidKeys(); var serverOptions = new ServerOptions { Host = "127.0.0.1", @@ -58,7 +59,10 @@ public class EndToEndChatTests : IAsyncLifetime DataDirectory = _testDir, ServerName = "E2E Test Server", Motd = "Testing GsDChat E2E", - MaxWebSocketMessageSizeBytes = 1048576 + MaxWebSocketMessageSizeBytes = 1048576, + VapidPublicKey = vapidPub, + VapidPrivateKey = vapidPriv, + VapidSubject = "mailto:test@gsdchat.local" }; builder.Services.AddSingleton(serverOptions); @@ -66,6 +70,7 @@ public class EndToEndChatTests : IAsyncLifetime builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -103,9 +108,52 @@ public class EndToEndChatTests : IAsyncLifetime MaxFileSizeMb = opt.MaxFileSizeMb, AllowMemberChannelCreation = opt.AllowMemberChannelCreation, AllowDmE2ee = opt.AllowDmE2ee, - MaxGroupChatUsers = opt.MaxGroupChatUsers + MaxGroupChatUsers = opt.MaxGroupChatUsers, + VapidPublicKey = opt.VapidPublicKey })); + _app.MapGet("/api/push/vapid-public-key", (ServerOptions opt) => + { + return Results.Ok(new { publicKey = opt.VapidPublicKey }); + }); + + _app.MapPost("/api/push/subscribe", async (PushSubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) => + { + string? token = ExtractToken(httpReq); + var user = await auth.ValidateSessionTokenAsync(token ?? ""); + if (user == null) return Results.Unauthorized(); + + await chatDb.SavePushSubscriptionAsync(new PushSubscriptionRecord + { + UserId = user.Id, + Endpoint = req.Endpoint.Trim(), + P256dh = req.P256dh.Trim(), + Auth = req.Auth.Trim(), + UserAgent = req.UserAgent ?? string.Empty + }); + return Results.Ok(new { success = true }); + }); + + _app.MapPost("/api/push/unsubscribe", async (PushUnsubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) => + { + string? token = ExtractToken(httpReq); + var user = await auth.ValidateSessionTokenAsync(token ?? ""); + if (user == null) return Results.Unauthorized(); + + await chatDb.RemovePushSubscriptionAsync(user.Id, req.Endpoint.Trim()); + return Results.Ok(new { success = true }); + }); + + _app.MapPost("/api/push/test", async (HttpRequest httpReq, IAuthService auth, WebPushService webPush) => + { + string? token = ExtractToken(httpReq); + var user = await auth.ValidateSessionTokenAsync(token ?? ""); + if (user == null) return Results.Unauthorized(); + + bool delivered = await webPush.SendTestPushAsync(user.Id, user.Username); + return Results.Ok(new { success = delivered }); + }); + _app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, CsrfProtectionService csrf, HttpContext context) => { string? csrfToken = context.Request.Headers["X-CSRF-Token"]; @@ -872,5 +920,233 @@ public class EndToEndChatTests : IAsyncLifetime Assert.Contains(charlieGroupMsgs, m => m.Content == "Hello team members!"); Assert.False(stateDave.ChannelMessages.ContainsKey(groupId)); } + + [Fact] + public async Task InboxNotifications_MentionsAnnouncementsFollowedChannelsAndDms_ShouldDeliverAndMarkReadOnJoin() + { + var stateAlice = CreateClientState(); + using var connAlice = new ChatClientConnection(stateAlice); + var regAlice = await connAlice.RegisterAsync("AliceInbox", "Pass123!"); + stateAlice.Token = regAlice.Token!; + stateAlice.CurrentUserId = regAlice.UserId!; + stateAlice.CurrentUsername = regAlice.Username!; + stateAlice.CurrentUserRole = regAlice.Role!; + + var stateBob = CreateClientState(); + using var connBob = new ChatClientConnection(stateBob); + var regBob = await connBob.RegisterAsync("BobInbox", "Pass123!"); + stateBob.Token = regBob.Token!; + stateBob.CurrentUserId = regBob.UserId!; + stateBob.CurrentUsername = regBob.Username!; + stateBob.CurrentUserRole = regBob.Role!; + + await connAlice.StartWebSocketAsync(); + await connBob.StartWebSocketAsync(); + await Task.Delay(300); + + string generalId = stateAlice.Channels.First(c => c.Name == "general").Id; + string announcementsId = stateAlice.Channels.First(c => c.Name == "announcements").Id; + + // 1. Alice mentions @BobInbox in #general -> Bob receives an unread Mention inbox item + await connAlice.SendChatMessageAsync(generalId, "Hello @BobInbox please review the PR!"); + for (int i = 0; i < 20; i++) + { + if (stateBob.UnreadInboxCount >= 1) break; + await Task.Delay(100); + } + + Assert.Equal(1, stateBob.UnreadInboxCount); + var bobItems = stateBob.GetInboxItems(); + Assert.Single(bobItems); + Assert.Equal(InboxCategories.Mention, bobItems[0].Category); + Assert.Contains("Hello @BobInbox", bobItems[0].ContentPreview); + Assert.False(bobItems[0].IsRead); + + // 2. Alice posts in #announcements -> Bob receives an unread Announcement inbox item + await connAlice.SendChatMessageAsync(announcementsId, "Release v2.0 is live!"); + for (int i = 0; i < 20; i++) + { + if (stateBob.UnreadInboxCount >= 2) break; + await Task.Delay(100); + } + + Assert.Equal(2, stateBob.UnreadInboxCount); + bobItems = stateBob.GetInboxItems(); + Assert.Contains(bobItems, x => x.Category == InboxCategories.Announcement && x.ContentPreview.Contains("Release v2.0")); + + // 3. Bob joins #announcements -> auto-marks #announcements inbox items as read! + await connBob.JoinChannelAsync(announcementsId); + for (int i = 0; i < 20; i++) + { + if (stateBob.UnreadInboxCount == 1) break; + await Task.Delay(100); + } + Assert.Equal(1, stateBob.UnreadInboxCount); + + // 4. Bob follows #general -> non-mention messages in #general now create FollowedChannel inbox items for Bob + await connBob.ToggleFollowChannelAsync(generalId, follow: true); + for (int i = 0; i < 20; i++) + { + if (stateBob.IsConversationFollowed(stateBob.Channels.First(c => c.Id == generalId))) break; + await Task.Delay(100); + } + Assert.True(stateBob.IsConversationFollowed(stateBob.Channels.First(c => c.Id == generalId))); + + await connAlice.SendChatMessageAsync(generalId, "Regular update in followed general channel"); + for (int i = 0; i < 20; i++) + { + if (stateBob.UnreadInboxCount >= 2) break; + await Task.Delay(100); + } + + bobItems = stateBob.GetInboxItems(); + Assert.Contains(bobItems, x => x.Category == InboxCategories.FollowedChannel && x.ContentPreview.Contains("Regular update")); + + // 5. Bob marks all read and clears read items + await connBob.SendInboxActionAsync("mark_all_read"); + for (int i = 0; i < 20; i++) + { + if (stateBob.UnreadInboxCount == 0) break; + await Task.Delay(100); + } + Assert.Equal(0, stateBob.UnreadInboxCount); + + await connBob.SendInboxActionAsync("clear_read"); + for (int i = 0; i < 20; i++) + { + if (stateBob.GetInboxItems().Count == 0) break; + await Task.Delay(100); + } + Assert.Empty(stateBob.GetInboxItems()); + } + + [Fact] + public async Task InboxNotifications_WithE2eeDirectMessage_ShouldDecryptInClientInboxAndDeliverEncryptedWebPush() + { + var serverOptions = _app!.Services.GetRequiredService(); + serverOptions.AllowDmE2ee = true; + var db = _app.Services.GetRequiredService(); + + // Spin up a local mock Web Push receiver endpoint to capture the RFC 8291 encrypted push HTTP POST + using var pushListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0); + pushListener.Start(); + int pushPort = ((System.Net.IPEndPoint)pushListener.LocalEndpoint).Port; + pushListener.Stop(); + + byte[]? receivedEncryptedPushBody = null; + string? receivedAuthHeader = null; + string? receivedContentEncoding = null; + + var pushBuilder = WebApplication.CreateBuilder(); + pushBuilder.WebHost.UseUrls($"http://127.0.0.1:{pushPort}"); + pushBuilder.Logging.ClearProviders(); + await using var pushEndpointApp = pushBuilder.Build(); + pushEndpointApp.MapPost("/push-sink", async (HttpContext ctx) => + { + receivedAuthHeader = ctx.Request.Headers["Authorization"].ToString(); + receivedContentEncoding = ctx.Request.Headers["Content-Encoding"].ToString(); + using var ms = new MemoryStream(); + await ctx.Request.Body.CopyToAsync(ms); + receivedEncryptedPushBody = ms.ToArray(); + return Results.StatusCode(201); + }); + await pushEndpointApp.StartAsync(); + + try + { + var stateAlice = CreateClientState(); + using var connAlice = new ChatClientConnection(stateAlice); + var regAlice = await connAlice.RegisterAsync("AlicePushDm", "Pass123!"); + stateAlice.Token = regAlice.Token!; + stateAlice.CurrentUserId = regAlice.UserId!; + stateAlice.CurrentUsername = regAlice.Username!; + + var stateBob = CreateClientState(); + using var connBob = new ChatClientConnection(stateBob); + var regBob = await connBob.RegisterAsync("BobPushDm", "Pass123!"); + stateBob.Token = regBob.Token!; + stateBob.CurrentUserId = regBob.UserId!; + stateBob.CurrentUsername = regBob.Username!; + + await connAlice.StartWebSocketAsync(); + await connBob.StartWebSocketAsync(); + await Task.Delay(250); + + // Register a simulated browser Web Push subscription for Bob + var (subPub, subPriv) = GsDChat.Core.Security.WebPushCrypto.GenerateVapidKeys(); + byte[] authBytes = new byte[16]; + System.Security.Cryptography.RandomNumberGenerator.Fill(authBytes); + string subAuth = GsDChat.Core.Security.WebPushCrypto.Base64UrlEncode(authBytes); + + using var http = new HttpClient { BaseAddress = new Uri(_serverUrl) }; + http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", stateBob.Token); + var subPayload = JsonSerializer.Serialize(new PushSubscribeRequest + { + Endpoint = $"http://127.0.0.1:{pushPort}/push-sink", + P256dh = subPub, + Auth = subAuth, + UserAgent = "Xunit-Push-Test" + }); + var subRes = await http.PostAsync("/api/push/subscribe", new StringContent(subPayload, Encoding.UTF8, "application/json")); + Assert.True(subRes.IsSuccessStatusCode); + + // Start E2EE DM between Alice and Bob + await connAlice.StartDmAsync("BobPushDm"); + for (int i = 0; i < 20; i++) + { + if (stateAlice.DirectMessages.Count > 0 && stateBob.DirectMessages.Count > 0) break; + await Task.Delay(100); + } + string dmId = stateAlice.DirectMessages[0].Id; + + Assert.True((await connAlice.UnlockOrInitializeE2eeWithPinAsync("alice-pin-123")).Success); + Assert.True((await connBob.UnlockOrInitializeE2eeWithPinAsync("bob-pin-456")).Success); + + for (int i = 0; i < 20; i++) + { + if (!string.IsNullOrEmpty(stateAlice.GetPeerPublicKeyForDm(stateAlice.DirectMessages[0]))) break; + await Task.Delay(100); + } + + // Alice sends an E2EE DM to Bob + string secretText = "Secret Inbox & Push DM payload!"; + await connAlice.SendChatMessageAsync(dmId, secretText); + + for (int i = 0; i < 30; i++) + { + if (stateBob.UnreadInboxCount >= 1 && receivedEncryptedPushBody != null) break; + await Task.Delay(100); + } + + // 1. Verify Server DB stored only ciphertext in inbox_items + var dbInboxItems = await db.GetInboxItemsForUserAsync(stateBob.CurrentUserId); + Assert.Single(dbInboxItems); + Assert.True(dbInboxItems[0].IsEncrypted); + Assert.StartsWith("E2EE:v1:", dbInboxItems[0].ContentPreview); + Assert.DoesNotContain("Secret Inbox", dbInboxItems[0].ContentPreview); + + // 2. Verify Bob's client decrypted the Inbox item preview automatically using his unlocked E2EE key vault + var bobClientInbox = stateBob.GetInboxItems(); + Assert.Single(bobClientInbox); + Assert.Equal(InboxCategories.DirectMessage, bobClientInbox[0].Category); + Assert.Equal(secretText, bobClientInbox[0].ContentPreview); + + // 3. Verify WebPushService sent an RFC 8292 VAPID + RFC 8291 aes128gcm Push Notification to Bob's subscription + Assert.NotNull(receivedEncryptedPushBody); + Assert.Equal("aes128gcm", receivedContentEncoding); + Assert.NotNull(receivedAuthHeader); + Assert.StartsWith("vapid t=", receivedAuthHeader); + + // Decrypt the Web Push payload as the browser would, and verify E2EE privacy is preserved in OS push banner + byte[] pushJsonBytes = GsDChat.Core.Security.WebPushCrypto.DecryptPayload(receivedEncryptedPushBody!, subPub, subPriv, subAuth); + string pushJson = Encoding.UTF8.GetString(pushJsonBytes); + Assert.Contains("New encrypted message from @AlicePushDm", pushJson); + Assert.DoesNotContain("Secret Inbox", pushJson); + } + finally + { + await pushEndpointApp.StopAsync(); + } + } } diff --git a/tests/GsDChat.Tests/NetworkProtocolTests.cs b/tests/GsDChat.Tests/NetworkProtocolTests.cs index 3255da0..ebfdc16 100644 --- a/tests/GsDChat.Tests/NetworkProtocolTests.cs +++ b/tests/GsDChat.Tests/NetworkProtocolTests.cs @@ -32,12 +32,32 @@ public class NetworkProtocolTests Assert.Equal("TestServer", sync.ServerName); Assert.Equal("Welcome MOTD", sync.Motd); Assert.NotNull(sync.Screens); - Assert.Equal(4, sync.Screens.Count); + Assert.Equal(5, sync.Screens.Count); Assert.Contains(sync.Screens, s => s.ScreenId == "F1_Chat"); Assert.Contains(sync.Screens, s => s.ScreenId == "F2_Channels"); Assert.Contains(sync.Screens, s => s.ScreenId == "F3_Users"); Assert.Contains(sync.Screens, s => s.ScreenId == "F4_Files"); + Assert.Contains(sync.Screens, s => s.ScreenId == "F5_Inbox"); + } + + [Fact] + public void NetworkEnvelope_ShouldPackAndUnpackInboxPackets() + { + var actionPacket = new InboxActionPacket + { + Action = "mark_read", + ItemId = "item_123", + ChannelId = "ch_general" + }; + + var env = NetworkEnvelope.Create(MessageTypes.InboxAction, actionPacket); + var unpacked = env.Unpack(); + + Assert.NotNull(unpacked); + Assert.Equal("mark_read", unpacked.Action); + Assert.Equal("item_123", unpacked.ItemId); + Assert.Equal("ch_general", unpacked.ChannelId); } [Fact] diff --git a/tests/GsDChat.Tests/WebClientStaticTests.cs b/tests/GsDChat.Tests/WebClientStaticTests.cs index b151170..4f9d65f 100644 --- a/tests/GsDChat.Tests/WebClientStaticTests.cs +++ b/tests/GsDChat.Tests/WebClientStaticTests.cs @@ -105,6 +105,10 @@ public class WebClientStaticTests : IAsyncLifetime Assert.Contains("id=\"dmList\"", html); Assert.Contains("id=\"createGroupCard\"", html); Assert.Contains("id=\"startDmCard\"", html); + Assert.Contains("id=\"view-inbox\"", html); + Assert.Contains("id=\"navTabInbox\"", html); + Assert.Contains("id=\"inboxUnreadBadge\"", html); + Assert.Contains("id=\"toggleWebPushBtn\"", html); } [Fact] @@ -119,6 +123,8 @@ public class WebClientStaticTests : IAsyncLifetime Assert.Contains("--bg-main", css); Assert.Contains(".app-layout", css); Assert.Contains(".conv-security-badge", css); + Assert.Contains(".inbox-item", css); + Assert.Contains(".inbox-badge", css); } [Fact] @@ -137,5 +143,25 @@ public class WebClientStaticTests : IAsyncLifetime Assert.Contains("unlockOrInitE2eeWithPin", js); Assert.Contains("FETCH_HISTORY", js); Assert.Contains("TOGGLE_E2EE", js); + Assert.Contains("INBOX_SYNC", js); + Assert.Contains("INBOX_NEW_ITEM", js); + Assert.Contains("subscribeWebPush", js); + } + + [Fact] + public async Task GetServiceWorkerAndManifest_ShouldServeWebPushAssets() + { + Assert.NotNull(_httpClient); + + var swRes = await _httpClient.GetAsync("/sw.js"); + Assert.True(swRes.IsSuccessStatusCode); + string swJs = await swRes.Content.ReadAsStringAsync(); + Assert.Contains("showNotification", swJs); + Assert.Contains("notificationclick", swJs); + + var manifestRes = await _httpClient.GetAsync("/manifest.json"); + Assert.True(manifestRes.IsSuccessStatusCode); + string manifestJson = await manifestRes.Content.ReadAsStringAsync(); + Assert.Contains("GsDChat", manifestJson); } }