mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-18 13:24:59 +00:00
Expose chat read positions and E2EE errors
Add optional chat activity and read-position details to the unread-count endpoint. Return stable E2EE rejection codes for stale timestamps and untrusted signing devices, with tests for both behaviors.
This commit is contained in:
@@ -55,6 +55,8 @@ public static class E2eeProtocol
|
||||
public const int MaxDevices = 500;
|
||||
public const string EncryptedMimeType = "application/vnd.govor.encrypted";
|
||||
public const string DevicesChangedError = "E2EE_DEVICES_CHANGED";
|
||||
public const string TimestampOutOfRangeError = "E2EE_TIMESTAMP_OUT_OF_RANGE";
|
||||
public const string SigningDeviceRejectedError = "E2EE_SIGNING_DEVICE_REJECTED";
|
||||
public static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
public static bool IsEncrypted(string? value)
|
||||
|
||||
@@ -224,9 +224,10 @@ public sealed class E2eeService(GovorDbContext context)
|
||||
envelope.RecipientType != (int)type || envelope.ReplyToMessageId != replyTo ||
|
||||
envelope.IsEdit != editedMessage.HasValue ||
|
||||
(editedMessage.HasValue && envelope.MessageId != editedMessage) ||
|
||||
!envelope.MediaIds.Order().SequenceEqual(media.Order()) ||
|
||||
Math.Abs((double)envelope.CreatedAt - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) > 300_000)
|
||||
throw new ArgumentException("E2EE routing, attachment or time context does not match.");
|
||||
!envelope.MediaIds.Order().SequenceEqual(media.Order()))
|
||||
throw new ArgumentException("E2EE routing or attachment context does not match.");
|
||||
if (Math.Abs((double)envelope.CreatedAt - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) > 300_000)
|
||||
throw new ArgumentException(E2eeProtocol.TimestampOutOfRangeError);
|
||||
|
||||
var signingSession = await context.UserSessions.AsNoTracking().Include(s => s.CryptoSession)
|
||||
.ThenInclude(c => c.SignedPreKey).SingleOrDefaultAsync(s => s.Id == envelope.Sender.SessionId &&
|
||||
@@ -235,7 +236,7 @@ public sealed class E2eeService(GovorDbContext context)
|
||||
ToDeviceKey(signingSession.CryptoSession, sender).Fingerprint != envelope.Sender.Fingerprint ||
|
||||
signingSession.CryptoSession.AccountIdentityKey != envelope.Sender.AccountIdentityKey ||
|
||||
signingSession.CryptoSession.Generation != envelope.Sender.Generation)
|
||||
throw new UnauthorizedAccessException("E2EE signing device is unknown or revoked.");
|
||||
throw new UnauthorizedAccessException(E2eeProtocol.SigningDeviceRejectedError);
|
||||
var directory = await GetConversationKeysAsync(sender, conversation, type);
|
||||
var expected = directory.Devices.Select(k => k.Fingerprint).Distinct().Order(StringComparer.Ordinal);
|
||||
if (!expected.SequenceEqual(envelope.Recipients.Order(StringComparer.Ordinal)))
|
||||
|
||||
@@ -11,4 +11,9 @@ public interface IMessageReadingService
|
||||
Task<Result<ChatReadResult, Error>> ReadChatAsync(Guid readerId, Guid chatId,
|
||||
RecipientType type, IReadOnlyCollection<Guid>? messageIds = null, Guid? upToMessageId = null);
|
||||
Task<Result<int, Error>> GetUnreadCountAsync(Guid readerId, Guid chatId, RecipientType type);
|
||||
Task<Result<ChatActivity, Error>> GetChatActivityAsync(Guid readerId, Guid chatId, RecipientType type,
|
||||
bool includeReadPosition = false);
|
||||
}
|
||||
|
||||
public sealed record ChatActivity(int UnreadCount, DateTime? LastMessageAt,
|
||||
Guid? LastReadMessageId = null, Guid? FirstUnreadMessageId = null);
|
||||
|
||||
@@ -148,6 +148,33 @@ public class MessageReadingService : IMessageReadingService
|
||||
chat.CountAsync(m => m.SenderId != readerId &&
|
||||
!_dbContext.MessageViews.Any(v => v.MessageId == m.Id && v.UserId == readerId));
|
||||
|
||||
public async Task<Result<ChatActivity, Error>> GetChatActivityAsync(Guid readerId, Guid chatId, RecipientType type,
|
||||
bool includeReadPosition = false)
|
||||
{
|
||||
if (!await _dbContext.HasChatAccessAsync(readerId, chatId, type))
|
||||
return Result.Failure<ChatActivity>(Denied());
|
||||
|
||||
var chat = _dbContext.Messages.AsNoTracking()
|
||||
.Where(m => m.RecipientId == chatId && m.RecipientType == type);
|
||||
var activity = await chat.GroupBy(_ => 1).Select(g => new ChatActivity(
|
||||
g.Count(m => m.SenderId != readerId &&
|
||||
!_dbContext.MessageViews.Any(v => v.MessageId == m.Id && v.UserId == readerId)),
|
||||
g.Max(m => (DateTime?)m.SentAt))).SingleOrDefaultAsync();
|
||||
if (activity is null) return new ChatActivity(0, null);
|
||||
if (!includeReadPosition) return activity;
|
||||
|
||||
var firstUnread = await chat.Where(m => m.SenderId != readerId &&
|
||||
!_dbContext.MessageViews.Any(v => v.MessageId == m.Id && v.UserId == readerId))
|
||||
.OrderBy(m => m.SentAt).ThenBy(m => m.Id)
|
||||
.Select(m => new { m.Id, m.SentAt }).FirstOrDefaultAsync();
|
||||
// Outgoing messages count as read. Do not skip an earlier unread incoming message.
|
||||
var readHistory = firstUnread is null ? chat : chat.Where(m => m.SentAt < firstUnread.SentAt ||
|
||||
(m.SentAt == firstUnread.SentAt && m.Id.CompareTo(firstUnread.Id) < 0));
|
||||
var lastRead = await readHistory.OrderByDescending(m => m.SentAt).ThenByDescending(m => m.Id)
|
||||
.Select(m => (Guid?)m.Id).FirstOrDefaultAsync();
|
||||
return activity with { LastReadMessageId = lastRead, FirstUnreadMessageId = firstUnread?.Id };
|
||||
}
|
||||
|
||||
private static Error Denied() => Error.Forbidden("Chat.AccessDenied",
|
||||
"You are not a member of this chat.");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user