Chat invites: an operator-minted single-use link decides who may chat; an uninvited account gets no chat token (#89)

This commit is contained in:
Eureka 2026-11-27 21:15:47 +00:00
commit 5d9fc14598
28 changed files with 1286 additions and 184 deletions

View file

@ -239,6 +239,47 @@ Rollback signs members out again (the old release reads the old cookie names); s
`pg_restore` from it, then `shred -u` the copy and `rmdir $S`; readback `test ! -e $S`. The dump itself stays root-only.
6. Leave the failed release directory for diagnosis; do not delete it in the window.
## Rolling back the chat invite release
Release `hands/bifrost-chat-invite` drops `MembershipInvitations` and adds `ChatInvites` and `UserAccounts.ChatInvitedAtUtc`
(migration `20261127120000_AddChatInvites`). So the symlink move above is **not enough** after it has migrated: the previous
binary reads `MembershipInvitations` on every GitHub sign-in and throws. Roll back the schema with the binary.
The host has no `dotnet ef`, so the migration's `Down` is applied as the SQL below, by the `postgres` superuser against the
`bifrost` database, with the service stopped. It recreates the old table empty and removes the new ones, in one transaction.
**It discards every minted invite and every redemption**, and the invited fact on each account; the operator mints
the invites again on the next release.
```sql
BEGIN;
DROP TABLE "ChatInvites";
ALTER TABLE "UserAccounts" DROP COLUMN "ChatInvitedAtUtc";
CREATE TABLE "MembershipInvitations" (
"Id" uuid NOT NULL,
"GitHubLogin" character varying(120) NOT NULL,
"NormalizedGitHubLogin" character varying(120) NOT NULL,
"IssuedByUserAccountId" uuid NULL,
"AcceptedByUserAccountId" uuid NULL,
"IssuedAtUtc" timestamp with time zone NOT NULL,
"AcceptedAtUtc" timestamp with time zone NULL,
"RevokedAtUtc" timestamp with time zone NULL,
"Notes" text NOT NULL,
CONSTRAINT "PK_MembershipInvitations" PRIMARY KEY ("Id"),
CONSTRAINT "FK_MembershipInvitations_UserAccounts_AcceptedByUserAccountId" FOREIGN KEY ("AcceptedByUserAccountId") REFERENCES "UserAccounts" ("Id") ON DELETE SET NULL,
CONSTRAINT "FK_MembershipInvitations_UserAccounts_IssuedByUserAccountId" FOREIGN KEY ("IssuedByUserAccountId") REFERENCES "UserAccounts" ("Id") ON DELETE SET NULL
);
CREATE INDEX "IX_MembershipInvitations_AcceptedByUserAccountId" ON "MembershipInvitations" ("AcceptedByUserAccountId");
CREATE INDEX "IX_MembershipInvitations_IssuedByUserAccountId" ON "MembershipInvitations" ("IssuedByUserAccountId");
CREATE UNIQUE INDEX "IX_MembershipInvitations_NormalizedGitHubLogin" ON "MembershipInvitations" ("NormalizedGitHubLogin");
DELETE FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20261127120000_AddChatInvites';
COMMIT;
```
Then point `/srv/bifrost/app/current` at the previous release and start it, as in Rollback. Go **only this far**: the same release
also brings `AddAccountMergeSaga`, whose `Down` refuses while any merge row exists, so never roll
the schema back past `20261114140000_AddAccountMergeNoticeAcks` once a merge has been made. The live-PG test
`Reverting_the_migration_is_refused_while_any_merge_exists` pins that refusal and the `Down` through `AddChatInvites`.
## What this plan does not do
It does not deploy, does not add an Idunn recipe, and does not touch `bifrost-watchdog-notice.timer`. The

View file

@ -44,8 +44,8 @@ user stay attached.
interval, l.34) ends sessions of suspended or deleted subjects, never of a chat-tier account for lacking membership.
- `MemberRole` (`StandardMember`, `Producer`, `Maintainer`, `LedgerReviewer`, `PlatformAdmin`) are capability
roles a member holds in addition. They are not the new field.
- Invites are `MembershipInvitation`, keyed by GitHub login (`MembershipSynchronizationService.cs:39-41`,
`Members/Index.cshtml.cs:69-71`). A guest may have no GitHub login at all.
- Chat invites are `ChatInvite` (see `oidc-issuer.md`, Chat invites), not keyed to any login;
a guest may have no GitHub login at all.
- Heimdall sign-in (`HeimdallAuthService.StartAsync`) with `requireMemberAccess = false` already creates an
identity-only account at `Authenticated`; with member access it creates `Active`.
- Nothing exists for room grants, leaving, erasing, or any "estate" in code (estates are rulings and research
@ -76,8 +76,8 @@ read" would have to be derived in three places. One stored field is one reading.
## Invite shape
New table `GuestInvitation`, separate from `MembershipInvitation` (which is GitHub-login-keyed and leads to
approval, not to a guest). Fields:
New table `GuestInvitation`, separate from `ChatInvite` (which leads to chat, and
not to a guest). Fields:
| field | rule |
|---|---|

View file

@ -71,7 +71,11 @@ The authorize endpoint reads the cookie session and the same actor facts the `/A
the return path carries only a short `request_uri`, so `LocalReturnPath.MaxLength` stays 256.
- Signed in, membership `Suspended`: redirect to the client's `redirect_uri` with `error=access_denied` and
`error_description=The account is suspended.`
- Signed in with no membership, `Authenticated` or `PendingApproval` (the chat tier): treated like an active member for
- Signed in, not suspended, with no `ChatInvitedAtUtc` and a membership that is not `Active` (the chat tier before an invite):
`error=access_denied` with `error_description=Chat is by invitation. Open an invite link, then sign in, to chat.`
(`OidcEndpoints.NotInvitedDescription`). This follows the suspension and identity refusals and comes before the consent redirect,
so an uninvited account is never invited to agree. A desk token (every scope a desk scope) asks no invite.
- Signed in, invited or `Active`, with no membership or `Authenticated` or `PendingApproval` (the chat tier): treated like an active member for
sign-in to chat and nothing else. The token carries the same `openid profile` claims; the issuer writes no membership,
role or vote, and every member or governance surface (`/App`, `/eve/governance`, `/api/sealed-motions`, the fork desk)
still asks for `Active` itself, so neither the session nor the token opens them.
@ -97,9 +101,29 @@ The authorize endpoint reads the cookie session and the same actor facts the `/A
(this path does not revoke the token; the back-channel reconciler below does, when it is configured). There is no refresh token, so refresh needs no gate.
The logout reconciler ends the sessions of those same accounts; a chat-tier account is never logged out for lacking membership.
## Chat invites
Who may chat is decided here, by the issuer, and nowhere else: an account holding `UserAccount.ChatInvitedAtUtc` or an `Active`
membership. "Invited" is derived at token time (authorize, token, userinfo, the logout reconciler: `ChatRefusalAsync`) and is never
copied to MAS or Synapse. Native registration and Heimdall sign-in create accounts that can use the Mill and the member pages; they do not
reach chat on their own.
- A member with `CanManageMembership` mints an invite on the Members page with a note. The link `https://<host>/invite#<token>` is shown
once, on the response to the mint. The token is 32 random bytes; only its SHA-256 (`ChatInvite.TokenHash`) is stored. An invite is valid
for 14 days, single use, and can be revoked until redeemed. The audit trail records `chat.invite.minted`, `chat.invite.redeemed` and
`chat.invite.revoked`. The payment ledger will later mint the same record through `ChatInviteService.MintAsync`.
- `GET /invite` serves a page that reads the token from the URL fragment (never sent to a server, so in no request line, access log, error log or Referer) and posts it to `POST /invite`. A live invite sets a one-hour `HttpOnly`, `Secure`, `SameSite=Lax` cookie (`__Host-bifrost_chat_invite`) holding
the token and redirects to the sign-in chooser. Anything else (unknown, expired, revoked, redeemed) gets one page, `This link is not valid`,
with status 404 and no cookie.
- Redemption has one owner, `ChatInviteService.RedeemCarriedAsync`, called after the Heimdall completion signs in and after native
registration signs in. A request carrying the cookie spends the invite onto the signed-in account (`ChatInvitedAtUtc`, `RedeemedByUserAccountId`)
in one save conditioned on the invite still being unredeemed and unrevoked, so of two accounts racing for one link one loses. The cookie
is cleared either way. An account that is already invited, or `Active`, keeps the invite unspent. GitHub OAuth sign-in redeems nothing, so `/auth/sign-in?provider=github` answers 409 with the sign-ins that do while the cookie is carried. A merge carries no copy of the fact: an account counts as invited while any merge standing into it folded an invited account (`AccountMergeLedger.CarriedInviteAsync`), so undoing merges in any order leaves what the standing merges give.
- Sessions that were open for an uninvited, non-`Active` account end at the logout reconciler's next pass, as for any refusal read by `ChatRefusalAsync`.
## Chat needs a receipt
The issuer is the chat tier: every token it issues is a chat token. Ruled by Meta, 2026-11-11: speaking in chat needs agreement
The issuer is the chat tier: every token it issues is a chat token. Ruled by Meta, 2026-11-11: speaking in chat needs an invite (above) and agreement
to the training notice, and nothing else does. A live `ConsentReceipt` for `TrainingNotice.Version` is required (the same
reading as the consent page's "agreed", `ConsentEndpoints.HasLiveReceiptAsync`); account sign-in, the members page and votes need no
receipt. A member with no receipt keeps all of those and loses only the chat token until they agree on the consent page.

View file

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Bifrost.Web.Tests" />
<PackageReference Include="MessagePack" Version="3.1.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>

View file

@ -19,7 +19,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
public DbSet<TierSnapshot> TierSnapshots => Set<TierSnapshot>();
public DbSet<MembershipInvitation> MembershipInvitations => Set<MembershipInvitation>();
public DbSet<ChatInvite> ChatInvites => Set<ChatInvite>();
public DbSet<Project> Projects => Set<Project>();
@ -152,18 +152,21 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
.HasForeignKey(x => x.MembershipId);
});
modelBuilder.Entity<MembershipInvitation>(entity =>
modelBuilder.Entity<ChatInvite>(entity =>
{
entity.HasIndex(x => x.NormalizedGitHubLogin).IsUnique();
entity.Property(x => x.GitHubLogin).HasMaxLength(120);
entity.Property(x => x.NormalizedGitHubLogin).HasMaxLength(120);
entity.HasOne(x => x.IssuedByUserAccount)
entity.HasIndex(x => x.TokenHash).IsUnique();
entity.Property(x => x.TokenHash).HasMaxLength(64);
entity.Property(x => x.Note).HasMaxLength(500);
// The single-use fact: a redemption saves `WHERE RedeemedAtUtc IS NULL`, so of two racing accounts one save loses.
entity.Property(x => x.RedeemedAtUtc).IsConcurrencyToken();
entity.Property(x => x.RevokedAtUtc).IsConcurrencyToken();
entity.HasOne<UserAccount>()
.WithMany()
.HasForeignKey(x => x.IssuedByUserAccountId)
.OnDelete(DeleteBehavior.SetNull);
entity.HasOne(x => x.AcceptedByUserAccount)
entity.HasOne<UserAccount>()
.WithMany()
.HasForeignKey(x => x.AcceptedByUserAccountId)
.HasForeignKey(x => x.RedeemedByUserAccountId)
.OnDelete(DeleteBehavior.SetNull);
});

View file

@ -0,0 +1,105 @@
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bifrost.Web.Data.Migrations
{
// Hand-written like AddAccountMergeNoticeAcks (no dotnet-ef on the authoring host), the snapshot edited to match.
// MembershipInvitations (keyed to a GitHub login, matched only on a GitHub sign-in) is dropped: the live table held zero rows
// when this was written (read 2026-11-27 on the production database), so nothing is carried over. Down recreates the empty table.
[DbContext(typeof(BifrostDbContext))]
[Migration("20261127120000_AddChatInvites")]
public partial class AddChatInvites : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(name: "MembershipInvitations");
migrationBuilder.AddColumn<DateTimeOffset>(
name: "ChatInvitedAtUtc",
table: "UserAccounts",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.CreateTable(
name: "ChatInvites",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
TokenHash = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
Note = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
IssuedByUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
IssuedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
ExpiresAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
RedeemedByUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
RedeemedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
RevokedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ChatInvites", x => x.Id);
table.ForeignKey(
name: "FK_ChatInvites_UserAccounts_IssuedByUserAccountId",
column: x => x.IssuedByUserAccountId,
principalTable: "UserAccounts",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "FK_ChatInvites_UserAccounts_RedeemedByUserAccountId",
column: x => x.RedeemedByUserAccountId,
principalTable: "UserAccounts",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateIndex(name: "IX_ChatInvites_IssuedByUserAccountId", table: "ChatInvites", column: "IssuedByUserAccountId");
migrationBuilder.CreateIndex(name: "IX_ChatInvites_RedeemedByUserAccountId", table: "ChatInvites", column: "RedeemedByUserAccountId");
migrationBuilder.CreateIndex(name: "IX_ChatInvites_TokenHash", table: "ChatInvites", column: "TokenHash", unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(name: "ChatInvites");
migrationBuilder.DropColumn(name: "ChatInvitedAtUtc", table: "UserAccounts");
migrationBuilder.CreateTable(
name: "MembershipInvitations",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
GitHubLogin = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: false),
NormalizedGitHubLogin = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: false),
IssuedByUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
AcceptedByUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
IssuedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
AcceptedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
RevokedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
Notes = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MembershipInvitations", x => x.Id);
table.ForeignKey(
name: "FK_MembershipInvitations_UserAccounts_AcceptedByUserAccountId",
column: x => x.AcceptedByUserAccountId,
principalTable: "UserAccounts",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "FK_MembershipInvitations_UserAccounts_IssuedByUserAccountId",
column: x => x.IssuedByUserAccountId,
principalTable: "UserAccounts",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateIndex(name: "IX_MembershipInvitations_AcceptedByUserAccountId", table: "MembershipInvitations", column: "AcceptedByUserAccountId");
migrationBuilder.CreateIndex(name: "IX_MembershipInvitations_IssuedByUserAccountId", table: "MembershipInvitations", column: "IssuedByUserAccountId");
migrationBuilder.CreateIndex(name: "IX_MembershipInvitations_NormalizedGitHubLogin", table: "MembershipInvitations", column: "NormalizedGitHubLogin", unique: true);
}
}
}

View file

@ -1033,51 +1033,52 @@ namespace Bifrost.Web.Data.Migrations
b.ToTable("Memberships");
});
modelBuilder.Entity("Bifrost.Web.Domain.MembershipInvitation", b =>
modelBuilder.Entity("Bifrost.Web.Domain.ChatInvite", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("AcceptedAtUtc")
b.Property<DateTimeOffset>("ExpiresAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("AcceptedByUserAccountId")
.HasColumnType("uuid");
b.Property<string>("GitHubLogin")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<DateTimeOffset>("IssuedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("IssuedByUserAccountId")
.HasColumnType("uuid");
b.Property<string>("NormalizedGitHubLogin")
b.Property<string>("Note")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<string>("Notes")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("RedeemedAtUtc")
.IsConcurrencyToken()
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("RedeemedByUserAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("RevokedAtUtc")
.IsConcurrencyToken()
.HasColumnType("timestamp with time zone");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.HasKey("Id");
b.HasIndex("AcceptedByUserAccountId");
b.HasIndex("IssuedByUserAccountId");
b.HasIndex("NormalizedGitHubLogin")
b.HasIndex("RedeemedByUserAccountId");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("MembershipInvitations");
b.ToTable("ChatInvites");
});
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
@ -1558,6 +1559,9 @@ namespace Bifrost.Web.Data.Migrations
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<DateTimeOffset?>("ChatInvitedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedAtUtc")
.HasColumnType("timestamp with time zone");
@ -2513,21 +2517,17 @@ namespace Bifrost.Web.Data.Migrations
b.Navigation("UserAccount");
});
modelBuilder.Entity("Bifrost.Web.Domain.MembershipInvitation", b =>
modelBuilder.Entity("Bifrost.Web.Domain.ChatInvite", b =>
{
b.HasOne("Bifrost.Web.Domain.UserAccount", "AcceptedByUserAccount")
.WithMany()
.HasForeignKey("AcceptedByUserAccountId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("Bifrost.Web.Domain.UserAccount", "IssuedByUserAccount")
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
.WithMany()
.HasForeignKey("IssuedByUserAccountId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("AcceptedByUserAccount");
b.Navigation("IssuedByUserAccount");
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
.WithMany()
.HasForeignKey("RedeemedByUserAccountId")
.OnDelete(DeleteBehavior.SetNull);
});
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>

View file

@ -266,6 +266,9 @@ public sealed class UserAccount
public DateTimeOffset LastSeenAtUtc { get; set; }
/// <summary>When a chat invite was redeemed onto this account. Bifrost's OIDC issuer reads it (or Active membership) to decide who gets a chat token.</summary>
public DateTimeOffset? ChatInvitedAtUtc { get; set; }
public MemberProfile? MemberProfile { get; set; }
public Membership? Membership { get; set; }
@ -413,29 +416,30 @@ public sealed class TierSnapshot
public Membership Membership { get; set; } = null!;
}
public sealed class MembershipInvitation
/// <summary>
/// An operator-minted, single-use invitation to chat. The link carries a 32-byte random token; only its SHA-256 is stored.
/// Redeemed onto the account that signs in carrying it (UserAccount.ChatInvitedAtUtc); Bifrost's OIDC issuer reads that fact.
/// </summary>
public sealed class ChatInvite
{
public Guid Id { get; set; } = Guid.NewGuid();
public string GitHubLogin { get; set; } = string.Empty;
/// <summary>Lowercase hex SHA-256 of the token; the token itself is shown once at minting and never stored.</summary>
public string TokenHash { get; set; } = string.Empty;
public string NormalizedGitHubLogin { get; set; } = string.Empty;
public string Note { get; set; } = string.Empty;
public Guid? IssuedByUserAccountId { get; set; }
public Guid? AcceptedByUserAccountId { get; set; }
public DateTimeOffset IssuedAtUtc { get; set; }
public DateTimeOffset? AcceptedAtUtc { get; set; }
public DateTimeOffset ExpiresAtUtc { get; set; }
public Guid? RedeemedByUserAccountId { get; set; }
public DateTimeOffset? RedeemedAtUtc { get; set; }
public DateTimeOffset? RevokedAtUtc { get; set; }
public string Notes { get; set; } = string.Empty;
public UserAccount? IssuedByUserAccount { get; set; }
public UserAccount? AcceptedByUserAccount { get; set; }
}
public sealed class Project

View file

@ -0,0 +1,144 @@
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
};
}

View file

@ -95,6 +95,18 @@ public sealed class AccountMergeLedger(
public Task<MergeStanding?> StandingAsync(Guid userAccountId, CancellationToken cancellationToken) =>
StandingAsync(dbContext, userAccountId, cancellationToken);
/// <summary>
/// The earliest chat-invite time among the accounts folded into this one by merges that stand now (landed, not undone). Derived from
/// the merge state on every call, never copied onto the survivor, so undoing merges in any order leaves exactly the merges still standing.
/// </summary>
public static async Task<DateTimeOffset?> CarriedInviteAsync(BifrostDbContext db, Guid survivorId, CancellationToken cancellationToken) =>
await db.AccountMerges.AsNoTracking()
.Where(m => m.SurvivorUserAccountId == survivorId && FoldedStates.Contains(m.State))
.Join(db.UserAccounts, m => m.FoldedUserAccountId, a => a.Id, (m, a) => a.ChatInvitedAtUtc)
.Where(at => at != null)
.OrderBy(at => at)
.FirstOrDefaultAsync(cancellationToken);
/// <summary>The single reading of standing, shared by the actor accessor and the OIDC refusal, which holds only a context. Derived from the merge state on every call.</summary>
public static async Task<MergeStanding?> StandingAsync(BifrostDbContext db, Guid userAccountId, CancellationToken cancellationToken)
{

View file

@ -36,11 +36,6 @@ public sealed class MembershipSynchronizationService(
.ThenInclude(x => x.TierSnapshots)
.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
var invitation = await dbContext.MembershipInvitations
.SingleOrDefaultAsync(
x => x.NormalizedGitHubLogin == normalizedLogin && x.RevokedAtUtc == null,
cancellationToken);
if (userAccount is null)
{
userAccount = new UserAccount
@ -60,7 +55,7 @@ public sealed class MembershipSynchronizationService(
},
Membership = new Bifrost.Web.Domain.Membership
{
Status = invitation is null ? MembershipStatus.Authenticated : MembershipStatus.PendingApproval,
Status = MembershipStatus.Authenticated,
CreatedAtUtc = now
}
};
@ -88,11 +83,6 @@ public sealed class MembershipSynchronizationService(
UserAccountId = userAccount.Id,
CreatedAtUtc = now
};
if (invitation is not null && userAccount.Membership.Status == MembershipStatus.Authenticated)
{
userAccount.Membership.Status = MembershipStatus.PendingApproval;
}
}
if (string.IsNullOrWhiteSpace(userAccount.MemberProfile!.Nickname))
@ -105,12 +95,6 @@ public sealed class MembershipSynchronizationService(
userAccount.GitHubLogin,
cancellationToken);
if (invitation is not null && invitation.AcceptedByUserAccountId is null)
{
invitation.AcceptedByUserAccountId = userAccount.Id;
invitation.AcceptedAtUtc = now;
}
MembershipStatus? promotedFrom = null;
if (IsBootstrapAdmin(gitHubLogin, bootstrapOptions.Value))
{

View file

@ -17,7 +17,7 @@ namespace Bifrost.Web.Features.Oidc;
/// <summary>
/// The decisions Bifrost owns at the OIDC provider: who the chat user is (sub = UserAccount.Id,
/// preferred_username = NormalizedBifrostIdentity) and whether they may get a session (membership Active).
/// preferred_username = NormalizedBifrostIdentity) and whether they may get a session (invited or Active, not suspended).
/// OpenIddict does the protocol; these endpoints read the cookie session and the same actor facts the /App policy reads.
/// </summary>
public static class OidcEndpoints
@ -27,6 +27,7 @@ public static class OidcEndpoints
public const string NoIdentityDescription = "The account has no Bifrost identity.";
public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved.";
public const string ConsentRequiredDescription = "Agreement to the training notice in force is needed to speak in a recorded room.";
public const string NotInvitedDescription = "Chat is by invitation. Open an invite link, then sign in, to chat.";
private const string OpenIddictScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
private const string IdentityAuthenticationType = "Bifrost.Oidc";
@ -53,7 +54,7 @@ public static class OidcEndpoints
}
var actor = await actors.GetAsync(http.RequestAborted);
// Chat tier: any account that is not suspended may sign in to chat. Membership is neither required nor written;
// Chat tier: an invited account or an Active member that is not suspended may sign in to chat (the invite check is below). Membership is neither required nor written;
// every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
if (actor.UserAccount is null)
{
@ -102,6 +103,13 @@ public static class OidcEndpoints
_ => [Destinations.AccessToken]
});
// Chat is by invitation: a chat token goes only to an invited account or an Active member, and an account that is neither is not
// sent on to agree to a notice. Read again at token and userinfo time by ChatRefusalAsync; a desk token asks no invite.
if (!IsDeskToken(principal) && !await Bifrost.Web.Features.Invites.ChatInviteService.IsInvitedAsync(db, account, http.RequestAborted))
{
return Deny(Errors.AccessDenied, NotInvitedDescription);
}
// The training notice is the chat's: a desk token is not a chat token and needs no receipt (Meta's ruling, 2026-11-11).
// Last, so a refusal that no agreement can cure (suspended, no identity, reserved) is never answered with an invitation to agree.
// Not an OIDC error: the member is sent to the consent page with this request's resume path, and the parked request
@ -160,7 +168,7 @@ public static class OidcEndpoints
/// <summary>
/// The one reading of "this subject may still chat", shared by the token and userinfo endpoints and the logout reconciler:
/// null when they may, else the description of why not. The account exists, its membership is not Suspended (absent, pending
/// or Active all chat), and, for a chat token (not a desk token), it holds a live receipt for the notice version in force. Re-read on every call.
/// or Active all chat), and, for a chat token (not a desk token), it is invited (ChatInvitedAtUtc or Active) and holds a live receipt for the notice version in force. Re-read on every call.
/// </summary>
internal static async Task<string?> ChatRefusalAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken, bool deskToken = false)
{
@ -183,7 +191,17 @@ public static class OidcEndpoints
return MergedDescription;
}
return deskToken || await ConsentEndpoints.HasLiveReceiptAsync(db, accountId, cancellationToken) ? null : ConsentRequiredDescription;
if (deskToken)
{
return null;
}
if (!await Bifrost.Web.Features.Invites.ChatInviteService.IsInvitedAsync(db, account, cancellationToken))
{
return NotInvitedDescription;
}
return await ConsentEndpoints.HasLiveReceiptAsync(db, accountId, cancellationToken) ? null : ConsentRequiredDescription;
}
/// <summary>The account id of the subject when it is an Active member now, else null. The door to the fork desk (cookie surfaces check IsActiveMember); a chat-tier token does not pass it. Re-read on every call.</summary>

View file

@ -42,7 +42,8 @@ public sealed record RegistrationOutcome(
public sealed class NativeRegistration(
BifrostIdentityService identities,
RegistrationChallengeService challenges,
RegistrationRateLimit rateLimit)
RegistrationRateLimit rateLimit,
Bifrost.Web.Features.Invites.ChatInviteService chatInvites)
{
public async Task<RegistrationOutcome> RunAsync(HttpContext http, RegistrationAttempt attempt, CancellationToken cancellationToken)
{
@ -113,6 +114,7 @@ public sealed class NativeRegistration(
{
var account = await identities.RegisterNativeAsync(attempt.Identity ?? "", attempt.DisplayName, attempt.AcceptedNoticeVersion, cancellationToken);
await http.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identities.BuildPrincipal(account));
await chatInvites.RedeemCarriedAsync(http, account.Id, cancellationToken);
return new(account, null, StatusCodes.Status200OK, null, RegistrationField.None, false);
}
catch (BifrostIdentityException error)

View file

@ -8,9 +8,9 @@
<section class="panel-grid">
<article class="panel">
<span class="eyebrow">Members</span>
<h1>Invite and approval gate</h1>
<h1>Chat invites and approval gate</h1>
<p class="panel-intro">
Invite-first onboarding keeps the alpha intentionally small. Approval remains human
Chat is by invitation: mint a single-use link and send it yourself. Approval remains human
because trust and contributor accountability are product concerns, not just auth concerns.
</p>
@ -21,22 +21,24 @@
@if (Model.Actor.CanManageMembership)
{
@if (Model.MintedLink is not null)
{
<div class="callout success" role="status">
Invite link, shown once. Send it to one person; it works for 14 days and one account.
<p><code>@Model.MintedLink</code></p>
</div>
}
<form method="post" asp-page-handler="Invite">
<div asp-validation-summary="ModelOnly" class="validation-summary-errors"></div>
<div class="form-grid">
<div class="field">
<label asp-for="Input.GitHubLogin"></label>
<input asp-for="Input.GitHubLogin" />
<span asp-validation-for="Input.GitHubLogin"></span>
</div>
<div class="field">
<label asp-for="Input.Notes"></label>
<input asp-for="Input.Notes" />
<span asp-validation-for="Input.Notes"></span>
<label asp-for="Input.Note"></label>
<input asp-for="Input.Note" />
<span asp-validation-for="Input.Note"></span>
</div>
</div>
<div class="panel-actions">
<button class="button" type="submit">Issue invite</button>
<button class="button" type="submit">Mint chat invite link</button>
</div>
</form>
}
@ -247,18 +249,20 @@
</div>
}
</section>
@if (Model.Actor.CanManageMembership)
{
<section class="table-panel" style="margin-top: 1.5rem;">
<div class="panel-header" style="padding: 1.25rem 1.25rem 0;">
<div>
<h2>Outstanding invites</h2>
<p class="table-meta">@Model.Invitations.Count active invitations tracked.</p>
<h2>Outstanding chat invites</h2>
<p class="table-meta">@Model.Invitations.Count unredeemed.</p>
</div>
</div>
@if (Model.Invitations.Count == 0)
{
<div class="empty-state" style="margin: 1.25rem;">No invitations yet.</div>
<div class="empty-state" style="margin: 1.25rem;">No unredeemed invites.</div>
}
else
{
@ -266,24 +270,24 @@
<table>
<thead>
<tr>
<th>GitHub login</th>
<th>For</th>
<th>Issued</th>
<th>Accepted</th>
<th>Notes</th>
<th>Expires</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var invitation in Model.Invitations)
@foreach (var invite in Model.Invitations)
{
<tr>
<td>@invitation.GitHubLogin</td>
<td>@invitation.IssuedAtUtc.ToString("dd MMM yyyy HH:mm") UTC</td>
<td>@invite.Note</td>
<td>@invite.IssuedAtUtc.ToString("dd MMM yyyy HH:mm") UTC</td>
<td>@invite.ExpiresAtUtc.ToString("dd MMM yyyy HH:mm") UTC</td>
<td>
@(invitation.AcceptedAtUtc is null
? "Waiting for sign-in"
: invitation.AcceptedAtUtc.Value.ToString("dd MMM yyyy HH:mm") + " UTC")
<form method="post" asp-page-handler="RevokeInvite" asp-route-inviteId="@invite.Id">
<button class="button secondary" type="submit">Revoke</button>
</form>
</td>
<td>@invitation.Notes</td>
</tr>
}
</tbody>
@ -291,6 +295,7 @@
</div>
}
</section>
}
@section Scripts {
<partial name="_ValidationScriptsPartial" />

View file

@ -1,6 +1,7 @@
using System.ComponentModel.DataAnnotations;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Invites;
using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.Mvc;
@ -14,10 +15,11 @@ public sealed class IndexModel(
ICurrentBifrostActorAccessor actorAccessor,
AuditTrailService auditTrailService,
MembershipSuspensionService suspension,
ChatInviteService chatInvites,
TimeProvider timeProvider) : PageModel
{
[BindProperty]
public InviteMemberInput Input { get; set; } = new();
public MintInviteInput Input { get; set; } = new();
[BindProperty]
public UpdateProfileInput Profile { get; set; } = new();
@ -47,7 +49,10 @@ public sealed class IndexModel(
public IReadOnlyList<MemberDirectoryItem> Users { get; private set; } = [];
public IReadOnlyList<MembershipInvitation> Invitations { get; private set; } = [];
public IReadOnlyList<ChatInvite> Invitations { get; private set; } = [];
/// <summary>The link just minted, present only on the response to the mint.</summary>
public string? MintedLink { get; private set; }
public async Task OnGetAsync(CancellationToken cancellationToken)
{
@ -62,53 +67,30 @@ public sealed class IndexModel(
return Forbid();
}
if (!ModelState.IsValid)
// The mint form carries only the note, so only the note is checked: ModelState also holds the profile form's required fields, which this post never sends.
if (string.IsNullOrWhiteSpace(Input.Note) || Input.Note.Length > 500)
{
ModelState.AddModelError($"{nameof(Input)}.{nameof(Input.Note)}", "Say who this invite is for, in at most 500 characters.");
await LoadAsync(cancellationToken);
return Page();
}
var normalizedLogin = Input.GitHubLogin.Trim().ToUpperInvariant();
var invitation = await dbContext.MembershipInvitations
.SingleOrDefaultAsync(x => x.NormalizedGitHubLogin == normalizedLogin, cancellationToken);
var (_, token) = await chatInvites.MintAsync(Actor.UserAccount.Id, Input.Note, cancellationToken);
// The link is shown once, on this response: no redirect, no TempData, nothing stored that could show it again.
MintedLink = chatInvites.LinkFor(token);
await LoadAsync(cancellationToken);
return Page();
}
if (invitation is null)
public async Task<IActionResult> OnPostRevokeInviteAsync(Guid inviteId, CancellationToken cancellationToken)
{
Actor = await actorAccessor.GetAsync(cancellationToken);
if (!Actor.CanManageMembership || Actor.UserAccount is null)
{
invitation = new MembershipInvitation
{
GitHubLogin = Input.GitHubLogin.Trim(),
NormalizedGitHubLogin = normalizedLogin,
IssuedByUserAccountId = Actor.UserAccount.Id,
IssuedAtUtc = timeProvider.GetUtcNow(),
Notes = Input.Notes.Trim()
};
dbContext.MembershipInvitations.Add(invitation);
}
else
{
invitation.RevokedAtUtc = null;
invitation.Notes = Input.Notes.Trim();
return Forbid();
}
var existingUser = await dbContext.UserAccounts
.Include(x => x.Membership)
.SingleOrDefaultAsync(x => x.NormalizedGitHubLogin == normalizedLogin, cancellationToken);
if (existingUser?.Membership is not null && existingUser.Membership.Status == MembershipStatus.Authenticated)
{
existingUser.Membership.Status = MembershipStatus.PendingApproval;
}
await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
Actor.UserAccount.Id,
nameof(MembershipInvitation),
invitation.Id,
"membership.invited",
$"Issued invite for {invitation.GitHubLogin}.",
cancellationToken);
await chatInvites.RevokeAsync(inviteId, Actor.UserAccount.Id, cancellationToken);
return RedirectToPage();
}
@ -415,11 +397,7 @@ public sealed class IndexModel(
contributorTier?.Weight ?? 0m);
}).ToList();
Invitations = await dbContext.MembershipInvitations
.AsNoTracking()
.Where(x => x.RevokedAtUtc == null)
.OrderByDescending(x => x.IssuedAtUtc)
.ToListAsync(cancellationToken);
Invitations = Actor.CanManageMembership ? await chatInvites.PendingAsync(cancellationToken) : [];
if (Actor.UserAccount is not null)
{
@ -449,14 +427,11 @@ public sealed class IndexModel(
membership.CanModerateMotions = membership.IsPlatformAdmin || roles.Contains(MemberRole.Producer) || roles.Contains(MemberRole.Maintainer);
}
public sealed class InviteMemberInput
public sealed class MintInviteInput
{
[Required, StringLength(120)]
[Display(Name = "GitHub login")]
public string GitHubLogin { get; set; } = string.Empty;
[StringLength(500)]
public string Notes { get; set; } = string.Empty;
[Display(Name = "Who is this for")]
public string Note { get; set; } = string.Empty;
}
public sealed class UpdateProfileInput

View file

@ -40,14 +40,6 @@
</div>
}
@if (Model.Invitation is not null)
{
<div class="callout success">
Invitation tracked for <code>@Model.Invitation.GitHubLogin</code>.
Issued @Model.Invitation.IssuedAtUtc.ToString("dd MMM yyyy") UTC.
</div>
}
<div class="panel-actions">
@if (Model.Actor.IsActiveMember)
{

View file

@ -22,8 +22,6 @@ public sealed class StatusModel(
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
public MembershipInvitation? Invitation { get; private set; }
public string StatusLabel => Actor.Membership?.Status switch
{
MembershipStatus.Active => "Active member",
@ -44,9 +42,9 @@ public sealed class StatusModel(
public string StatusMessage => Actor.Membership?.Status switch
{
MembershipStatus.Active => "You can participate in projects, claim work, vote on motions, and view the ledger console.",
MembershipStatus.PendingApproval => "Your GitHub sign-in matched an invite, but an admin still needs to approve active participation.",
MembershipStatus.PendingApproval => "An admin still needs to approve active participation.",
MembershipStatus.Suspended => "Your account is currently suspended from active participation pending an admin review.",
MembershipStatus.Authenticated => "You are signed in, but there is no active invite or approval on your account yet.",
MembershipStatus.Authenticated => "You are signed in, but there is no approval on your account yet.",
_ => "No membership record was found."
};
@ -56,17 +54,5 @@ public sealed class StatusModel(
HasMerges = Actor.Merge is not null
|| (Actor.UserAccount is { } account
&& await dbContext.AccountMerges.AnyAsync(x => x.SurvivorUserAccountId == account.Id || x.FoldedUserAccountId == account.Id, cancellationToken));
if (Actor.UserAccount is null)
{
return;
}
Invitation = await dbContext.MembershipInvitations
.AsNoTracking()
.SingleOrDefaultAsync(
x => x.NormalizedGitHubLogin == Actor.UserAccount.NormalizedGitHubLogin &&
x.RevokedAtUtc == null,
cancellationToken);
}
}

View file

@ -138,6 +138,7 @@ builder.Services.AddOptions<RegistrationOptions>().BindConfiguration(Registratio
builder.Services.AddSingleton<RegistrationChallengeService>();
builder.Services.AddSingleton<RegistrationRateLimit>();
builder.Services.AddScoped<NativeRegistration>();
builder.Services.AddScoped<Bifrost.Web.Features.Invites.ChatInviteService>();
builder.Services.AddHostedService<SealedBallotCloser>();
builder.Services.AddOptions<AccountMergeOptions>().BindConfiguration(AccountMergeOptions.SectionName);
builder.Services.AddScoped<Bifrost.Web.Features.Membership.AccountMergeLedger>();
@ -374,6 +375,76 @@ app.MapPost("/github/webhooks", async (
};
}).AllowAnonymous();
// The invite link is /invite#<token>: the token sits in the fragment, which no browser sends, so it never reaches a request line,
// an access log, an error log or a Referer. The page reads it and posts it (the body is not logged); a live invite sets a short cookie
// and goes to the sign-in chooser, anything else gets one page with no detail. The cookie is spent by ChatInviteService.RedeemCarriedAsync after any sign-in.
app.MapGet("/invite", (HttpContext httpContext) =>
{
httpContext.Response.Headers.CacheControl = "no-store";
// same-origin, not no-referrer: a no-referrer page posts its form with Origin: null, which RequestOriginGuard refuses. The fragment is never in a Referer,
// and same-origin sends the Referer to this site only.
httpContext.Response.Headers["Referrer-Policy"] = "same-origin";
return Results.Content(
"""
<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Invite - Bifrost</title></head>
<body><main><h1>Opening your invite</h1>
<form id="f" method="post" action="/invite"><input type="hidden" name="token" id="t" /><noscript><p>This page needs JavaScript to open your invite.</p></noscript></form>
<script>
var h = location.hash.slice(1);
if (h) { history.replaceState(null, "", "/invite"); document.getElementById("t").value = h; document.getElementById("f").submit(); }
else { document.querySelector("h1").textContent = "This link is not valid"; }
</script></main></body></html>
""",
"text/html; charset=utf-8");
}).AllowAnonymous();
// The post is refused cross-site by RequestOriginGuard (no antiforgery cookie exists for a visitor, so a foreign page could otherwise plant
// its own invite in this browser), and its body is capped to what a token needs before any of it is read.
app.MapPost("/invite", async (HttpContext httpContext, Bifrost.Web.Features.Invites.ChatInviteService invites, IOptions<BifrostHostOptions> hostOptions, CancellationToken cancellationToken) =>
{
httpContext.Response.Headers.CacheControl = "no-store";
httpContext.Response.Headers["Referrer-Policy"] = "no-referrer";
if (!RequestOriginGuard.Allows(httpContext.Request, hostOptions.Value))
{
return Results.Text("Cross-site invite links are refused.", statusCode: StatusCodes.Status403Forbidden);
}
const int MaxInviteBodyBytes = 1024;
if (httpContext.Request.ContentLength > MaxInviteBodyBytes)
{
return Results.Text("Too large.", statusCode: StatusCodes.Status413PayloadTooLarge);
}
if (httpContext.Features.Get<Microsoft.AspNetCore.Http.Features.IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } limit)
{
limit.MaxRequestBodySize = MaxInviteBodyBytes; // a chunked body with no declared length is cut at the same cap
}
string token;
try
{
token = httpContext.Request.HasFormContentType ? (await httpContext.Request.ReadFormAsync(cancellationToken))["token"].ToString() : string.Empty;
}
catch (Microsoft.AspNetCore.Http.BadHttpRequestException)
{
return Results.Text("Too large.", statusCode: StatusCodes.Status413PayloadTooLarge);
}
if (token.Length is 0 or > 200 || !await invites.IsLiveAsync(token, cancellationToken))
{
return Results.Content(
"""
<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Invite - Bifrost</title></head>
<body><main><h1>This link is not valid</h1></main></body></html>
""",
"text/html; charset=utf-8",
statusCode: StatusCodes.Status404NotFound);
}
invites.Carry(httpContext, token);
return Results.Redirect("/auth/sign-in?returnUrl=%2F");
}).AllowAnonymous();
app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuthOptions> gitHubOptions) =>
{
var returnPath = LocalReturnPath.Parse(httpContext.Request.Query["returnUrl"].ToString());
@ -391,6 +462,20 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuth
return;
}
// GitHub sign-in spends no invite: its account is made by the per-request sync, and redeeming there would hook every request.
// A visitor carrying an invite is told which sign-ins redeem it, instead of being signed in and refused at chat.
if (httpContext.Request.Cookies.ContainsKey(Bifrost.Web.Features.Invites.ChatInviteService.CookieName))
{
httpContext.Response.StatusCode = StatusCodes.Status409Conflict;
httpContext.Response.ContentType = "text/html; charset=utf-8";
await httpContext.Response.WriteAsync(
$"""
<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Sign in - Bifrost</title></head>
<body><main><h1>Use Discord, Patreon or Twitch to accept this invite</h1><p>GitHub sign-in cannot accept a chat invite. <a href="/auth/sign-in?returnUrl={Uri.EscapeDataString(returnPath.Value)}">Choose another sign-in</a>.</p></main></body></html>
""");
return;
}
if (!gitHubOptions.Value.IsConfigured)
{
httpContext.Response.Redirect("/?auth=github-not-configured");
@ -835,6 +920,7 @@ app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
app.MapPost("/auth/heimdall/complete", async (
HttpContext httpContext,
HeimdallAuthService heimdallAuthService,
Bifrost.Web.Features.Invites.ChatInviteService chatInvites,
IOptions<BifrostHostOptions> hostOptions,
ILogger<HeimdallAuthService> logger,
CancellationToken cancellationToken) =>
@ -893,6 +979,11 @@ app.MapPost("/auth/heimdall/complete", async (
form?["code"].ToString(),
cancellationToken);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, signIn.Principal);
if (Guid.TryParse(signIn.Principal.FindFirstValue(ClaimTypes.NameIdentifier), out var signedInAccountId))
{
await chatInvites.RedeemCarriedAsync(httpContext, signedInAccountId, cancellationToken);
}
httpContext.Response.Cookies.Delete(held!.Value.Name, HeimdallAttemptCookie.DeleteOptions());
return Results.LocalRedirect(signIn.ReturnPath.Value);
}
@ -978,6 +1069,10 @@ static async Task WriteSignInChooserAsync(HttpContext httpContext, string return
httpContext.Response.ContentType = "text/html; charset=utf-8";
var encodedReturnUrl = Uri.EscapeDataString(returnUrl);
var escapedReturnUrl = System.Net.WebUtility.HtmlEncode(returnUrl);
// GitHub sign-in spends no invite (only Heimdall completion and native registration call RedeemCarriedAsync), so a visitor carrying one is not offered it.
var gitHubChoice = httpContext.Request.Cookies.ContainsKey(Bifrost.Web.Features.Invites.ChatInviteService.CookieName)
? string.Empty
: $"""<a href="/auth/sign-in?provider=github&returnUrl={encodedReturnUrl}">GitHub <span>OAuth</span></a>""";
await httpContext.Response.WriteAsync($$"""
<!doctype html>
<html lang="en">
@ -1002,7 +1097,7 @@ static async Task WriteSignInChooserAsync(HttpContext httpContext, string return
<h1>Create or use a Bifrost patron account</h1>
<p>Choose a provider to attach this checkout to a Bifrost account. Patron accounts do not automatically grant active member access.</p>
<div class="providers">
<a href="/auth/sign-in?provider=github&returnUrl={{encodedReturnUrl}}">GitHub <span>OAuth</span></a>
{{gitHubChoice}}
<a class="secondary" href="/auth/heimdall/discord?returnUrl={{encodedReturnUrl}}">Discord <span>Heimdall</span></a>
<a class="secondary" href="/auth/heimdall/patreon?returnUrl={{encodedReturnUrl}}">Patreon <span>Heimdall</span></a>
<a class="secondary" href="/auth/heimdall/twitch?returnUrl={{encodedReturnUrl}}">Twitch <span>Heimdall</span></a>

View file

@ -53,7 +53,7 @@ public sealed class MergePostgres : IAsyncLifetime
public Task InitializeAsync() => Task.CompletedTask;
/// <summary>A fresh database, built by the real migrations, and a world over it.</summary>
public async Task<AccountMergeLedgerTests.World> NewWorldAsync()
public async Task<AccountMergeLedgerTests.World> NewWorldAsync(params Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesInterceptor[] interceptors)
{
var name = $"bifrost_merge_{Guid.NewGuid():N}";
await using (var admin = new NpgsqlConnection(Admin))
@ -64,7 +64,7 @@ public sealed class MergePostgres : IAsyncLifetime
}
_databases.Add(name);
var world = AccountMergeLedgerTests.World.OnPostgres(new NpgsqlConnectionStringBuilder(Admin) { Database = name }.ConnectionString);
var world = AccountMergeLedgerTests.World.OnPostgres(new NpgsqlConnectionStringBuilder(Admin) { Database = name }.ConnectionString, interceptors);
await using var db = world.Db();
await db.Database.MigrateAsync();
return world;
@ -416,7 +416,7 @@ public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFi
await down.GetService<IMigrator>().MigrateAsync("20261113120000_AddPasskeyCredentials");
Assert.Equal("20261113120000_AddPasskeyCredentials", (await down.Database.GetAppliedMigrationsAsync()).Last());
await down.GetService<IMigrator>().MigrateAsync(); // and up again, trigger and index and all
Assert.Equal("20261114140000_AddAccountMergeNoticeAcks", (await down.Database.GetAppliedMigrationsAsync()).Last());
Assert.Equal(down.Database.GetMigrations().Last(), (await down.Database.GetAppliedMigrationsAsync()).Last()); // the newest the assembly knows, whatever it is
}
// ---- restage and intake journal ----

View file

@ -147,7 +147,7 @@ public sealed class BootstrapAdminTests
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
var actor = new CurrentBifrostActor(true, await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments).SingleAsync(x => x.Id == by));
var page = new IndexModel(db, new FixedActor(actor), scope.ServiceProvider.GetRequiredService<AuditTrailService>(),
scope.ServiceProvider.GetRequiredService<MembershipSuspensionService>(), TimeProvider.System);
scope.ServiceProvider.GetRequiredService<MembershipSuspensionService>(), scope.ServiceProvider.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>(), TimeProvider.System);
Assert.IsType<RedirectToPageResult>(await page.OnPostToggleRoleAsync(target, role, CancellationToken.None));
}

View file

@ -0,0 +1,539 @@
using System.Net;
using System.Text.RegularExpressions;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Invites;
using Bifrost.Web.Tests.Support;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace Bifrost.Web.Tests;
/// <summary>The Members page mints, lists and revokes chat invites; only a membership manager may. The link is shown once.</summary>
public sealed class ChatInviteMintTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
{
private static readonly Regex Link = new("https://localhost/invite#([A-Za-z0-9_-]+)", RegexOptions.Compiled);
private HttpClient Client(string? bifrostIdentity = null)
{
var client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
BaseAddress = new Uri("https://localhost"),
HandleCookies = true
});
if (bifrostIdentity is not null)
{
client.DefaultRequestHeaders.Add("X-Test-Bifrost-Identity", bifrostIdentity);
}
return client;
}
private static async Task<string> AntiforgeryAsync(HttpClient client)
{
var html = await (await client.GetAsync("/App/Members")).Content.ReadAsStringAsync();
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
Assert.True(token.Length > 0, html.Length > 3000 ? html[..3000] : html);
return token;
}
private static async Task<HttpResponseMessage> PostAsync(HttpClient client, string handler, Dictionary<string, string> fields)
{
fields["__RequestVerificationToken"] = await AntiforgeryAsync(client);
return await client.PostAsync($"/App/Members?handler={handler}", new FormUrlEncodedContent(fields));
}
private async Task SeedActiveMemberAsync(string identity)
{
using var scope = factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
db.UserAccounts.Add(new UserAccount
{
DisplayName = identity, BifrostIdentity = identity, NormalizedBifrostIdentity = identity,
Membership = new Bifrost.Web.Domain.Membership { Status = MembershipStatus.Active, ApprovedAtUtc = DateTimeOffset.UtcNow }
});
await db.SaveChangesAsync();
}
private async Task<List<ChatInvite>> RowsAsync()
{
using var scope = factory.Services.CreateScope();
return await scope.ServiceProvider.GetRequiredService<BifrostDbContext>().ChatInvites.AsNoTracking().ToListAsync();
}
private async Task<List<string>> AuditActionsAsync()
{
using var scope = factory.Services.CreateScope();
return await scope.ServiceProvider.GetRequiredService<BifrostDbContext>().AuditEvents.AsNoTracking()
.Where(x => x.EntityType == ChatInviteService.EntityType).Select(x => x.Action).ToListAsync();
}
[Fact]
public async Task A_manager_mints_a_link_shown_once_lists_it_and_revokes_it()
{
var admin = Client();
using var _ = await admin.GetAsync("/App/Members"); // sign-in sync creates and promotes the bootstrap admin
var before = (await RowsAsync()).Count;
using var minted = await PostAsync(admin, "Invite", new() { ["Input.Note"] = "for Ada" });
Assert.Equal(HttpStatusCode.OK, minted.StatusCode);
var html = await minted.Content.ReadAsStringAsync();
var token = Link.Match(html).Groups[1].Value;
Assert.True(token.Length > 0, "no invite link on the mint response");
var row = Assert.Single((await RowsAsync()).Where(x => x.Note == "for Ada"));
Assert.Equal(ChatInviteService.Hash(token), row.TokenHash);
Assert.Equal(before + 1, (await RowsAsync()).Count);
Assert.Equal(row.IssuedAtUtc + ChatInviteService.Lifetime, row.ExpiresAtUtc);
// Shown once: the list names the note and a revoke, never the link.
var again = await (await admin.GetAsync("/App/Members")).Content.ReadAsStringAsync();
Assert.Contains("for Ada", again);
Assert.DoesNotContain(token, again);
using var revoked = await PostAsync(admin, "RevokeInvite", new() { ["inviteId"] = row.Id.ToString() });
Assert.Equal(HttpStatusCode.Redirect, revoked.StatusCode);
Assert.NotNull(Assert.Single((await RowsAsync()).Where(x => x.Id == row.Id)).RevokedAtUtc);
using var opened = await Client().OpenInviteAsync(token);
Assert.Equal(HttpStatusCode.NotFound, opened.StatusCode);
Assert.Contains("chat.invite.minted", await AuditActionsAsync());
Assert.Contains("chat.invite.revoked", await AuditActionsAsync());
}
[Fact]
public async Task A_member_who_is_not_a_manager_cannot_mint_or_revoke()
{
var identity = $"plain-{Guid.NewGuid():N}"[..20];
await SeedActiveMemberAsync(identity);
var plain = Client(identity);
var before = (await RowsAsync()).Count;
using var mint = await PostAsync(plain, "Invite", new() { ["Input.Note"] = "nope" });
Assert.Equal(HttpStatusCode.Found, mint.StatusCode); // Forbid() redirects to the access-denied path
Assert.Contains("/Membership/Status", mint.Headers.Location!.OriginalString);
var admin = Client();
using var _ = await admin.GetAsync("/App/Members");
using var minted = await PostAsync(admin, "Invite", new() { ["Input.Note"] = "keep" });
var keep = Assert.Single((await RowsAsync()).Where(x => x.Note == "keep"));
using var revoke = await PostAsync(plain, "RevokeInvite", new() { ["inviteId"] = keep.Id.ToString() });
Assert.Equal(HttpStatusCode.Found, revoke.StatusCode);
Assert.Contains("/Membership/Status", revoke.Headers.Location!.OriginalString);
Assert.Null(Assert.Single((await RowsAsync()).Where(x => x.Id == keep.Id)).RevokedAtUtc);
Assert.Equal(before + 1, (await RowsAsync()).Count);
Assert.DoesNotContain("keep", await (await plain.GetAsync("/App/Members")).Content.ReadAsStringAsync());
}
[Fact]
public async Task The_token_never_travels_in_a_request_line_the_link_keeps_it_in_the_fragment()
{
var admin = Client();
using var _ = await admin.GetAsync("/App/Members");
using var minted = await PostAsync(admin, "Invite", new() { ["Input.Note"] = "fragment" });
var html = await minted.Content.ReadAsStringAsync();
var token = Link.Match(html).Groups[1].Value;
Assert.Contains("/invite#" + token, html);
// The landing page carries no token and posts what its fragment holds; the old path form opens nothing.
using var page = await Client().GetAsync("/invite");
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
var body = await page.Content.ReadAsStringAsync();
Assert.DoesNotContain(token, body);
Assert.Contains("location.hash", body);
// The page's policy decides what Origin its form posts with: no-referrer would make it "null", which the guard refuses (see the Origin: null test).
Assert.Equal("same-origin", Assert.Single(page.Headers.GetValues("Referrer-Policy")));
using var oldPath = await Client().GetAsync("/invite/" + token);
Assert.Equal(HttpStatusCode.NotFound, oldPath.StatusCode);
Assert.False(oldPath.Headers.Contains("Set-Cookie"));
}
[Fact]
public async Task The_chooser_a_carried_invite_lands_on_offers_only_the_sign_ins_that_redeem_it()
{
var admin = Client();
using var _ = await admin.GetAsync("/App/Members");
using var minted = await PostAsync(admin, "Invite", new() { ["Input.Note"] = "chooser" });
var token = Link.Match(await minted.Content.ReadAsStringAsync()).Groups[1].Value;
var visitor = Client();
var plain = await (await visitor.GetAsync("/auth/sign-in?returnUrl=%2F")).Content.ReadAsStringAsync();
Assert.Contains("provider=github", plain);
using var landed = await visitor.OpenInviteAsync(token);
Assert.Equal(HttpStatusCode.Redirect, landed.StatusCode);
var carried = await (await visitor.GetAsync(landed.Headers.Location)).Content.ReadAsStringAsync();
Assert.DoesNotContain("provider=github", carried);
Assert.Contains("/auth/heimdall/discord", carried);
// The hand-typed URL is refused with the way forward; without the cookie it is not.
using var typed = await visitor.GetAsync("/auth/sign-in?provider=github&returnUrl=%2F");
Assert.Equal(HttpStatusCode.Conflict, typed.StatusCode);
Assert.Contains("Discord, Patreon or Twitch", await typed.Content.ReadAsStringAsync());
using var bare = await Client().GetAsync("/auth/sign-in?provider=github&returnUrl=%2F");
Assert.NotEqual(HttpStatusCode.Conflict, bare.StatusCode);
}
}
/// <summary>A Heimdall sign-in carrying the invite cookie spends the invite onto the account that signed in.</summary>
public sealed class ChatInviteHeimdallTests
{
private static async Task<string> MintAsync(HeimdallHost host)
{
using var scope = host.Services.CreateScope();
var (_, token) = await scope.ServiceProvider.GetRequiredService<ChatInviteService>().MintAsync(Guid.NewGuid(), "via heimdall", CancellationToken.None);
return token;
}
[Fact]
public async Task A_new_heimdall_account_carrying_the_cookie_is_invited_once_and_the_cookie_is_cleared()
{
using var host = new HeimdallHost();
var token = await MintAsync(host);
var jar = ChatInviteService.CookieName + "=" + token;
var first = HeimdallShapes.NewAccountId();
var attempt = await host.StartAsync();
var done = await host.CompleteWithHeaderAsync(attempt.Nonce, host.CodeFor(attempt, first), $"{attempt.CookieName}={attempt.Cookie}; {jar}");
Assert.True(done.SignedIn);
var account = await host.Account(first);
Assert.NotNull(account!.ChatInvitedAtUtc);
var row = await host.Db(db => db.ChatInvites.AsNoTracking().SingleAsync(x => x.TokenHash == ChatInviteService.Hash(token)));
Assert.Equal(account.Id, row.RedeemedByUserAccountId);
var cleared = HeimdallHost.SetCookieHeader(done.Response, ChatInviteService.CookieName);
Assert.NotNull(cleared);
Assert.Contains("1970", cleared);
// A second account carrying the same link signs in but is not invited.
var second = HeimdallShapes.NewAccountId();
var again = await host.StartAsync();
var refused = await host.CompleteWithHeaderAsync(again.Nonce, host.CodeFor(again, second), $"{again.CookieName}={again.Cookie}; {jar}");
Assert.True(refused.SignedIn);
Assert.Null((await host.Account(second))!.ChatInvitedAtUtc);
Assert.Equal(account.Id, (await host.Db(db => db.ChatInvites.AsNoTracking().SingleAsync(x => x.TokenHash == ChatInviteService.Hash(token)))).RedeemedByUserAccountId);
Assert.NotNull((await host.Account(first))!.ChatInvitedAtUtc);
Assert.Contains("chat.invite.redeemed", await host.Db(db => db.AuditEvents.AsNoTracking().Select(x => x.Action).ToListAsync()));
}
[Fact]
public async Task An_invite_revoked_after_its_link_was_carried_redeems_nothing()
{
using var host = new HeimdallHost();
string token;
using (var scope = host.Services.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<ChatInviteService>();
var (invite, minted) = await service.MintAsync(Guid.NewGuid(), "revoked in flight", CancellationToken.None);
token = minted;
Assert.True(await service.RevokeAsync(invite.Id, Guid.NewGuid(), CancellationToken.None));
}
var accountId = HeimdallShapes.NewAccountId();
var attempt = await host.StartAsync();
var done = await host.CompleteWithHeaderAsync(attempt.Nonce, host.CodeFor(attempt, accountId), $"{attempt.CookieName}={attempt.Cookie}; {ChatInviteService.CookieName}={token}");
Assert.True(done.SignedIn);
Assert.Null((await host.Account(accountId))!.ChatInvitedAtUtc);
Assert.Null((await host.Db(db => db.ChatInvites.AsNoTracking().SingleAsync(x => x.TokenHash == ChatInviteService.Hash(token)))).RedeemedAtUtc);
}
[Fact]
public async Task A_heimdall_sign_in_without_the_cookie_is_not_invited()
{
using var host = new HeimdallHost();
await MintAsync(host);
var accountId = HeimdallShapes.NewAccountId();
var attempt = await host.StartAsync();
var done = await host.CompleteAsync(attempt, host.CodeFor(attempt, accountId));
Assert.True(done.SignedIn);
Assert.Null((await host.Account(accountId))!.ChatInvitedAtUtc);
}
}
/// <summary>The single-use fact rests on a concurrency token and the migration, which the in-memory provider does not enforce: proven on a real server (skipped without BIFROST_TEST_PG).</summary>
public sealed class ChatInvitePostgresTests(MergePostgres postgres) : IClassFixture<MergePostgres>
{
[PostgresFact]
public async Task Two_accounts_racing_for_one_link_leave_it_with_exactly_one_and_the_token_is_stored_only_hashed()
{
var world = await postgres.NewWorldAsync();
var time = TimeProvider.System;
const string token = "race-token-0123456789";
Guid first, second;
await using (var seed = world.Db())
{
var a = new UserAccount { BifrostIdentity = "racer-a", NormalizedBifrostIdentity = "racer-a", DisplayName = "A" };
var b = new UserAccount { BifrostIdentity = "racer-b", NormalizedBifrostIdentity = "racer-b", DisplayName = "B" };
seed.UserAccounts.AddRange(a, b);
seed.ChatInvites.Add(new ChatInvite { TokenHash = ChatInviteService.Hash(token), Note = "race", IssuedAtUtc = time.GetUtcNow(), ExpiresAtUtc = time.GetUtcNow().AddDays(1) });
await seed.SaveChangesAsync();
(first, second) = (a.Id, b.Id);
}
async Task Redeem(Guid account)
{
await using var db = world.Db();
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
http.Request.Headers.Cookie = ChatInviteService.CookieName + "=" + token;
var options = Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions());
await new ChatInviteService(db, new Bifrost.Web.Features.Shared.AuditTrailService(db, time), time, options).RedeemCarriedAsync(http, account, CancellationToken.None);
}
await Task.WhenAll(Task.Run(() => Redeem(first)), Task.Run(() => Redeem(second)));
await using var read = world.Db();
var invite = await read.ChatInvites.AsNoTracking().SingleAsync();
Assert.NotNull(invite.RedeemedByUserAccountId);
Assert.Equal(1, await read.UserAccounts.CountAsync(x => x.ChatInvitedAtUtc != null));
Assert.Equal(invite.RedeemedByUserAccountId, (await read.UserAccounts.SingleAsync(x => x.ChatInvitedAtUtc != null)).Id);
Assert.Equal(1, await read.AuditEvents.CountAsync(x => x.Action == "chat.invite.redeemed"));
}
/// <summary>Holds each redemption's save until both have loaded the invite, so the interleave the concurrency token exists for is forced, not left to timing.</summary>
private sealed class BothLoadedBeforeEitherSaves : Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesInterceptor
{
private int _arrived;
private readonly TaskCompletionSource _both = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override async ValueTask<Microsoft.EntityFrameworkCore.Diagnostics.InterceptionResult<int>> SavingChangesAsync(
Microsoft.EntityFrameworkCore.Diagnostics.DbContextEventData eventData,
Microsoft.EntityFrameworkCore.Diagnostics.InterceptionResult<int> result,
CancellationToken cancellationToken = default)
{
if (eventData.Context!.ChangeTracker.Entries<ChatInvite>().Any(x => x.State == EntityState.Modified))
{
if (Interlocked.Increment(ref _arrived) == 2)
{
_both.TrySetResult();
}
await _both.Task.WaitAsync(TimeSpan.FromSeconds(20), cancellationToken);
}
return result;
}
}
[PostgresFact]
public async Task Two_redemptions_that_both_loaded_the_invite_before_either_saved_still_leave_it_with_one()
{
var world = await postgres.NewWorldAsync(new BothLoadedBeforeEitherSaves());
var time = TimeProvider.System;
const string token = "interleave-token-0123456789";
Guid first, second;
await using (var seed = world.Db())
{
var a = new UserAccount { BifrostIdentity = "inter-a", NormalizedBifrostIdentity = "inter-a", DisplayName = "A" };
var b = new UserAccount { BifrostIdentity = "inter-b", NormalizedBifrostIdentity = "inter-b", DisplayName = "B" };
seed.UserAccounts.AddRange(a, b);
seed.ChatInvites.Add(new ChatInvite { TokenHash = ChatInviteService.Hash(token), Note = "interleave", IssuedAtUtc = time.GetUtcNow(), ExpiresAtUtc = time.GetUtcNow().AddDays(1) });
await seed.SaveChangesAsync();
(first, second) = (a.Id, b.Id);
}
async Task Redeem(Guid account)
{
await using var db = world.Db();
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
http.Request.Headers.Cookie = ChatInviteService.CookieName + "=" + token;
var options = Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions());
await new ChatInviteService(db, new Bifrost.Web.Features.Shared.AuditTrailService(db, time), time, options).RedeemCarriedAsync(http, account, CancellationToken.None);
}
await Task.WhenAll(Task.Run(() => Redeem(first)), Task.Run(() => Redeem(second)));
await using var read = world.Db();
var invite = await read.ChatInvites.AsNoTracking().SingleAsync();
var invited = await read.UserAccounts.Where(x => x.ChatInvitedAtUtc != null).Select(x => x.Id).ToListAsync();
Assert.Single(invited);
Assert.Equal(invite.RedeemedByUserAccountId, invited[0]);
Assert.Equal(1, await read.AuditEvents.CountAsync(x => x.Action == "chat.invite.redeemed"));
}
}
/// <summary>An account merge leaves the person invited while the merge stands: the fact is read from the merges that stand, never copied, so undo in any order leaves what the surviving merges give.</summary>
public sealed class ChatInviteMergeTests
{
private static readonly DateTimeOffset Early = new(2026, 11, 1, 9, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset Late = new(2026, 11, 10, 9, 0, 0, TimeSpan.Zero);
private static async Task<UserAccount> AccountAsync(AccountMergeLedgerTests.World world, string name, DateTimeOffset? invitedAt = null)
{
var account = await world.AccountAsync(name, MembershipStatus.Authenticated);
if (invitedAt is { } at)
{
await using var db = world.Db();
(await db.UserAccounts.SingleAsync(x => x.Id == account.Id)).ChatInvitedAtUtc = at;
await db.SaveChangesAsync();
}
return account;
}
private static async Task<bool> RefusedAsNotInvitedAsync(AccountMergeLedgerTests.World world, UserAccount account)
{
await using var db = world.Db();
return await Bifrost.Web.Features.Oidc.OidcEndpoints.ChatRefusalAsync(db, account.Id.ToString(), default) == Bifrost.Web.Features.Oidc.OidcEndpoints.NotInvitedDescription;
}
private static async Task UndoAsync(AccountMergeLedgerTests.World world, AccountMerge merge)
{
await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed);
await using var db = world.Db();
await world.Ledger(db).UndoLocalAsync(merge.Id, default);
}
[Fact]
public async Task An_invited_account_folded_into_an_uninvited_survivor_leaves_the_person_invited_until_the_merge_is_undone()
{
var world = new AccountMergeLedgerTests.World();
var survivor = await AccountAsync(world, "survivor");
var folded = await AccountAsync(world, "folded", Early);
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
Assert.False(await RefusedAsNotInvitedAsync(world, survivor));
await UndoAsync(world, merge);
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
}
[Fact]
public async Task A_folded_account_that_was_never_invited_gives_the_survivor_nothing()
{
var world = new AccountMergeLedgerTests.World();
var survivor = await AccountAsync(world, "survivor");
var folded = await AccountAsync(world, "folded");
await world.CommitAsync(await world.MergeAsync(survivor, folded));
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Two_invited_accounts_merged_into_one_survivor_undone_in_either_order_leave_the_survivor_uninvited(bool earlierMergeFirst)
{
var world = new AccountMergeLedgerTests.World();
var survivor = await AccountAsync(world, "survivor");
var late = await AccountAsync(world, "late", Late);
var early = await AccountAsync(world, "early", Early);
var first = await world.CommitAsync(await world.MergeAsync(survivor, late));
var second = await world.CommitAsync(await world.MergeAsync(survivor, early));
await UndoAsync(world, earlierMergeFirst ? first : second);
Assert.False(await RefusedAsNotInvitedAsync(world, survivor)); // the other merge still stands
await UndoAsync(world, earlierMergeFirst ? second : first);
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
}
}
public static class InviteRequests
{
/// <summary>What a browser sends from the landing page's form under its Referrer-Policy: same-origin: the site's Origin and Sec-Fetch-Site: same-origin.</summary>
public static Task<HttpResponseMessage> OpenInviteAsync(this HttpClient client, string token, string? origin = "https://localhost", string? fetchSite = "same-origin", int padding = 0)
{
var request = new HttpRequestMessage(HttpMethod.Post, "/invite")
{
Content = new StringContent("token=" + token + new string('a', padding), System.Text.Encoding.UTF8, "application/x-www-form-urlencoded")
};
if (origin is not null)
{
request.Headers.Add("Origin", origin);
}
if (fetchSite is not null)
{
request.Headers.Add("Sec-Fetch-Site", fetchSite);
}
return client.SendAsync(request);
}
}
/// <summary>POST /invite plants a cookie, so a foreign page must not be able to make the post, and the body is only as big as a token.</summary>
public sealed class ChatInvitePostTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
{
private HttpClient Client() => factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, BaseAddress = new Uri("https://localhost"), HandleCookies = false });
private async Task<string> MintAsync()
{
using var scope = factory.Services.CreateScope();
var (_, token) = await scope.ServiceProvider.GetRequiredService<ChatInviteService>().MintAsync(Guid.NewGuid(), "post", CancellationToken.None);
return token;
}
[Fact]
public async Task A_cross_site_post_with_a_live_token_sets_no_cookie_and_the_same_origin_post_does()
{
var token = await MintAsync();
foreach (var (origin, site) in new (string?, string?)[] { ("https://evil.example", "cross-site"), (null, "cross-site"), (null, "same-site"), (null, null) })
{
using var refused = await Client().OpenInviteAsync(token, origin, site);
Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode);
Assert.False(refused.Headers.Contains("Set-Cookie"));
}
using var own = await Client().OpenInviteAsync(token);
Assert.Equal(HttpStatusCode.Redirect, own.StatusCode);
Assert.Contains(own.Headers.GetValues("Set-Cookie"), x => x.StartsWith(ChatInviteService.CookieName + "=", StringComparison.Ordinal));
using var fetch = await Client().OpenInviteAsync(token, origin: null, fetchSite: "same-origin");
Assert.Equal(HttpStatusCode.Redirect, fetch.StatusCode);
}
[Fact]
public async Task A_post_with_Origin_null_is_refused_which_is_why_the_page_must_not_send_no_referrer()
{
var token = await MintAsync();
using var refused = await Client().OpenInviteAsync(token, origin: "null", fetchSite: "same-origin");
Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode);
Assert.False(refused.Headers.Contains("Set-Cookie"));
}
[Fact]
public async Task A_body_bigger_than_a_token_needs_is_refused_unread()
{
var token = await MintAsync();
using var big = await Client().OpenInviteAsync(token, padding: 3_000_000);
Assert.Equal(HttpStatusCode.RequestEntityTooLarge, big.StatusCode);
Assert.False(big.Headers.Contains("Set-Cookie"));
}
}
/// <summary>Redemption asks the same question as every other decision: an account already invited through a merge spends no second invite.</summary>
public sealed class ChatInviteDerivedRedemptionTests
{
[Fact]
public async Task A_survivor_invited_through_a_merge_keeps_a_second_invite_unspent()
{
var world = new AccountMergeLedgerTests.World();
var survivor = await world.AccountAsync("survivor", MembershipStatus.Authenticated);
var folded = await world.AccountAsync("folded", MembershipStatus.Authenticated);
await using (var seed = world.Db())
{
(await seed.UserAccounts.SingleAsync(x => x.Id == folded.Id)).ChatInvitedAtUtc = new DateTimeOffset(2026, 11, 1, 9, 0, 0, TimeSpan.Zero);
await seed.SaveChangesAsync();
}
await world.CommitAsync(await world.MergeAsync(survivor, folded));
await using var db = world.Db();
var service = new ChatInviteService(db, new Bifrost.Web.Features.Shared.AuditTrailService(db, world.Clock), world.Clock,
Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions()));
var (invite, token) = await service.MintAsync(Guid.NewGuid(), "second", CancellationToken.None);
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
http.Request.Headers.Cookie = ChatInviteService.CookieName + "=" + token;
await service.RedeemCarriedAsync(http, survivor.Id, CancellationToken.None);
await using var read = world.Db();
var row = await read.ChatInvites.AsNoTracking().SingleAsync(x => x.Id == invite.Id);
Assert.Null(row.RedeemedAtUtc);
Assert.Null((await read.UserAccounts.AsNoTracking().SingleAsync(x => x.Id == survivor.Id)).ChatInvitedAtUtc);
}
}

View file

@ -195,6 +195,18 @@ public sealed class DeskCredentialTests : IDisposable
Assert.Empty(factory.Door.Calls);
}
[Fact]
public async Task A_desk_token_asks_no_chat_invite()
{
var (client, identity) = await SignedInAsync();
await factory.SetMembershipAsync(identity, MembershipStatus.Authenticated);
var request = NewRequest(DeskClient, DeskRedirect, "desk.read");
var code = await CodeAsync(client, request);
Assert.False(string.IsNullOrEmpty(code));
}
[Fact]
public async Task The_session_cookie_alone_authenticates_nothing_on_the_desk()
{

View file

@ -164,7 +164,7 @@ public sealed class MembershipSuspensionTests : IClassFixture<TestWebApplication
{
var page = new IndexModel(
db, new FixedActor(await ActorAsync(seed.AdminId)), sp.GetRequiredService<AuditTrailService>(),
sp.GetRequiredService<MembershipSuspensionService>(), TimeProvider.System);
sp.GetRequiredService<MembershipSuspensionService>(), sp.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>(), TimeProvider.System);
return await page.OnPostApproveAsync(seed.MemberId, CancellationToken.None);
});
@ -181,7 +181,7 @@ public sealed class MembershipSuspensionTests : IClassFixture<TestWebApplication
{
var page = new IndexModel(
db, new FixedActor(await ActorAsync(seed.OrdinaryId)), sp.GetRequiredService<AuditTrailService>(),
sp.GetRequiredService<MembershipSuspensionService>(), TimeProvider.System);
sp.GetRequiredService<MembershipSuspensionService>(), sp.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>(), TimeProvider.System);
return await page.OnPostSuspendAsync(seed.MemberId, "nope", CancellationToken.None);
});

View file

@ -32,6 +32,7 @@ public sealed class MigrationDiscoveryTests
"20261114120000_AddAccountMerges",
"20261114130000_AddAccountMergeSaga",
"20261114140000_AddAccountMergeNoticeAcks",
"20261127120000_AddChatInvites",
];
// Database.GetMigrations() reads assembly metadata only; no connection is opened.

View file

@ -192,6 +192,133 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
Assert.Equal(["name", "preferred_username", "sub"], info.EnumerateObject().Select(x => x.Name).Order().ToArray());
}
[Fact]
public async Task An_uninvited_account_gets_no_chat_token_at_authorize_or_exchange()
{
var (client, identity) = await SignedInAsync(MembershipStatus.Authenticated, "Not Invited", invited: false);
var request = NewRequest();
var redirect = AssertRedirectToClient(await DriveAsync(client, request), request.State);
Assert.Equal("access_denied", redirect["error"]);
Assert.Equal(Bifrost.Web.Features.Oidc.OidcEndpoints.NotInvitedDescription, redirect["error_description"]);
Assert.False(redirect.ContainsKey("code"));
// A code and a token issued while invited stop working when the invite is gone: the same reading at every endpoint.
await _factory.SetInvitedAsync(identity, true);
var pending = NewRequest();
var pendingCode = await CodeAsync(client, pending);
var tokens = await CompleteFlowAsync(client);
await _factory.SetInvitedAsync(identity, false);
using var exchange = await TokenAsync(client, pending, pendingCode);
var body = await exchange.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.BadRequest, exchange.StatusCode);
Assert.Contains("invalid_grant", body);
Assert.DoesNotContain("access_token", body);
using var userinfo = await UserInfoAsync(tokens.AccessToken);
Assert.Equal(HttpStatusCode.Forbidden, userinfo.StatusCode);
}
[Fact]
public async Task An_active_member_needs_no_invite()
{
var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Member", invited: false);
var tokens = await CompleteFlowAsync(client);
Assert.Equal(identity, (await ValidateIdTokenAsync(tokens.IdToken, tokens.Request.Nonce)).Claim("preferred_username"));
Assert.Null(await _factory.InvitedAtAsync(identity));
}
[Fact]
public async Task An_invite_link_is_redeemed_at_native_sign_in_once_and_the_cookie_is_cleared()
{
var token = await _factory.MintInviteAsync("first");
var client = NewClient();
using (var opened = await client.OpenInviteAsync(token))
{
Assert.Equal(HttpStatusCode.Redirect, opened.StatusCode);
var cookie = Assert.Single(opened.Headers.GetValues("Set-Cookie"), x => x.StartsWith(Bifrost.Web.Features.Invites.ChatInviteService.CookieName + "=", StringComparison.Ordinal));
Assert.Contains("httponly", cookie, StringComparison.OrdinalIgnoreCase);
Assert.Contains("samesite=lax", cookie, StringComparison.OrdinalIgnoreCase);
}
using var registered = await RegistrationKit.RegisterAsync(client, $"invited-{Guid.NewGuid():N}");
Assert.Equal(HttpStatusCode.OK, registered.StatusCode);
var identity = (await registered.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("bifrostIdentity").GetString()!.ToLowerInvariant();
Assert.NotNull(await _factory.InvitedAtAsync(identity));
var row = await _factory.InviteRowAsync(token);
Assert.Equal(_factory.AccountId(identity), row.RedeemedByUserAccountId);
Assert.Contains(registered.Headers.GetValues("Set-Cookie"), x =>
x.StartsWith(Bifrost.Web.Features.Invites.ChatInviteService.CookieName + "=;", StringComparison.Ordinal) && x.Contains("expires=", StringComparison.OrdinalIgnoreCase));
// Invited and agreed (registration carried the notice): chat works with no further step.
var tokens = await CompleteFlowAsync(client);
Assert.Equal(identity, (await ValidateIdTokenAsync(tokens.IdToken, tokens.Request.Nonce)).Claim("preferred_username"));
// Single use: a second account carrying the same token is refused and the first keeps it.
var other = NewClient();
other.DefaultRequestHeaders.Add("Cookie", Bifrost.Web.Features.Invites.ChatInviteService.CookieName + "=" + token);
using var second = await RegistrationKit.RegisterAsync(other, $"second-{Guid.NewGuid():N}");
var secondIdentity = (await second.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("bifrostIdentity").GetString()!.ToLowerInvariant();
Assert.Null(await _factory.InvitedAtAsync(secondIdentity));
Assert.Equal(_factory.AccountId(identity), (await _factory.InviteRowAsync(token)).RedeemedByUserAccountId);
Assert.NotNull(await _factory.InvitedAtAsync(identity));
}
[Fact]
public async Task An_expired_or_revoked_invite_sets_no_cookie_and_redeems_nothing()
{
var expired = await _factory.MintInviteAsync("expires");
var revoked = await _factory.MintInviteAsync("revoked");
using (var scope = _factory.Services.CreateScope())
{
var invites = scope.ServiceProvider.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>();
Assert.True(await invites.RevokeAsync((await _factory.InviteRowAsync(revoked)).Id, Guid.NewGuid(), CancellationToken.None));
}
_factory.Clock.Advance(Bifrost.Web.Features.Invites.ChatInviteService.Lifetime + TimeSpan.FromMinutes(1));
var fresh = await _factory.MintInviteAsync("fresh");
foreach (var token in new[] { expired, revoked, "not-a-token" })
{
using var client = NewClient();
using var opened = await client.OpenInviteAsync(token);
Assert.Equal(HttpStatusCode.NotFound, opened.StatusCode);
Assert.False(opened.Headers.Contains("Set-Cookie"));
Assert.DoesNotContain("expire", await opened.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
}
// A cookie carried anyway (set before the link lapsed) redeems nothing either.
var carried = NewClient();
carried.DefaultRequestHeaders.Add("Cookie", Bifrost.Web.Features.Invites.ChatInviteService.CookieName + "=" + expired);
using var registered = await RegistrationKit.RegisterAsync(carried, $"lapsed-{Guid.NewGuid():N}");
var identity = (await registered.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("bifrostIdentity").GetString()!.ToLowerInvariant();
Assert.Null(await _factory.InvitedAtAsync(identity));
Assert.Null((await _factory.InviteRowAsync(expired)).RedeemedAtUtc);
using var live = await NewClient().OpenInviteAsync(fresh);
Assert.Equal(HttpStatusCode.Redirect, live.StatusCode);
}
[Fact]
public async Task The_database_holds_only_the_token_hash()
{
var token = await _factory.MintInviteAsync("hashed");
var row = await _factory.InviteRowAsync(token);
Assert.Equal(Bifrost.Web.Features.Invites.ChatInviteService.Hash(token), row.TokenHash);
Assert.NotEqual(token, row.TokenHash);
Assert.Equal(64, row.TokenHash.Length);
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<Bifrost.Web.Data.BifrostDbContext>();
Assert.DoesNotContain(db.ChatInvites.AsNoTracking().AsEnumerable(), x => x.Note == token || x.TokenHash == token);
Assert.DoesNotContain(db.AuditEvents.AsNoTracking().AsEnumerable(), x => x.Detail.Contains(token));
}
[Fact]
public async Task A_chat_tier_account_with_a_reserved_identity_is_still_refused()
{
@ -1029,7 +1156,7 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
return identity.ToLowerInvariant();
}
private async Task<(HttpClient Client, string Identity)> SignedInAsync(MembershipStatus status, string displayName, ReceiptState receipt = ReceiptState.Current)
private async Task<(HttpClient Client, string Identity)> SignedInAsync(MembershipStatus status, string displayName, ReceiptState receipt = ReceiptState.Current, bool invited = true)
{
var client = NewClient();
var identity = await RegisterAsync(client, $"member-{Guid.NewGuid():N}", agree: receipt != ReceiptState.None);
@ -1040,6 +1167,7 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
await _factory.SetMembershipAsync(identity, status);
await _factory.SetDisplayNameAsync(identity, displayName);
await _factory.SetInvitedAsync(identity, invited);
return (client, identity);
}

View file

@ -414,6 +414,7 @@ public sealed class OidcLogoutFactory : OidcWebApplicationFactory
}
await SetMembershipAsync(identity, MembershipStatus.Active);
await SetInvitedAsync(identity, true);
if (suspensionReason is not null)
{
using var scope = Services.CreateScope();

View file

@ -276,6 +276,36 @@ public class OidcWebApplicationFactory : TestWebApplicationFactory
}
}
/// <summary>Marks the account as holding a redeemed chat invite (or clears it), as a redemption or a revoked grant would leave it.</summary>
public async Task SetInvitedAsync(string identity, bool invited)
{
using var scope = Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity).ChatInvitedAtUtc = invited ? DateTimeOffset.UtcNow : null;
await db.SaveChangesAsync();
}
/// <summary>Mints a chat invite through the one service and returns its token.</summary>
public async Task<string> MintInviteAsync(string note = "test")
{
using var scope = Services.CreateScope();
var (_, token) = await scope.ServiceProvider.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>().MintAsync(Guid.NewGuid(), note, CancellationToken.None);
return token;
}
public async Task<ChatInvite> InviteRowAsync(string token)
{
using var scope = Services.CreateScope();
var hash = Bifrost.Web.Features.Invites.ChatInviteService.Hash(token);
return await scope.ServiceProvider.GetRequiredService<BifrostDbContext>().ChatInvites.AsNoTracking().SingleAsync(x => x.TokenHash == hash);
}
public async Task<DateTimeOffset?> InvitedAtAsync(string identity)
{
using var scope = Services.CreateScope();
return (await scope.ServiceProvider.GetRequiredService<BifrostDbContext>().UserAccounts.AsNoTracking().SingleAsync(x => x.NormalizedBifrostIdentity == identity)).ChatInvitedAtUtc;
}
public Guid AccountId(string identity)
{
using var scope = Services.CreateScope();

View file

@ -60,7 +60,7 @@ public sealed class SuspensionReasonExposureTests
{
viewer.Membership!.IsPlatformAdmin = admin;
var model = new Bifrost.Web.Pages.App.Members.IndexModel(db, new FixedActor(new CurrentBifrostActor(true, viewer)),
sp.GetRequiredService<AuditTrailService>(), sp.GetRequiredService<MembershipSuspensionService>(), TimeProvider.System);
sp.GetRequiredService<AuditTrailService>(), sp.GetRequiredService<MembershipSuspensionService>(), sp.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>(), TimeProvider.System);
await model.OnGetAsync(CancellationToken.None);
return model.Users;
}