Bifrost/src/Bifrost.Web/Features/Invites/ChatInviteService.cs

144 lines
7 KiB
C#

using System.Security.Cryptography;
using System.Text;
using Bifrost.Web.Configuration;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace Bifrost.Web.Features.Invites;
/// <summary>
/// The one owner of chat invites. An operator mints a single-use link (<see cref="MintAsync"/>; the payment ledger will mint the same record),
/// a visitor who opens it carries the token in a short cookie through sign-in, and every sign-in path ends in <see cref="RedeemCarriedAsync"/>,
/// which spends the invite onto the signed-in account. Only the SHA-256 of the token is stored.
/// </summary>
public sealed class ChatInviteService(BifrostDbContext db, AuditTrailService audit, TimeProvider time, IOptions<BifrostHostOptions> host)
{
public const string CookieName = BifrostCookies.HostPrefix + "bifrost_chat_invite";
public const string EntityType = "ChatInvite";
public static readonly TimeSpan Lifetime = TimeSpan.FromDays(14);
public static readonly TimeSpan CookieLifetime = TimeSpan.FromHours(1);
/// <summary>The link an operator sends: the public base URL plus the invite path.</summary>
public string LinkFor(string token) => host.Value.PublicBaseUrl.TrimEnd('/') + "/invite#" + token;
public static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))).ToLowerInvariant();
/// <summary>Mints an invite and returns the token, which exists only in this result.</summary>
public async Task<(ChatInvite Invite, string Token)> MintAsync(Guid issuedBy, string note, CancellationToken cancellationToken)
{
var token = WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
var now = time.GetUtcNow();
var invite = new ChatInvite
{
TokenHash = Hash(token),
Note = note.Trim(),
IssuedByUserAccountId = issuedBy,
IssuedAtUtc = now,
ExpiresAtUtc = now + Lifetime
};
db.ChatInvites.Add(invite);
await audit.RecordAsync(issuedBy, EntityType, invite.Id, "chat.invite.minted", $"Minted a chat invite: {invite.Note}", cancellationToken);
return (invite, token);
}
/// <summary>Revokes an unredeemed invite. False when it is absent or already redeemed or revoked.</summary>
public async Task<bool> RevokeAsync(Guid inviteId, Guid revokedBy, CancellationToken cancellationToken)
{
var invite = await db.ChatInvites.SingleOrDefaultAsync(x => x.Id == inviteId, cancellationToken);
if (invite is null || invite.RedeemedAtUtc is not null || invite.RevokedAtUtc is not null)
{
return false;
}
invite.RevokedAtUtc = time.GetUtcNow();
try
{
await audit.RecordAsync(revokedBy, EntityType, invite.Id, "chat.invite.revoked", $"Revoked a chat invite: {invite.Note}", cancellationToken);
}
catch (DbUpdateConcurrencyException)
{
db.ChangeTracker.Clear();
return false;
}
return true;
}
/// <summary>The unredeemed, unrevoked invites, newest first (expired ones included, so they can be revoked and seen).</summary>
public Task<List<ChatInvite>> PendingAsync(CancellationToken cancellationToken) =>
db.ChatInvites.AsNoTracking()
.Where(x => x.RedeemedAtUtc == null && x.RevokedAtUtc == null)
.OrderByDescending(x => x.IssuedAtUtc)
.ToListAsync(cancellationToken);
/// <summary>True when the token names an invite that is unredeemed, unrevoked and unexpired now.</summary>
public async Task<bool> IsLiveAsync(string token, CancellationToken cancellationToken)
{
var now = time.GetUtcNow();
var hash = Hash(token);
var invite = await db.ChatInvites.AsNoTracking().SingleOrDefaultAsync(x => x.TokenHash == hash, cancellationToken);
return invite is not null && invite.RedeemedAtUtc is null && invite.RevokedAtUtc is null && invite.ExpiresAtUtc > now;
}
/// <summary>
/// The one reading of "invited", for every decision that asks it (token, userinfo, redemption): a redeemed chat invite, an invite carried by an
/// account merged into this one, or an Active membership. Derived at read time, never copied to MAS or Synapse. The account needs its Membership loaded.
/// </summary>
public static async Task<bool> IsInvitedAsync(BifrostDbContext db, UserAccount account, CancellationToken cancellationToken) =>
account.ChatInvitedAtUtc is not null || new CurrentBifrostActor(true, account).IsActiveMember
|| await Bifrost.Web.Features.Membership.AccountMergeLedger.CarriedInviteAsync(db, account.Id, cancellationToken) is not null;
public void Carry(HttpContext http, string token) =>
http.Response.Cookies.Append(CookieName, token, CookieOptions(CookieLifetime));
/// <summary>
/// The one redemption, called after every sign-in. A request carrying the cookie spends the invite onto this account in one save and
/// clears the cookie. An account that is already invited, or an Active member, keeps the invite unspent. A second account with the same
/// link is refused: the save is conditional on the invite still being unredeemed, so a race has one winner.
/// </summary>
public async Task RedeemCarriedAsync(HttpContext http, Guid accountId, CancellationToken cancellationToken)
{
if (!http.Request.Cookies.TryGetValue(CookieName, out var token) || string.IsNullOrEmpty(token))
{
return;
}
http.Response.Cookies.Delete(CookieName, CookieOptions(null));
var now = time.GetUtcNow();
var hash = Hash(token);
var invite = await db.ChatInvites.SingleOrDefaultAsync(x => x.TokenHash == hash, cancellationToken);
var account = await db.UserAccounts.Include(x => x.Membership).SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
if (invite is null || account is null
|| invite.RedeemedAtUtc is not null || invite.RevokedAtUtc is not null || invite.ExpiresAtUtc <= now
|| await IsInvitedAsync(db, account, cancellationToken))
{
return;
}
invite.RedeemedByUserAccountId = account.Id;
invite.RedeemedAtUtc = now;
account.ChatInvitedAtUtc = now;
try
{
await audit.RecordAsync(account.Id, EntityType, invite.Id, "chat.invite.redeemed", $"Redeemed a chat invite: {invite.Note}", cancellationToken);
}
catch (DbUpdateConcurrencyException)
{
// Another account spent it first, or it was revoked in between: nothing of this attempt is kept.
db.ChangeTracker.Clear();
}
}
private static CookieOptions CookieOptions(TimeSpan? maxAge) => new()
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Lax,
Path = BifrostCookies.Path,
MaxAge = maxAge
};
}