Add persistent Inbox and RFC 8291/8292 Web Push notification system
This commit is contained in:
parent
4714d25724
commit
7cc9ba7f4d
27 changed files with 3573 additions and 17 deletions
|
|
@ -326,6 +326,13 @@ public class ChatClientConnection : IDisposable
|
||||||
DecryptMessageIfNeeded(msg);
|
DecryptMessageIfNeeded(msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
foreach (var item in _state.GetInboxItems())
|
||||||
|
{
|
||||||
|
if (E2eeCrypto.IsEncryptedPayload(item.ContentPreview))
|
||||||
|
{
|
||||||
|
DecryptInboxItemIfNeeded(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
_state.NeedsRedraw = true;
|
_state.NeedsRedraw = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -462,6 +469,28 @@ public class ChatClientConnection : IDisposable
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.InboxSync:
|
||||||
|
var inSync = envelope.Unpack<InboxSyncPacket>();
|
||||||
|
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<InboxNewItemPacket>();
|
||||||
|
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:
|
case MessageTypes.SystemNotice:
|
||||||
var notice = envelope.Unpack<SystemNoticePacket>();
|
var notice = envelope.Unpack<SystemNoticePacket>();
|
||||||
if (notice != null)
|
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)
|
public async Task SendEnvelopeAsync(NetworkEnvelope envelope)
|
||||||
{
|
{
|
||||||
if (_webSocket == null || _webSocket.State != WebSocketState.Open) return;
|
if (_webSocket == null || _webSocket.State != WebSocketState.Open) return;
|
||||||
|
|
@ -753,6 +819,39 @@ public class ChatClientConnection : IDisposable
|
||||||
return SendEnvelopeAsync(envelope);
|
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<bool> UploadFileAsync(string localFilePath, string channelId)
|
public async Task<bool> UploadFileAsync(string localFilePath, string channelId)
|
||||||
{
|
{
|
||||||
if (!File.Exists(localFilePath))
|
if (!File.Exists(localFilePath))
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ public class ConsoleUi
|
||||||
RegisterScreen(new ChannelsScreen(state, connection));
|
RegisterScreen(new ChannelsScreen(state, connection));
|
||||||
RegisterScreen(new UsersScreen(state, connection));
|
RegisterScreen(new UsersScreen(state, connection));
|
||||||
RegisterScreen(new FilesScreen(state, connection));
|
RegisterScreen(new FilesScreen(state, connection));
|
||||||
|
RegisterScreen(new InboxScreen(state, connection));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void RegisterScreen(IScreen screen)
|
public void RegisterScreen(IScreen screen)
|
||||||
|
|
@ -117,9 +118,15 @@ public class ConsoleUi
|
||||||
if (_state.ActiveScreenId != "F4_Files") { _state.ActiveScreenId = "F4_Files"; Console.Clear(); }
|
if (_state.ActiveScreenId != "F4_Files") { _state.ActiveScreenId = "F4_Files"; Console.Clear(); }
|
||||||
_state.NeedsRedraw = true;
|
_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;
|
_state.NeedsRedraw = true;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
|
@ -227,13 +234,23 @@ public class ConsoleUi
|
||||||
foreach (var screen in _screens.Values)
|
foreach (var screen in _screens.Values)
|
||||||
{
|
{
|
||||||
bool isActive = screen.ScreenId == _state.ActiveScreenId;
|
bool isActive = screen.ScreenId == _state.ActiveScreenId;
|
||||||
|
string titleLabel = screen.Title;
|
||||||
|
if (screen.ScreenId == "F5_Inbox" && _state.UnreadInboxCount > 0)
|
||||||
|
{
|
||||||
|
titleLabel = $"Inbox ({_state.UnreadInboxCount})";
|
||||||
|
}
|
||||||
|
|
||||||
if (isActive)
|
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
|
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
|
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}");
|
sb.AppendLine($" {status}");
|
||||||
|
|
|
||||||
|
|
@ -122,7 +122,7 @@ public class ChannelsScreen : IScreen
|
||||||
sb.AppendLine($" {Ansi.BrightCyan}Invite to Group > Username:{Ansi.Reset} {_inputBuffer}█");
|
sb.AppendLine($" {Ansi.BrightCyan}Invite to Group > Username:{Ansi.Reset} {_inputBuffer}█");
|
||||||
break;
|
break;
|
||||||
default:
|
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;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -130,17 +130,22 @@ public class ChannelsScreen : IScreen
|
||||||
private void RenderItem(StringBuilder sb, Channel ch, bool isSelected, string label, string subtitle)
|
private void RenderItem(StringBuilder sb, Channel ch, bool isSelected, string label, string subtitle)
|
||||||
{
|
{
|
||||||
bool isActive = ch.Id == _state.ActiveChannelId;
|
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 prefix = isSelected ? $"{Ansi.BrightYellow}► " : " ";
|
||||||
string activeTag = isActive ? $" {Ansi.BrightGreen}[ACTIVE]{Ansi.Reset}" : "";
|
string activeTag = isActive ? $" {Ansi.BrightGreen}[ACTIVE]{Ansi.Reset}" : "";
|
||||||
string sub = string.IsNullOrEmpty(subtitle) ? "" : $" {Ansi.Gray}- {subtitle}{Ansi.Reset}";
|
string sub = string.IsNullOrEmpty(subtitle) ? "" : $" {Ansi.Gray}- {subtitle}{Ansi.Reset}";
|
||||||
|
|
||||||
if (isSelected)
|
if (isSelected)
|
||||||
{
|
{
|
||||||
sb.AppendLine($"{prefix}{Ansi.Inverse}{label}{Ansi.Reset}{activeTag}{sub}");
|
sb.AppendLine($"{prefix}{Ansi.Inverse}{label}{Ansi.Reset}{activeTag}{followTag}{sub}");
|
||||||
}
|
}
|
||||||
else
|
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.SetStatus($"Toggled account-wide E2EE to {(!_state.AccountE2eeEnabled ? "ON" : "OFF")}.");
|
||||||
_state.NeedsRedraw = true;
|
_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)
|
else if (key.Key == ConsoleKey.L || key.Key == ConsoleKey.D)
|
||||||
{
|
{
|
||||||
if (_selectedIndex >= 0 && _selectedIndex < all.Count)
|
if (_selectedIndex >= 0 && _selectedIndex < all.Count)
|
||||||
|
|
|
||||||
|
|
@ -429,6 +429,25 @@ public class ChatScreen : IScreen
|
||||||
await _connection.LeaveGroupAsync(_state.ActiveChannelId);
|
await _connection.LeaveGroupAsync(_state.ActiveChannelId);
|
||||||
break;
|
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":
|
case "upload":
|
||||||
if (string.IsNullOrEmpty(args))
|
if (string.IsNullOrEmpty(args))
|
||||||
{
|
{
|
||||||
|
|
|
||||||
208
src/GsDChat.Client/Screens/InboxScreen.cs
Normal file
208
src/GsDChat.Client/Screens/InboxScreen.cs
Normal file
|
|
@ -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")}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -45,6 +45,9 @@ public class ClientState
|
||||||
public HashSet<string> LoadingHistoryChannels { get; } = new(StringComparer.OrdinalIgnoreCase);
|
public HashSet<string> LoadingHistoryChannels { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||||
public List<UserSummary> Users { get; } = new();
|
public List<UserSummary> Users { get; } = new();
|
||||||
public List<FileSummary> Files { get; } = new();
|
public List<FileSummary> Files { get; } = new();
|
||||||
|
public List<InboxItem> InboxItems { get; } = new();
|
||||||
|
public int UnreadInboxCount { get; set; } = 0;
|
||||||
|
public InboxPreferences InboxPreferences { get; set; } = new();
|
||||||
public List<string> SystemNotices { get; } = new();
|
public List<string> SystemNotices { get; } = new();
|
||||||
|
|
||||||
public int ChatScrollOffset { get; set; } = 0;
|
public int ChatScrollOffset { get; set; } = 0;
|
||||||
|
|
@ -440,4 +443,57 @@ public class ClientState
|
||||||
NeedsRedraw = true;
|
NeedsRedraw = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void SetInboxSync(List<InboxItem> 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<InboxItem> GetInboxItems()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return new List<InboxItem>(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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
63
src/GsDChat.Core/Models/InboxModels.cs
Normal file
63
src/GsDChat.Core/Models/InboxModels.cs
Normal file
|
|
@ -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<string> FollowedChannelIds { get; set; } = new();
|
||||||
|
public List<string> 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;
|
||||||
|
}
|
||||||
|
|
@ -45,6 +45,20 @@ public class ServerInfoResponse
|
||||||
public bool AllowMemberChannelCreation { get; set; } = true;
|
public bool AllowMemberChannelCreation { get; set; } = true;
|
||||||
public bool AllowDmE2ee { get; set; } = true;
|
public bool AllowDmE2ee { get; set; } = true;
|
||||||
public int MaxGroupChatUsers { get; set; } = 10;
|
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
|
public class UploadFileResponse
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,11 @@ public static class MessageTypes
|
||||||
public const string Error = "ERROR";
|
public const string Error = "ERROR";
|
||||||
public const string ExecuteCommand = "EXECUTE_COMMAND";
|
public const string ExecuteCommand = "EXECUTE_COMMAND";
|
||||||
public const string CommandResult = "COMMAND_RESULT";
|
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 Ping = "PING";
|
||||||
public const string Pong = "PONG";
|
public const string Pong = "PONG";
|
||||||
}
|
}
|
||||||
|
|
@ -232,3 +237,38 @@ public class CommandResultPacket
|
||||||
public string Output { get; set; } = string.Empty;
|
public string Output { get; set; } = string.Empty;
|
||||||
public string ChannelId { get; set; } = string.Empty;
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class InboxSyncPacket
|
||||||
|
{
|
||||||
|
public List<InboxItem> 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; }
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -109,6 +109,19 @@ public class ServerUiSync
|
||||||
new() { Name = "FileList", Position = "Center", ShowBorder = true, BorderTitle = "Available Files" },
|
new() { Name = "FileList", Position = "Center", ShowBorder = true, BorderTitle = "Available Files" },
|
||||||
new() { Name = "Actions", Position = "Bottom", Height = 3, ShowBorder = true, BorderTitle = "Transfer Commands" }
|
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<PanelDefinition>
|
||||||
|
{
|
||||||
|
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" }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
||||||
323
src/GsDChat.Core/Security/WebPushCrypto.cs
Normal file
323
src/GsDChat.Core/Security/WebPushCrypto.cs
Normal file
|
|
@ -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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Encrypts a Web Push payload using RFC 8291 (aes128gcm content encoding).
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decrypts an RFC 8291 aes128gcm Web Push payload (used for verification and testing).
|
||||||
|
/// </summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -17,6 +17,11 @@ public class ServerOptions
|
||||||
public bool AllowDmE2ee { get; set; } = true;
|
public bool AllowDmE2ee { get; set; } = true;
|
||||||
public int MaxGroupChatUsers { get; set; } = 10;
|
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
|
// Security Settings
|
||||||
public int RateLimitRequestsPerMinute { get; set; } = 60;
|
public int RateLimitRequestsPerMinute { get; set; } = 60;
|
||||||
public int MaxConnectionsPerIp { get; set; } = 10;
|
public int MaxConnectionsPerIp { get; set; } = 10;
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using GsDChat.Core.Security;
|
||||||
|
|
||||||
namespace GsDChat.Server.Configuration;
|
namespace GsDChat.Server.Configuration;
|
||||||
|
|
||||||
|
|
@ -87,6 +88,13 @@ public class ServerSettingsManager
|
||||||
options.MaxGroupChatUsers = 2;
|
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);
|
Save(options);
|
||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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
|
// Seed default channels if none exist
|
||||||
var channelsCountCmd = conn.CreateCommand();
|
var channelsCountCmd = conn.CreateCommand();
|
||||||
channelsCountCmd.CommandText = "SELECT COUNT(*) FROM channels WHERE type = 'Channel';";
|
channelsCountCmd.CommandText = "SELECT COUNT(*) FROM channels WHERE type = 'Channel';";
|
||||||
|
|
@ -642,6 +708,8 @@ public class ChatDatabase : IDisposable
|
||||||
|
|
||||||
using var cleanupCmd = conn.CreateCommand();
|
using var cleanupCmd = conn.CreateCommand();
|
||||||
cleanupCmd.CommandText = """
|
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 files WHERE channel_id = @id;
|
||||||
DELETE FROM messages WHERE channel_id = @id;
|
DELETE FROM messages WHERE channel_id = @id;
|
||||||
DELETE FROM channel_members WHERE channel_id = @id;
|
DELETE FROM channel_members WHERE channel_id = @id;
|
||||||
|
|
@ -1265,6 +1333,365 @@ public class ChatDatabase : IDisposable
|
||||||
|
|
||||||
#endregion
|
#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<List<InboxItem>> GetInboxItemsForUserAsync(string userId, int limit = 100)
|
||||||
|
{
|
||||||
|
var items = new List<InboxItem>();
|
||||||
|
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<int> 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<bool> 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<int> 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<int> 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<bool> 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<int> 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<InboxPreferences> 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<bool> 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<bool> 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<bool> 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<List<PushSubscriptionRecord>> GetPushSubscriptionsForUserAsync(string userId)
|
||||||
|
{
|
||||||
|
var subs = new List<PushSubscriptionRecord>();
|
||||||
|
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()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
// SQLite in-process connections are pooled and closed as needed
|
// SQLite in-process connections are pooled and closed as needed
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
using GsDChat.Core.Protocol;
|
using GsDChat.Core.Protocol;
|
||||||
using GsDChat.Server.Configuration;
|
using GsDChat.Server.Configuration;
|
||||||
using GsDChat.Server.Data;
|
using GsDChat.Server.Data;
|
||||||
|
|
@ -112,6 +113,7 @@ builder.WebHost.ConfigureKestrel(kestrel =>
|
||||||
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
|
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
|
||||||
builder.Services.AddSingleton<IAuthService, AuthService>();
|
builder.Services.AddSingleton<IAuthService, AuthService>();
|
||||||
builder.Services.AddSingleton<FileStorageService>();
|
builder.Services.AddSingleton<FileStorageService>();
|
||||||
|
builder.Services.AddSingleton<WebPushService>();
|
||||||
builder.Services.AddSingleton<ChatWebSocketManager>();
|
builder.Services.AddSingleton<ChatWebSocketManager>();
|
||||||
builder.Services.AddSingleton<ModLoaderService>();
|
builder.Services.AddSingleton<ModLoaderService>();
|
||||||
builder.Services.AddSingleton<RateLimitService>();
|
builder.Services.AddSingleton<RateLimitService>();
|
||||||
|
|
@ -148,6 +150,8 @@ app.Use(async (context, next) =>
|
||||||
context.Response.Headers.Append("Content-Security-Policy",
|
context.Response.Headers.Append("Content-Security-Policy",
|
||||||
"default-src 'self'; " +
|
"default-src 'self'; " +
|
||||||
"script-src 'self' 'unsafe-inline'; " +
|
"script-src 'self' 'unsafe-inline'; " +
|
||||||
|
"worker-src 'self'; " +
|
||||||
|
"manifest-src 'self'; " +
|
||||||
"style-src 'self' 'unsafe-inline'; " +
|
"style-src 'self' 'unsafe-inline'; " +
|
||||||
"img-src 'self' data:; " +
|
"img-src 'self' data:; " +
|
||||||
"font-src 'self'; " +
|
"font-src 'self'; " +
|
||||||
|
|
@ -213,10 +217,74 @@ app.MapGet("/api/info", (ServerOptions opt, IAuthService auth, HttpRequest req)
|
||||||
MaxFileSizeMb = opt.MaxFileSizeMb,
|
MaxFileSizeMb = opt.MaxFileSizeMb,
|
||||||
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
|
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
|
||||||
AllowDmE2ee = opt.AllowDmE2ee,
|
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) =>
|
app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, RateLimitService rateLimiter, CsrfProtectionService csrf, HttpContext context) =>
|
||||||
{
|
{
|
||||||
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||||
|
|
|
||||||
209
src/GsDChat.Server/Services/WebPushService.cs
Normal file
209
src/GsDChat.Server/Services/WebPushService.cs
Normal file
|
|
@ -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<WebPushService> _logger;
|
||||||
|
private readonly HttpClient _httpClient;
|
||||||
|
|
||||||
|
public WebPushService(
|
||||||
|
ChatDatabase db,
|
||||||
|
ServerOptions options,
|
||||||
|
ILogger<WebPushService> 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<Task>(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<bool> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -5,6 +5,7 @@ using System.Linq;
|
||||||
using System.Net.WebSockets;
|
using System.Net.WebSockets;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
@ -23,17 +24,23 @@ public class ChatWebSocketManager
|
||||||
private readonly ChatDatabase _db;
|
private readonly ChatDatabase _db;
|
||||||
private readonly ServerOptions _options;
|
private readonly ServerOptions _options;
|
||||||
private readonly ILogger<ChatWebSocketManager> _logger;
|
private readonly ILogger<ChatWebSocketManager> _logger;
|
||||||
|
private readonly WebPushService? _webPush;
|
||||||
|
|
||||||
// Extensibility hooks for mod system
|
// Extensibility hooks for mod system
|
||||||
public Func<ChatMessage, Task<ChatMessage?>>? MessagePipelineInterceptor { get; set; }
|
public Func<ChatMessage, Task<ChatMessage?>>? MessagePipelineInterceptor { get; set; }
|
||||||
public Func<string, string, ConnectedClient, Task<CommandResultPacket?>>? CommandInterceptor { get; set; }
|
public Func<string, string, ConnectedClient, Task<CommandResultPacket?>>? CommandInterceptor { get; set; }
|
||||||
public Func<ServerUiSync>? UiSyncProvider { get; set; }
|
public Func<ServerUiSync>? UiSyncProvider { get; set; }
|
||||||
|
|
||||||
public ChatWebSocketManager(ChatDatabase db, ServerOptions options, ILogger<ChatWebSocketManager> logger)
|
public ChatWebSocketManager(
|
||||||
|
ChatDatabase db,
|
||||||
|
ServerOptions options,
|
||||||
|
ILogger<ChatWebSocketManager> logger,
|
||||||
|
WebPushService? webPush = null)
|
||||||
{
|
{
|
||||||
_db = db;
|
_db = db;
|
||||||
_options = options;
|
_options = options;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
_webPush = webPush;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int ConnectedCount => _clients.Count;
|
public int ConnectedCount => _clients.Count;
|
||||||
|
|
@ -92,6 +99,9 @@ public class ChatWebSocketManager
|
||||||
// Send Files List (filtered for user access)
|
// Send Files List (filtered for user access)
|
||||||
await SendFileListToClientAsync(client, cancellationToken);
|
await SendFileListToClientAsync(client, cancellationToken);
|
||||||
|
|
||||||
|
// Send Initial Inbox & Preferences Sync
|
||||||
|
await SendInboxSyncToClientAsync(client, cancellationToken);
|
||||||
|
|
||||||
// Send Initial User List
|
// Send Initial User List
|
||||||
var initialUsers = await _db.GetAllUsersAsync();
|
var initialUsers = await _db.GetAllUsersAsync();
|
||||||
var onlineIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id), StringComparer.OrdinalIgnoreCase);
|
var onlineIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id), StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
@ -280,6 +290,34 @@ public class ChatWebSocketManager
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.InboxSync:
|
||||||
|
await SendInboxSyncToClientAsync(client, ct);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.InboxAction:
|
||||||
|
var inboxAct = envelope.Unpack<InboxActionPacket>();
|
||||||
|
if (inboxAct != null)
|
||||||
|
{
|
||||||
|
await HandleInboxActionAsync(client, inboxAct, ct);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.UpdateInboxPreferences:
|
||||||
|
var prefsPkg = envelope.Unpack<UpdateInboxPreferencesPacket>();
|
||||||
|
if (prefsPkg != null)
|
||||||
|
{
|
||||||
|
await HandleUpdateInboxPreferencesAsync(client, prefsPkg, ct);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.ToggleFollowChannel:
|
||||||
|
var followPkg = envelope.Unpack<ToggleFollowChannelPacket>();
|
||||||
|
if (followPkg != null)
|
||||||
|
{
|
||||||
|
await HandleToggleFollowChannelAsync(client, followPkg, ct);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
case MessageTypes.UserListSync:
|
case MessageTypes.UserListSync:
|
||||||
case "GET_USERS":
|
case "GET_USERS":
|
||||||
await BroadcastUserListAsync();
|
await BroadcastUserListAsync();
|
||||||
|
|
@ -515,6 +553,13 @@ public class ChatWebSocketManager
|
||||||
|
|
||||||
await _db.SaveMessageAsync(message);
|
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)
|
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
||||||
{
|
{
|
||||||
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
|
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 BroadcastToChannelAsync(channelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await ProcessMessageInboxNotificationsAsync(channel, message, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task HandleJoinChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
|
private async Task HandleJoinChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
|
||||||
|
|
@ -546,6 +593,12 @@ public class ChatWebSocketManager
|
||||||
|
|
||||||
client.ActiveChannelId = channelId;
|
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 SendChannelListToClientAsync(client, ct);
|
||||||
await SendHistoryPageAsync(client, channelId, offset: 0, limit: 50, prepend: false, 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).",
|
Text = $"Group chat '{InputSanitizer.SanitizeChannelName(group.Name)}' created by @{InputSanitizer.SanitizeUsername(client.User.Username)} ({group.MemberIds.Count}/{group.MaxUsers} members).",
|
||||||
Level = "Success"
|
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)
|
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)}.",
|
Text = $"@{InputSanitizer.SanitizeUsername(targetUser.Username)} was added to group '{InputSanitizer.SanitizeChannelName(group.Name)}' by @{InputSanitizer.SanitizeUsername(client.User.Username)}.",
|
||||||
Level = "Info"
|
Level = "Info"
|
||||||
});
|
});
|
||||||
|
|
||||||
|
await CreateGroupInviteInboxItemAsync(updatedGroup ?? group, client.User, targetUser.Id, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task HandleLeaveGroupAsync(ConnectedClient client, LeaveGroupPacket packet, CancellationToken ct)
|
private async Task HandleLeaveGroupAsync(ConnectedClient client, LeaveGroupPacket packet, CancellationToken ct)
|
||||||
|
|
@ -854,6 +915,10 @@ public class ChatWebSocketManager
|
||||||
if (modResult != null)
|
if (modResult != null)
|
||||||
{
|
{
|
||||||
await client.SendMessageAsync(MessageTypes.CommandResult, modResult, ct);
|
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;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -877,11 +942,140 @@ public class ChatWebSocketManager
|
||||||
$" /group create <name> [users] - Create a group chat (max {_options.MaxGroupChatUsers} users)\n" +
|
$" /group create <name> [users] - Create a group chat (max {_options.MaxGroupChatUsers} users)\n" +
|
||||||
" /group invite <username> - Invite a user to the active group chat\n" +
|
" /group invite <username> - Invite a user to the active group chat\n" +
|
||||||
" /group leave - Leave 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 <message> - Broadcast an official announcement (Admin/Owner)\n" +
|
||||||
" /users - List all registered users\n" +
|
" /users - List all registered users\n" +
|
||||||
" /motd - Display message of the day";
|
" /motd - Display message of the day";
|
||||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText, ChannelId = packet.ChannelId }, ct);
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText, ChannelId = packet.ChannelId }, ct);
|
||||||
break;
|
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 <announcement_message>",
|
||||||
|
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 <mentions|announcements|dms|channels|push> <on|off>",
|
||||||
|
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":
|
case "motd":
|
||||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}", ChannelId = packet.ChannelId }, ct);
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}", ChannelId = packet.ChannelId }, ct);
|
||||||
break;
|
break;
|
||||||
|
|
@ -1126,5 +1320,349 @@ public class ChatWebSocketManager
|
||||||
{
|
{
|
||||||
await BroadcastToChannelAsync(file.ChannelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = msg });
|
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<UserSummary> 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
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -704,7 +704,8 @@ html, body {
|
||||||
|
|
||||||
.channel-list,
|
.channel-list,
|
||||||
.user-list,
|
.user-list,
|
||||||
.files-list {
|
.files-list,
|
||||||
|
.inbox-list {
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|
@ -714,10 +715,139 @@ html, body {
|
||||||
}
|
}
|
||||||
|
|
||||||
.user-list,
|
.user-list,
|
||||||
.files-list {
|
.files-list,
|
||||||
|
.inbox-list {
|
||||||
flex: 1;
|
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,
|
.channel-item,
|
||||||
.user-item,
|
.user-item,
|
||||||
.file-item {
|
.file-item {
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,20 @@
|
||||||
e2eePromptedDms: {}, // dmChannelId -> bool (prevent repeated intrusive prompts after dismiss)
|
e2eePromptedDms: {}, // dmChannelId -> bool (prevent repeated intrusive prompts after dismiss)
|
||||||
users: [],
|
users: [],
|
||||||
files: [],
|
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,
|
socket: null,
|
||||||
isRegister: false,
|
isRegister: false,
|
||||||
reconnectTimer: null
|
reconnectTimer: null
|
||||||
|
|
@ -31,6 +45,8 @@
|
||||||
serverTitle: document.getElementById('serverTitle'),
|
serverTitle: document.getElementById('serverTitle'),
|
||||||
connIndicator: document.getElementById('connIndicator'),
|
connIndicator: document.getElementById('connIndicator'),
|
||||||
navTabs: document.querySelectorAll('.nav-tab'),
|
navTabs: document.querySelectorAll('.nav-tab'),
|
||||||
|
navTabInbox: document.getElementById('navTabInbox'),
|
||||||
|
inboxUnreadBadge: document.getElementById('inboxUnreadBadge'),
|
||||||
tabViews: document.querySelectorAll('.tab-view'),
|
tabViews: document.querySelectorAll('.tab-view'),
|
||||||
currentUsername: document.getElementById('currentUsername'),
|
currentUsername: document.getElementById('currentUsername'),
|
||||||
currentUserRole: document.getElementById('currentUserRole'),
|
currentUserRole: document.getElementById('currentUserRole'),
|
||||||
|
|
@ -43,6 +59,7 @@
|
||||||
channelSelectDropdown: document.getElementById('channelSelectDropdown'),
|
channelSelectDropdown: document.getElementById('channelSelectDropdown'),
|
||||||
chatSecurityBadge: document.getElementById('chatSecurityBadge'),
|
chatSecurityBadge: document.getElementById('chatSecurityBadge'),
|
||||||
activeChannelTopic: document.getElementById('activeChannelTopic'),
|
activeChannelTopic: document.getElementById('activeChannelTopic'),
|
||||||
|
toggleFollowBtn: document.getElementById('toggleFollowBtn'),
|
||||||
toggleDmE2eeBtn: document.getElementById('toggleDmE2eeBtn'),
|
toggleDmE2eeBtn: document.getElementById('toggleDmE2eeBtn'),
|
||||||
inviteGroupBtn: document.getElementById('inviteGroupBtn'),
|
inviteGroupBtn: document.getElementById('inviteGroupBtn'),
|
||||||
leaveGroupBtn: document.getElementById('leaveGroupBtn'),
|
leaveGroupBtn: document.getElementById('leaveGroupBtn'),
|
||||||
|
|
@ -93,6 +110,19 @@
|
||||||
filesList: document.getElementById('filesList'),
|
filesList: document.getElementById('filesList'),
|
||||||
filesViewUploadInput: document.getElementById('filesViewUploadInput'),
|
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
|
// E2EE Vault Modal
|
||||||
e2eeModal: document.getElementById('e2eeModal'),
|
e2eeModal: document.getElementById('e2eeModal'),
|
||||||
e2eeModalTitle: document.getElementById('e2eeModalTitle'),
|
e2eeModalTitle: document.getElementById('e2eeModalTitle'),
|
||||||
|
|
@ -466,6 +496,53 @@
|
||||||
return msg;
|
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() {
|
async function reDecryptAllLoadedMessages() {
|
||||||
for (const chId of Object.keys(state.messages)) {
|
for (const chId of Object.keys(state.messages)) {
|
||||||
const list = state.messages[chId] || [];
|
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) {
|
if (state.activeChannelId) {
|
||||||
renderMessages();
|
renderMessages();
|
||||||
}
|
}
|
||||||
|
renderInbox();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function unlockOrInitE2eeWithPin(pin, resetKeys = false) {
|
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
|
// Initialization
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|
@ -553,6 +846,7 @@
|
||||||
initElements();
|
initElements();
|
||||||
setupEventListeners();
|
setupEventListeners();
|
||||||
await fetchServerInfo();
|
await fetchServerInfo();
|
||||||
|
await initServiceWorkerAndPush();
|
||||||
|
|
||||||
if (state.token && state.user) {
|
if (state.token && state.user) {
|
||||||
loadCachedKeysForCurrentUser();
|
loadCachedKeysForCurrentUser();
|
||||||
|
|
@ -581,6 +875,9 @@
|
||||||
? state.serverInfo.allowDmE2ee
|
? state.serverInfo.allowDmE2ee
|
||||||
: (state.serverInfo.AllowDmE2ee !== undefined ? state.serverInfo.AllowDmE2ee : true);
|
: (state.serverInfo.AllowDmE2ee !== undefined ? state.serverInfo.AllowDmE2ee : true);
|
||||||
state.maxGroupChatUsers = state.serverInfo.maxGroupChatUsers || state.serverInfo.MaxGroupChatUsers || 10;
|
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.serverTitle.textContent = state.serverInfo.serverName || 'GsDChat';
|
||||||
el.modalServerName.textContent = state.serverInfo.serverName || 'GsDChat';
|
el.modalServerName.textContent = state.serverInfo.serverName || 'GsDChat';
|
||||||
|
|
@ -839,6 +1136,23 @@
|
||||||
const first = state.channels[0];
|
const first = state.channels[0];
|
||||||
state.activeChannelId = first.id || first.Id;
|
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();
|
renderChannels();
|
||||||
updateActiveChannelHeader();
|
updateActiveChannelHeader();
|
||||||
checkLazyDmE2eePrompt();
|
checkLazyDmE2eePrompt();
|
||||||
|
|
@ -909,6 +1223,82 @@
|
||||||
renderFiles();
|
renderFiles();
|
||||||
break;
|
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':
|
case 'SYSTEM_NOTICE':
|
||||||
const noticeText = payload.text || payload.Text;
|
const noticeText = payload.text || payload.Text;
|
||||||
if (noticeText) {
|
if (noticeText) {
|
||||||
|
|
@ -953,6 +1343,200 @@
|
||||||
return conv.type || conv.Type || 'Channel';
|
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 = '<div style="color:var(--text-muted); text-align:center; padding:24px;">Inbox is empty! Mentions (@username, @everyone, @here), #announcements, DMs, and followed channel messages will appear here.</div>';
|
||||||
|
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 = `
|
||||||
|
<div class="inbox-item-main">
|
||||||
|
<div class="inbox-item-top">
|
||||||
|
${isRead ? '' : '<span class="inbox-unread-dot" title="Unread">●</span>'}
|
||||||
|
<span class="inbox-category-badge cat-${escapeHtml(catCss)}">[${catLabel}]</span>
|
||||||
|
<span style="font-weight:700; color:var(--ctp-sapphire);">${escapeHtml(convDisplay)}</span>
|
||||||
|
<span style="color:var(--ctp-subtext0);">from @${escapeHtml(sender)}</span>
|
||||||
|
${isEnc ? '<span class="msg-e2ee-tag">🔒 E2EE</span>' : ''}
|
||||||
|
<span class="message-time">${escapeHtml(timeStr)}</span>
|
||||||
|
</div>
|
||||||
|
<div class="inbox-item-preview">${escapeHtml(preview)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="inbox-item-actions">
|
||||||
|
<button type="button" class="btn btn-secondary btn-sm btn-inbox-open" title="Jump to Conversation">[Open]</button>
|
||||||
|
<button type="button" class="btn btn-secondary btn-sm btn-inbox-toggle-read" title="Toggle Read/Unread">[${isRead ? 'Mark Unread' : '✓ Read'}]</button>
|
||||||
|
<button type="button" class="btn btn-outline-danger btn-sm btn-inbox-dismiss" title="Delete from Inbox">[✕]</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
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() {
|
function checkLazyDmE2eePrompt() {
|
||||||
const active = getConversationById(state.activeChannelId);
|
const active = getConversationById(state.activeChannelId);
|
||||||
if (!active || getConversationType(active) !== 'DM') return;
|
if (!active || getConversationType(active) !== 'DM') return;
|
||||||
|
|
@ -1061,6 +1645,8 @@
|
||||||
renderChannels();
|
renderChannels();
|
||||||
} else if (tabName === 'files') {
|
} else if (tabName === 'files') {
|
||||||
renderFiles();
|
renderFiles();
|
||||||
|
} else if (tabName === 'inbox') {
|
||||||
|
renderInbox();
|
||||||
} else if (tabName === 'chat') {
|
} else if (tabName === 'chat') {
|
||||||
renderMessages();
|
renderMessages();
|
||||||
}
|
}
|
||||||
|
|
@ -1079,6 +1665,21 @@
|
||||||
el.channelSelectDropdown.value = chId;
|
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 (chType === 'DM') {
|
||||||
if (el.activeConvPrefix) el.activeConvPrefix.textContent = '@';
|
if (el.activeConvPrefix) el.activeConvPrefix.textContent = '@';
|
||||||
const dmIsE2ee = (active.isE2ee ?? active.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
|
const dmIsE2ee = (active.isE2ee ?? active.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
|
||||||
|
|
@ -1147,6 +1748,7 @@
|
||||||
const chName = ch.name || ch.Name;
|
const chName = ch.name || ch.Name;
|
||||||
const chTopic = ch.topic || ch.Topic || '';
|
const chTopic = ch.topic || ch.Topic || '';
|
||||||
const isActive = chId === state.activeChannelId;
|
const isActive = chId === state.activeChannelId;
|
||||||
|
const isFollowed = isConversationFollowed(ch);
|
||||||
|
|
||||||
const item = document.createElement('div');
|
const item = document.createElement('div');
|
||||||
item.className = 'channel-item' + (isActive ? ' active' : '');
|
item.className = 'channel-item' + (isActive ? ' active' : '');
|
||||||
|
|
@ -1155,8 +1757,18 @@
|
||||||
<span class="channel-title">#${escapeHtml(chName)}</span>
|
<span class="channel-title">#${escapeHtml(chName)}</span>
|
||||||
<span class="channel-desc">${escapeHtml(chTopic)}</span>
|
<span class="channel-desc">${escapeHtml(chTopic)}</span>
|
||||||
</div>
|
</div>
|
||||||
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
|
<div style="display:flex; gap:6px; align-items:center;">
|
||||||
|
<button type="button" class="btn btn-secondary btn-sm btn-follow-conv" title="Toggle Inbox & Push Notifications">[${isFollowed ? '🔔 Following' : '🔕 Follow'}]</button>
|
||||||
|
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
|
||||||
|
</div>
|
||||||
`;
|
`;
|
||||||
|
const followBtn = item.querySelector('.btn-follow-conv');
|
||||||
|
if (followBtn) {
|
||||||
|
followBtn.addEventListener('click', (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
toggleFollowConversation(chId, !isFollowed);
|
||||||
|
});
|
||||||
|
}
|
||||||
item.addEventListener('click', () => {
|
item.addEventListener('click', () => {
|
||||||
joinChannel(chId);
|
joinChannel(chId);
|
||||||
switchTab('chat');
|
switchTab('chat');
|
||||||
|
|
@ -1178,6 +1790,7 @@
|
||||||
const members = grp.memberUsernames || grp.MemberUsernames || [];
|
const members = grp.memberUsernames || grp.MemberUsernames || [];
|
||||||
const maxU = grp.maxUsers || grp.MaxUsers || state.maxGroupChatUsers;
|
const maxU = grp.maxUsers || grp.MaxUsers || state.maxGroupChatUsers;
|
||||||
const isActive = gId === state.activeChannelId;
|
const isActive = gId === state.activeChannelId;
|
||||||
|
const isFollowed = isConversationFollowed(grp);
|
||||||
|
|
||||||
const item = document.createElement('div');
|
const item = document.createElement('div');
|
||||||
item.className = 'channel-item' + (isActive ? ' active' : '');
|
item.className = 'channel-item' + (isActive ? ' active' : '');
|
||||||
|
|
@ -1187,8 +1800,18 @@
|
||||||
<span class="channel-title">[Group] ${escapeHtml(gName)} <span style="font-size:0.75rem; color:var(--ctp-mauve);">(${members.length}/${maxU})</span></span>
|
<span class="channel-title">[Group] ${escapeHtml(gName)} <span style="font-size:0.75rem; color:var(--ctp-mauve);">(${members.length}/${maxU})</span></span>
|
||||||
<span class="channel-desc">${escapeHtml(gTopic || membersText)}</span>
|
<span class="channel-desc">${escapeHtml(gTopic || membersText)}</span>
|
||||||
</div>
|
</div>
|
||||||
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
|
<div style="display:flex; gap:6px; align-items:center;">
|
||||||
|
<button type="button" class="btn btn-secondary btn-sm btn-follow-conv" title="Toggle Group Notifications">[${isFollowed ? '🔔 On' : '🔕 Muted'}]</button>
|
||||||
|
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
|
||||||
|
</div>
|
||||||
`;
|
`;
|
||||||
|
const followBtn = item.querySelector('.btn-follow-conv');
|
||||||
|
if (followBtn) {
|
||||||
|
followBtn.addEventListener('click', (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
toggleFollowConversation(gId, !isFollowed);
|
||||||
|
});
|
||||||
|
}
|
||||||
item.addEventListener('click', () => {
|
item.addEventListener('click', () => {
|
||||||
joinChannel(gId);
|
joinChannel(gId);
|
||||||
switchTab('chat');
|
switchTab('chat');
|
||||||
|
|
@ -1210,6 +1833,7 @@
|
||||||
const isE2ee = (dm.isE2ee ?? dm.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
|
const isE2ee = (dm.isE2ee ?? dm.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
|
||||||
const peerReady = isDmPeerE2eeReady(dm);
|
const peerReady = isDmPeerE2eeReady(dm);
|
||||||
const isActive = dmId === state.activeChannelId;
|
const isActive = dmId === state.activeChannelId;
|
||||||
|
const isFollowed = isConversationFollowed(dm);
|
||||||
|
|
||||||
let descText = 'Plaintext (Server-Visible)';
|
let descText = 'Plaintext (Server-Visible)';
|
||||||
let badgeLabel = 'Plain';
|
let badgeLabel = 'Plain';
|
||||||
|
|
@ -1236,10 +1860,18 @@
|
||||||
<span class="channel-desc">${descText}</span>
|
<span class="channel-desc">${descText}</span>
|
||||||
</div>
|
</div>
|
||||||
<div style="display:flex; gap:6px; align-items:center;">
|
<div style="display:flex; gap:6px; align-items:center;">
|
||||||
|
<button type="button" class="btn btn-secondary btn-sm btn-follow-conv" title="Toggle DM Notifications">[${isFollowed ? '🔔 On' : '🔕 Muted'}]</button>
|
||||||
<button type="button" class="btn btn-secondary btn-sm btn-toggle-dm-e2ee" title="Toggle E2EE for this DM">[${isE2ee ? 'E2EE: ON' : 'E2EE: OFF'}]</button>
|
<button type="button" class="btn btn-secondary btn-sm btn-toggle-dm-e2ee" title="Toggle E2EE for this DM">[${isE2ee ? 'E2EE: ON' : 'E2EE: OFF'}]</button>
|
||||||
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : `<span class="conv-security-badge ${badgeClass}">${badgeLabel}</span>`}
|
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : `<span class="conv-security-badge ${badgeClass}">${badgeLabel}</span>`}
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
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');
|
const toggleBtn = item.querySelector('.btn-toggle-dm-e2ee');
|
||||||
if (toggleBtn) {
|
if (toggleBtn) {
|
||||||
toggleBtn.addEventListener('click', (e) => {
|
toggleBtn.addEventListener('click', (e) => {
|
||||||
|
|
@ -1863,6 +2495,20 @@
|
||||||
return;
|
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', {
|
sendEnvelope('EXECUTE_COMMAND', {
|
||||||
command: cmd,
|
command: cmd,
|
||||||
args: args,
|
args: args,
|
||||||
|
|
@ -2015,6 +2661,38 @@
|
||||||
if (el.toggleDmE2eeBtn) {
|
if (el.toggleDmE2eeBtn) {
|
||||||
el.toggleDmE2eeBtn.addEventListener('click', () => toggleDmE2ee(state.activeChannelId));
|
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) {
|
if (el.e2eePinForm) {
|
||||||
el.e2eePinForm.addEventListener('submit', async (e) => {
|
el.e2eePinForm.addEventListener('submit', async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@
|
||||||
<meta name="theme-color" content="#11111b">
|
<meta name="theme-color" content="#11111b">
|
||||||
<meta name="color-scheme" content="dark">
|
<meta name="color-scheme" content="dark">
|
||||||
<title>GsDChat - Web Client</title>
|
<title>GsDChat - Web Client</title>
|
||||||
|
<link rel="manifest" href="/manifest.json">
|
||||||
<!-- Preload stylesheet to prevent flash of unstyled content and forced layout reflow -->
|
<!-- Preload stylesheet to prevent flash of unstyled content and forced layout reflow -->
|
||||||
<link rel="preload" href="/app.css" as="style">
|
<link rel="preload" href="/app.css" as="style">
|
||||||
<link rel="stylesheet" href="/app.css">
|
<link rel="stylesheet" href="/app.css">
|
||||||
|
|
@ -49,6 +50,7 @@
|
||||||
<button class="nav-tab" data-tab="channels">[2:channels/dms]</button>
|
<button class="nav-tab" data-tab="channels">[2:channels/dms]</button>
|
||||||
<button class="nav-tab" data-tab="users">[3:users]</button>
|
<button class="nav-tab" data-tab="users">[3:users]</button>
|
||||||
<button class="nav-tab" data-tab="files">[4:files]</button>
|
<button class="nav-tab" data-tab="files">[4:files]</button>
|
||||||
|
<button class="nav-tab" data-tab="inbox" id="navTabInbox">[5:inbox] <span id="inboxUnreadBadge" class="inbox-badge" style="display:none;">0</span></button>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
|
|
@ -76,6 +78,7 @@
|
||||||
<span class="channel-topic" id="activeChannelTopic"></span>
|
<span class="channel-topic" id="activeChannelTopic"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="chat-header-actions">
|
<div class="chat-header-actions">
|
||||||
|
<button type="button" class="btn btn-sm btn-secondary" id="toggleFollowBtn" title="Follow or Mute notifications for this conversation">[🔔 Follow]</button>
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="toggleDmE2eeBtn" style="display:none;" title="Toggle E2EE for this Direct Message">[DM E2EE: ON]</button>
|
<button type="button" class="btn btn-sm btn-secondary" id="toggleDmE2eeBtn" style="display:none;" title="Toggle E2EE for this Direct Message">[DM E2EE: ON]</button>
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="inviteGroupBtn" style="display:none;" title="Invite User to Group">[+ Invite]</button>
|
<button type="button" class="btn btn-sm btn-secondary" id="inviteGroupBtn" style="display:none;" title="Invite User to Group">[+ Invite]</button>
|
||||||
<button type="button" class="btn btn-sm btn-outline-danger" id="leaveGroupBtn" style="display:none;" title="Leave Group">[Leave]</button>
|
<button type="button" class="btn btn-sm btn-outline-danger" id="leaveGroupBtn" style="display:none;" title="Leave Group">[Leave]</button>
|
||||||
|
|
@ -228,6 +231,37 @@
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<!-- View 5: Inbox & Notifications View -->
|
||||||
|
<section id="view-inbox" class="tab-view">
|
||||||
|
<div class="view-header">
|
||||||
|
<h2>== INBOX & NOTIFICATIONS <span id="inboxHeaderCount" class="section-sub-hint">(0 Unread)</span> ==</h2>
|
||||||
|
<div style="display:flex; gap:6px; flex-wrap:wrap;">
|
||||||
|
<button type="button" class="btn btn-secondary btn-sm" id="markAllReadInboxBtn">[✓ Mark All Read]</button>
|
||||||
|
<button type="button" class="btn btn-secondary btn-sm" id="clearReadInboxBtn">[Clear Read]</button>
|
||||||
|
<button type="button" class="btn btn-outline-danger btn-sm" id="clearAllInboxBtn">[Clear All]</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="inbox-settings-bar">
|
||||||
|
<div class="inbox-prefs-group">
|
||||||
|
<span class="inbox-prefs-label">TRIGGERS:</span>
|
||||||
|
<button type="button" class="btn btn-sm btn-secondary" id="prefMentionsBtn" title="Toggle @mention notifications">[Mentions: ON]</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-secondary" id="prefAnnouncementsBtn" title="Toggle #announcements & /announce notifications">[Announcements: ON]</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-secondary" id="prefDmsBtn" title="Toggle Direct Message & Group notifications">[DMs & Groups: ON]</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-secondary" id="prefFollowedBtn" title="Toggle Followed Channel notifications">[Followed Channels: ON]</button>
|
||||||
|
</div>
|
||||||
|
<div class="inbox-push-group">
|
||||||
|
<span class="inbox-prefs-label">WEB PUSH:</span>
|
||||||
|
<button type="button" class="btn btn-sm btn-primary" id="toggleWebPushBtn" title="Enable or disable background Web Push notifications on this browser">[🔔 Enable Web Push]</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-secondary" id="testWebPushBtn" title="Send a test Web Push notification to this device">[Test Push]</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="inbox-list" id="inboxList">
|
||||||
|
<!-- Populated by JS -->
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<!-- Toast Notification Overlay -->
|
<!-- Toast Notification Overlay -->
|
||||||
|
|
|
||||||
10
src/GsDChat.Server/wwwroot/manifest.json
Normal file
10
src/GsDChat.Server/wwwroot/manifest.json
Normal file
|
|
@ -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": []
|
||||||
|
}
|
||||||
104
src/GsDChat.Server/wwwroot/sw.js
Normal file
104
src/GsDChat.Server/wwwroot/sw.js
Normal file
|
|
@ -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);
|
||||||
|
}
|
||||||
|
})());
|
||||||
|
});
|
||||||
|
|
@ -113,4 +113,55 @@ public class CryptoTests
|
||||||
string? wrongPassword = E2eeCrypto.UnwrapPrivateKey(wrapped, "WrongPassword", "Alice");
|
string? wrongPassword = E2eeCrypto.UnwrapPrivateKey(wrapped, "WrongPassword", "Alice");
|
||||||
Assert.Null(wrongPassword);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -135,6 +135,8 @@ public class DatabaseTests : IDisposable
|
||||||
Assert.True(File.Exists(settingsPath));
|
Assert.True(File.Exists(settingsPath));
|
||||||
Assert.True(options.AllowDmE2ee);
|
Assert.True(options.AllowDmE2ee);
|
||||||
Assert.Equal(10, options.MaxGroupChatUsers);
|
Assert.Equal(10, options.MaxGroupChatUsers);
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(options.VapidPublicKey));
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(options.VapidPrivateKey));
|
||||||
|
|
||||||
options.ServerName = "Custom JSON Server";
|
options.ServerName = "Custom JSON Server";
|
||||||
options.AllowDmE2ee = false;
|
options.AllowDmE2ee = false;
|
||||||
|
|
@ -215,4 +217,108 @@ public class DatabaseTests : IDisposable
|
||||||
Assert.Null(await _db.GetFileRecordAsync("file_grp_1"));
|
Assert.Null(await _db.GetFileRecordAsync("file_grp_1"));
|
||||||
Assert.False(File.Exists(tempFilePath));
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,7 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
builder.WebHost.UseUrls(_serverUrl);
|
builder.WebHost.UseUrls(_serverUrl);
|
||||||
builder.Logging.ClearProviders(); // Keep test output clean
|
builder.Logging.ClearProviders(); // Keep test output clean
|
||||||
|
|
||||||
|
var (vapidPub, vapidPriv) = GsDChat.Core.Security.WebPushCrypto.GenerateVapidKeys();
|
||||||
var serverOptions = new ServerOptions
|
var serverOptions = new ServerOptions
|
||||||
{
|
{
|
||||||
Host = "127.0.0.1",
|
Host = "127.0.0.1",
|
||||||
|
|
@ -58,7 +59,10 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
DataDirectory = _testDir,
|
DataDirectory = _testDir,
|
||||||
ServerName = "E2E Test Server",
|
ServerName = "E2E Test Server",
|
||||||
Motd = "Testing GsDChat E2E",
|
Motd = "Testing GsDChat E2E",
|
||||||
MaxWebSocketMessageSizeBytes = 1048576
|
MaxWebSocketMessageSizeBytes = 1048576,
|
||||||
|
VapidPublicKey = vapidPub,
|
||||||
|
VapidPrivateKey = vapidPriv,
|
||||||
|
VapidSubject = "mailto:test@gsdchat.local"
|
||||||
};
|
};
|
||||||
|
|
||||||
builder.Services.AddSingleton(serverOptions);
|
builder.Services.AddSingleton(serverOptions);
|
||||||
|
|
@ -66,6 +70,7 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
builder.Services.AddSingleton<InviteTokenService>();
|
builder.Services.AddSingleton<InviteTokenService>();
|
||||||
builder.Services.AddSingleton<IAuthService, AuthService>();
|
builder.Services.AddSingleton<IAuthService, AuthService>();
|
||||||
builder.Services.AddSingleton<FileStorageService>();
|
builder.Services.AddSingleton<FileStorageService>();
|
||||||
|
builder.Services.AddSingleton<WebPushService>();
|
||||||
builder.Services.AddSingleton<ChatWebSocketManager>();
|
builder.Services.AddSingleton<ChatWebSocketManager>();
|
||||||
builder.Services.AddSingleton<RateLimitService>();
|
builder.Services.AddSingleton<RateLimitService>();
|
||||||
builder.Services.AddSingleton<ConnectionLimiterService>();
|
builder.Services.AddSingleton<ConnectionLimiterService>();
|
||||||
|
|
@ -103,9 +108,52 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
MaxFileSizeMb = opt.MaxFileSizeMb,
|
MaxFileSizeMb = opt.MaxFileSizeMb,
|
||||||
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
|
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
|
||||||
AllowDmE2ee = opt.AllowDmE2ee,
|
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) =>
|
_app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, CsrfProtectionService csrf, HttpContext context) =>
|
||||||
{
|
{
|
||||||
string? csrfToken = context.Request.Headers["X-CSRF-Token"];
|
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.Contains(charlieGroupMsgs, m => m.Content == "Hello team members!");
|
||||||
Assert.False(stateDave.ChannelMessages.ContainsKey(groupId));
|
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>();
|
||||||
|
serverOptions.AllowDmE2ee = true;
|
||||||
|
var db = _app.Services.GetRequiredService<ChatDatabase>();
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -32,12 +32,32 @@ public class NetworkProtocolTests
|
||||||
Assert.Equal("TestServer", sync.ServerName);
|
Assert.Equal("TestServer", sync.ServerName);
|
||||||
Assert.Equal("Welcome MOTD", sync.Motd);
|
Assert.Equal("Welcome MOTD", sync.Motd);
|
||||||
Assert.NotNull(sync.Screens);
|
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 == "F1_Chat");
|
||||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F2_Channels");
|
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 == "F3_Users");
|
||||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F4_Files");
|
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<InboxActionPacket>();
|
||||||
|
|
||||||
|
Assert.NotNull(unpacked);
|
||||||
|
Assert.Equal("mark_read", unpacked.Action);
|
||||||
|
Assert.Equal("item_123", unpacked.ItemId);
|
||||||
|
Assert.Equal("ch_general", unpacked.ChannelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|
|
||||||
|
|
@ -105,6 +105,10 @@ public class WebClientStaticTests : IAsyncLifetime
|
||||||
Assert.Contains("id=\"dmList\"", html);
|
Assert.Contains("id=\"dmList\"", html);
|
||||||
Assert.Contains("id=\"createGroupCard\"", html);
|
Assert.Contains("id=\"createGroupCard\"", html);
|
||||||
Assert.Contains("id=\"startDmCard\"", 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]
|
[Fact]
|
||||||
|
|
@ -119,6 +123,8 @@ public class WebClientStaticTests : IAsyncLifetime
|
||||||
Assert.Contains("--bg-main", css);
|
Assert.Contains("--bg-main", css);
|
||||||
Assert.Contains(".app-layout", css);
|
Assert.Contains(".app-layout", css);
|
||||||
Assert.Contains(".conv-security-badge", css);
|
Assert.Contains(".conv-security-badge", css);
|
||||||
|
Assert.Contains(".inbox-item", css);
|
||||||
|
Assert.Contains(".inbox-badge", css);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|
@ -137,5 +143,25 @@ public class WebClientStaticTests : IAsyncLifetime
|
||||||
Assert.Contains("unlockOrInitE2eeWithPin", js);
|
Assert.Contains("unlockOrInitE2eeWithPin", js);
|
||||||
Assert.Contains("FETCH_HISTORY", js);
|
Assert.Contains("FETCH_HISTORY", js);
|
||||||
Assert.Contains("TOGGLE_E2EE", 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue