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
|
|
@ -113,4 +113,55 @@ public class CryptoTests
|
|||
string? wrongPassword = E2eeCrypto.UnwrapPrivateKey(wrapped, "WrongPassword", "Alice");
|
||||
Assert.Null(wrongPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WebPushCrypto_GenerateVapidKeys_And_SignVerifyJwt_ShouldSucceed()
|
||||
{
|
||||
var (publicKey, privateKey) = WebPushCrypto.GenerateVapidKeys();
|
||||
Assert.False(string.IsNullOrWhiteSpace(publicKey));
|
||||
Assert.False(string.IsNullOrWhiteSpace(privateKey));
|
||||
|
||||
var pubBytes = WebPushCrypto.Base64UrlDecode(publicKey);
|
||||
var privBytes = WebPushCrypto.Base64UrlDecode(privateKey);
|
||||
Assert.Equal(65, pubBytes.Length);
|
||||
Assert.Equal(0x04, pubBytes[0]);
|
||||
Assert.Equal(32, privBytes.Length);
|
||||
|
||||
string authHeader = WebPushCrypto.CreateVapidAuthorizationHeader(
|
||||
"https://fcm.googleapis.com/fcm/send/example123",
|
||||
"mailto:admin@gsdchat.local",
|
||||
publicKey,
|
||||
privateKey);
|
||||
|
||||
Assert.StartsWith("vapid t=", authHeader);
|
||||
Assert.Contains($", k={publicKey}", authHeader);
|
||||
|
||||
// Extract JWT token and verify ES256 signature
|
||||
int tStart = authHeader.IndexOf("t=", StringComparison.Ordinal) + 2;
|
||||
int tEnd = authHeader.IndexOf(", k=", StringComparison.Ordinal);
|
||||
string jwt = authHeader.Substring(tStart, tEnd - tStart);
|
||||
|
||||
Assert.True(WebPushCrypto.VerifyVapidJwt(jwt, publicKey));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WebPushCrypto_Rfc8291Aes128GcmPayloadEncryption_ShouldRoundTrip()
|
||||
{
|
||||
// Generate simulated browser push subscription keypair (p256dh) and 16-byte auth secret
|
||||
var (subPub, subPriv) = WebPushCrypto.GenerateVapidKeys();
|
||||
byte[] authSecretBytes = new byte[16];
|
||||
System.Security.Cryptography.RandomNumberGenerator.Fill(authSecretBytes);
|
||||
string authSecret = WebPushCrypto.Base64UrlEncode(authSecretBytes);
|
||||
|
||||
string jsonPayload = "{\"title\":\"GsDChat (@Alice)\",\"body\":\"Hey @Bob check #announcements!\",\"channelId\":\"ch_1\"}";
|
||||
byte[] encryptedBody = WebPushCrypto.EncryptPayload(System.Text.Encoding.UTF8.GetBytes(jsonPayload), subPub, authSecret);
|
||||
|
||||
Assert.NotNull(encryptedBody);
|
||||
// Header is 86 bytes (16 salt + 4 rs + 1 idlen + 65 pubkey) + ciphertext + 16 tag
|
||||
Assert.True(encryptedBody.Length > 86 + 16);
|
||||
|
||||
byte[] decryptedBytes = WebPushCrypto.DecryptPayload(encryptedBody, subPub, subPriv, authSecret);
|
||||
string decrypted = System.Text.Encoding.UTF8.GetString(decryptedBytes);
|
||||
Assert.Equal(jsonPayload, decrypted);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -135,6 +135,8 @@ public class DatabaseTests : IDisposable
|
|||
Assert.True(File.Exists(settingsPath));
|
||||
Assert.True(options.AllowDmE2ee);
|
||||
Assert.Equal(10, options.MaxGroupChatUsers);
|
||||
Assert.False(string.IsNullOrWhiteSpace(options.VapidPublicKey));
|
||||
Assert.False(string.IsNullOrWhiteSpace(options.VapidPrivateKey));
|
||||
|
||||
options.ServerName = "Custom JSON Server";
|
||||
options.AllowDmE2ee = false;
|
||||
|
|
@ -215,4 +217,108 @@ public class DatabaseTests : IDisposable
|
|||
Assert.Null(await _db.GetFileRecordAsync("file_grp_1"));
|
||||
Assert.False(File.Exists(tempFilePath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InboxAndWebPushSubscriptions_DatabaseCrudOperations_ShouldSucceed()
|
||||
{
|
||||
var bob = new User { Username = "BobInbox", PasswordHash = "h", PasswordSalt = "s" };
|
||||
await _db.CreateUserAsync(bob);
|
||||
|
||||
// 1. Default preferences & channel follow overrides
|
||||
var prefs = await _db.GetInboxPreferencesAsync(bob.Id);
|
||||
Assert.True(prefs.MentionsEnabled);
|
||||
Assert.True(prefs.AnnouncementsEnabled);
|
||||
Assert.True(prefs.DirectMessagesEnabled);
|
||||
Assert.True(prefs.FollowedChannelsEnabled);
|
||||
Assert.True(prefs.PushNotificationsEnabled);
|
||||
Assert.Empty(prefs.FollowedChannelIds);
|
||||
Assert.Empty(prefs.MutedChannelIds);
|
||||
|
||||
var channels = await _db.GetChannelsAsync();
|
||||
var general = channels.First(c => c.Name == "general");
|
||||
var announcements = channels.First(c => c.Name == "announcements");
|
||||
|
||||
await _db.SetChannelFollowModeAsync(bob.Id, general.Id, ConversationFollowModes.Followed);
|
||||
await _db.SetChannelFollowModeAsync(bob.Id, announcements.Id, ConversationFollowModes.Muted);
|
||||
|
||||
prefs.MentionsEnabled = false;
|
||||
await _db.SaveInboxPreferencesAsync(prefs);
|
||||
|
||||
var reloadedPrefs = await _db.GetInboxPreferencesAsync(bob.Id);
|
||||
Assert.False(reloadedPrefs.MentionsEnabled);
|
||||
Assert.Contains(general.Id, reloadedPrefs.FollowedChannelIds);
|
||||
Assert.Contains(announcements.Id, reloadedPrefs.MutedChannelIds);
|
||||
|
||||
// 2. Inbox Items CRUD
|
||||
var item1 = new InboxItem
|
||||
{
|
||||
UserId = bob.Id,
|
||||
MessageId = "msg_1",
|
||||
ChannelId = general.Id,
|
||||
ChannelName = "general",
|
||||
ChannelType = ChannelTypes.Channel,
|
||||
SenderId = "u_alice",
|
||||
SenderUsername = "Alice",
|
||||
Category = InboxCategories.Mention,
|
||||
ContentPreview = "Hey @BobInbox!",
|
||||
IsRead = false,
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(-2)
|
||||
};
|
||||
var item2 = new InboxItem
|
||||
{
|
||||
UserId = bob.Id,
|
||||
MessageId = "msg_2",
|
||||
ChannelId = announcements.Id,
|
||||
ChannelName = "announcements",
|
||||
ChannelType = ChannelTypes.Channel,
|
||||
SenderId = "u_alice",
|
||||
SenderUsername = "Alice",
|
||||
Category = InboxCategories.Announcement,
|
||||
ContentPreview = "Server maintenance tonight",
|
||||
IsRead = false,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await _db.CreateInboxItemAsync(item1);
|
||||
await _db.CreateInboxItemAsync(item2);
|
||||
|
||||
Assert.Equal(2, await _db.GetUnreadInboxCountAsync(bob.Id));
|
||||
var items = await _db.GetInboxItemsForUserAsync(bob.Id);
|
||||
Assert.Equal(2, items.Count);
|
||||
Assert.Equal(item2.Id, items[0].Id); // Ordered newest first
|
||||
|
||||
// Mark channel read
|
||||
await _db.MarkChannelInboxItemsReadAsync(bob.Id, general.Id);
|
||||
Assert.Equal(1, await _db.GetUnreadInboxCountAsync(bob.Id));
|
||||
|
||||
// Clear read items
|
||||
await _db.ClearInboxItemsAsync(bob.Id, onlyRead: true);
|
||||
items = await _db.GetInboxItemsForUserAsync(bob.Id);
|
||||
Assert.Single(items);
|
||||
Assert.Equal(item2.Id, items[0].Id);
|
||||
|
||||
// Mark all read & clear all
|
||||
await _db.MarkAllInboxItemsReadAsync(bob.Id);
|
||||
Assert.Equal(0, await _db.GetUnreadInboxCountAsync(bob.Id));
|
||||
await _db.ClearInboxItemsAsync(bob.Id, onlyRead: false);
|
||||
Assert.Empty(await _db.GetInboxItemsForUserAsync(bob.Id));
|
||||
|
||||
// 3. Web Push Subscriptions CRUD
|
||||
var sub = new PushSubscriptionRecord
|
||||
{
|
||||
UserId = bob.Id,
|
||||
Endpoint = "https://push.example.org/send/sub_1",
|
||||
P256dh = "p256dh_key_value",
|
||||
Auth = "auth_secret_value",
|
||||
UserAgent = "Mozilla/5.0 Test"
|
||||
};
|
||||
await _db.SavePushSubscriptionAsync(sub);
|
||||
|
||||
var subs = await _db.GetPushSubscriptionsForUserAsync(bob.Id);
|
||||
Assert.Single(subs);
|
||||
Assert.Equal("https://push.example.org/send/sub_1", subs[0].Endpoint);
|
||||
|
||||
await _db.RemovePushSubscriptionByEndpointAsync("https://push.example.org/send/sub_1");
|
||||
Assert.Empty(await _db.GetPushSubscriptionsForUserAsync(bob.Id));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ public class EndToEndChatTests : IAsyncLifetime
|
|||
builder.WebHost.UseUrls(_serverUrl);
|
||||
builder.Logging.ClearProviders(); // Keep test output clean
|
||||
|
||||
var (vapidPub, vapidPriv) = GsDChat.Core.Security.WebPushCrypto.GenerateVapidKeys();
|
||||
var serverOptions = new ServerOptions
|
||||
{
|
||||
Host = "127.0.0.1",
|
||||
|
|
@ -58,7 +59,10 @@ public class EndToEndChatTests : IAsyncLifetime
|
|||
DataDirectory = _testDir,
|
||||
ServerName = "E2E Test Server",
|
||||
Motd = "Testing GsDChat E2E",
|
||||
MaxWebSocketMessageSizeBytes = 1048576
|
||||
MaxWebSocketMessageSizeBytes = 1048576,
|
||||
VapidPublicKey = vapidPub,
|
||||
VapidPrivateKey = vapidPriv,
|
||||
VapidSubject = "mailto:test@gsdchat.local"
|
||||
};
|
||||
|
||||
builder.Services.AddSingleton(serverOptions);
|
||||
|
|
@ -66,6 +70,7 @@ public class EndToEndChatTests : IAsyncLifetime
|
|||
builder.Services.AddSingleton<InviteTokenService>();
|
||||
builder.Services.AddSingleton<IAuthService, AuthService>();
|
||||
builder.Services.AddSingleton<FileStorageService>();
|
||||
builder.Services.AddSingleton<WebPushService>();
|
||||
builder.Services.AddSingleton<ChatWebSocketManager>();
|
||||
builder.Services.AddSingleton<RateLimitService>();
|
||||
builder.Services.AddSingleton<ConnectionLimiterService>();
|
||||
|
|
@ -103,9 +108,52 @@ public class EndToEndChatTests : IAsyncLifetime
|
|||
MaxFileSizeMb = opt.MaxFileSizeMb,
|
||||
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
|
||||
AllowDmE2ee = opt.AllowDmE2ee,
|
||||
MaxGroupChatUsers = opt.MaxGroupChatUsers
|
||||
MaxGroupChatUsers = opt.MaxGroupChatUsers,
|
||||
VapidPublicKey = opt.VapidPublicKey
|
||||
}));
|
||||
|
||||
_app.MapGet("/api/push/vapid-public-key", (ServerOptions opt) =>
|
||||
{
|
||||
return Results.Ok(new { publicKey = opt.VapidPublicKey });
|
||||
});
|
||||
|
||||
_app.MapPost("/api/push/subscribe", async (PushSubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) =>
|
||||
{
|
||||
string? token = ExtractToken(httpReq);
|
||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||
if (user == null) return Results.Unauthorized();
|
||||
|
||||
await chatDb.SavePushSubscriptionAsync(new PushSubscriptionRecord
|
||||
{
|
||||
UserId = user.Id,
|
||||
Endpoint = req.Endpoint.Trim(),
|
||||
P256dh = req.P256dh.Trim(),
|
||||
Auth = req.Auth.Trim(),
|
||||
UserAgent = req.UserAgent ?? string.Empty
|
||||
});
|
||||
return Results.Ok(new { success = true });
|
||||
});
|
||||
|
||||
_app.MapPost("/api/push/unsubscribe", async (PushUnsubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) =>
|
||||
{
|
||||
string? token = ExtractToken(httpReq);
|
||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||
if (user == null) return Results.Unauthorized();
|
||||
|
||||
await chatDb.RemovePushSubscriptionAsync(user.Id, req.Endpoint.Trim());
|
||||
return Results.Ok(new { success = true });
|
||||
});
|
||||
|
||||
_app.MapPost("/api/push/test", async (HttpRequest httpReq, IAuthService auth, WebPushService webPush) =>
|
||||
{
|
||||
string? token = ExtractToken(httpReq);
|
||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||
if (user == null) return Results.Unauthorized();
|
||||
|
||||
bool delivered = await webPush.SendTestPushAsync(user.Id, user.Username);
|
||||
return Results.Ok(new { success = delivered });
|
||||
});
|
||||
|
||||
_app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, CsrfProtectionService csrf, HttpContext context) =>
|
||||
{
|
||||
string? csrfToken = context.Request.Headers["X-CSRF-Token"];
|
||||
|
|
@ -872,5 +920,233 @@ public class EndToEndChatTests : IAsyncLifetime
|
|||
Assert.Contains(charlieGroupMsgs, m => m.Content == "Hello team members!");
|
||||
Assert.False(stateDave.ChannelMessages.ContainsKey(groupId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InboxNotifications_MentionsAnnouncementsFollowedChannelsAndDms_ShouldDeliverAndMarkReadOnJoin()
|
||||
{
|
||||
var stateAlice = CreateClientState();
|
||||
using var connAlice = new ChatClientConnection(stateAlice);
|
||||
var regAlice = await connAlice.RegisterAsync("AliceInbox", "Pass123!");
|
||||
stateAlice.Token = regAlice.Token!;
|
||||
stateAlice.CurrentUserId = regAlice.UserId!;
|
||||
stateAlice.CurrentUsername = regAlice.Username!;
|
||||
stateAlice.CurrentUserRole = regAlice.Role!;
|
||||
|
||||
var stateBob = CreateClientState();
|
||||
using var connBob = new ChatClientConnection(stateBob);
|
||||
var regBob = await connBob.RegisterAsync("BobInbox", "Pass123!");
|
||||
stateBob.Token = regBob.Token!;
|
||||
stateBob.CurrentUserId = regBob.UserId!;
|
||||
stateBob.CurrentUsername = regBob.Username!;
|
||||
stateBob.CurrentUserRole = regBob.Role!;
|
||||
|
||||
await connAlice.StartWebSocketAsync();
|
||||
await connBob.StartWebSocketAsync();
|
||||
await Task.Delay(300);
|
||||
|
||||
string generalId = stateAlice.Channels.First(c => c.Name == "general").Id;
|
||||
string announcementsId = stateAlice.Channels.First(c => c.Name == "announcements").Id;
|
||||
|
||||
// 1. Alice mentions @BobInbox in #general -> Bob receives an unread Mention inbox item
|
||||
await connAlice.SendChatMessageAsync(generalId, "Hello @BobInbox please review the PR!");
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (stateBob.UnreadInboxCount >= 1) break;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
Assert.Equal(1, stateBob.UnreadInboxCount);
|
||||
var bobItems = stateBob.GetInboxItems();
|
||||
Assert.Single(bobItems);
|
||||
Assert.Equal(InboxCategories.Mention, bobItems[0].Category);
|
||||
Assert.Contains("Hello @BobInbox", bobItems[0].ContentPreview);
|
||||
Assert.False(bobItems[0].IsRead);
|
||||
|
||||
// 2. Alice posts in #announcements -> Bob receives an unread Announcement inbox item
|
||||
await connAlice.SendChatMessageAsync(announcementsId, "Release v2.0 is live!");
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (stateBob.UnreadInboxCount >= 2) break;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
Assert.Equal(2, stateBob.UnreadInboxCount);
|
||||
bobItems = stateBob.GetInboxItems();
|
||||
Assert.Contains(bobItems, x => x.Category == InboxCategories.Announcement && x.ContentPreview.Contains("Release v2.0"));
|
||||
|
||||
// 3. Bob joins #announcements -> auto-marks #announcements inbox items as read!
|
||||
await connBob.JoinChannelAsync(announcementsId);
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (stateBob.UnreadInboxCount == 1) break;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(1, stateBob.UnreadInboxCount);
|
||||
|
||||
// 4. Bob follows #general -> non-mention messages in #general now create FollowedChannel inbox items for Bob
|
||||
await connBob.ToggleFollowChannelAsync(generalId, follow: true);
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (stateBob.IsConversationFollowed(stateBob.Channels.First(c => c.Id == generalId))) break;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.True(stateBob.IsConversationFollowed(stateBob.Channels.First(c => c.Id == generalId)));
|
||||
|
||||
await connAlice.SendChatMessageAsync(generalId, "Regular update in followed general channel");
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (stateBob.UnreadInboxCount >= 2) break;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
bobItems = stateBob.GetInboxItems();
|
||||
Assert.Contains(bobItems, x => x.Category == InboxCategories.FollowedChannel && x.ContentPreview.Contains("Regular update"));
|
||||
|
||||
// 5. Bob marks all read and clears read items
|
||||
await connBob.SendInboxActionAsync("mark_all_read");
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (stateBob.UnreadInboxCount == 0) break;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(0, stateBob.UnreadInboxCount);
|
||||
|
||||
await connBob.SendInboxActionAsync("clear_read");
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (stateBob.GetInboxItems().Count == 0) break;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(stateBob.GetInboxItems());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InboxNotifications_WithE2eeDirectMessage_ShouldDecryptInClientInboxAndDeliverEncryptedWebPush()
|
||||
{
|
||||
var serverOptions = _app!.Services.GetRequiredService<ServerOptions>();
|
||||
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("Welcome MOTD", sync.Motd);
|
||||
Assert.NotNull(sync.Screens);
|
||||
Assert.Equal(4, sync.Screens.Count);
|
||||
Assert.Equal(5, sync.Screens.Count);
|
||||
|
||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F1_Chat");
|
||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F2_Channels");
|
||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F3_Users");
|
||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F4_Files");
|
||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F5_Inbox");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NetworkEnvelope_ShouldPackAndUnpackInboxPackets()
|
||||
{
|
||||
var actionPacket = new InboxActionPacket
|
||||
{
|
||||
Action = "mark_read",
|
||||
ItemId = "item_123",
|
||||
ChannelId = "ch_general"
|
||||
};
|
||||
|
||||
var env = NetworkEnvelope.Create(MessageTypes.InboxAction, actionPacket);
|
||||
var unpacked = env.Unpack<InboxActionPacket>();
|
||||
|
||||
Assert.NotNull(unpacked);
|
||||
Assert.Equal("mark_read", unpacked.Action);
|
||||
Assert.Equal("item_123", unpacked.ItemId);
|
||||
Assert.Equal("ch_general", unpacked.ChannelId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
|
|
@ -105,6 +105,10 @@ public class WebClientStaticTests : IAsyncLifetime
|
|||
Assert.Contains("id=\"dmList\"", html);
|
||||
Assert.Contains("id=\"createGroupCard\"", html);
|
||||
Assert.Contains("id=\"startDmCard\"", html);
|
||||
Assert.Contains("id=\"view-inbox\"", html);
|
||||
Assert.Contains("id=\"navTabInbox\"", html);
|
||||
Assert.Contains("id=\"inboxUnreadBadge\"", html);
|
||||
Assert.Contains("id=\"toggleWebPushBtn\"", html);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -119,6 +123,8 @@ public class WebClientStaticTests : IAsyncLifetime
|
|||
Assert.Contains("--bg-main", css);
|
||||
Assert.Contains(".app-layout", css);
|
||||
Assert.Contains(".conv-security-badge", css);
|
||||
Assert.Contains(".inbox-item", css);
|
||||
Assert.Contains(".inbox-badge", css);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -137,5 +143,25 @@ public class WebClientStaticTests : IAsyncLifetime
|
|||
Assert.Contains("unlockOrInitE2eeWithPin", js);
|
||||
Assert.Contains("FETCH_HISTORY", js);
|
||||
Assert.Contains("TOGGLE_E2EE", js);
|
||||
Assert.Contains("INBOX_SYNC", js);
|
||||
Assert.Contains("INBOX_NEW_ITEM", js);
|
||||
Assert.Contains("subscribeWebPush", js);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetServiceWorkerAndManifest_ShouldServeWebPushAssets()
|
||||
{
|
||||
Assert.NotNull(_httpClient);
|
||||
|
||||
var swRes = await _httpClient.GetAsync("/sw.js");
|
||||
Assert.True(swRes.IsSuccessStatusCode);
|
||||
string swJs = await swRes.Content.ReadAsStringAsync();
|
||||
Assert.Contains("showNotification", swJs);
|
||||
Assert.Contains("notificationclick", swJs);
|
||||
|
||||
var manifestRes = await _httpClient.GetAsync("/manifest.json");
|
||||
Assert.True(manifestRes.IsSuccessStatusCode);
|
||||
string manifestJson = await manifestRes.Content.ReadAsStringAsync();
|
||||
Assert.Contains("GsDChat", manifestJson);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue