""");
+ }
+
+ string Invalid(RegistrationField field) => model.Error is not null && model.ErrorField == field ? " aria-invalid=\"true\" aria-describedby=\"errors\"" : "";
+ var wait = model.WaitSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
+
+ return $$"""
+
+
+
+
+
+ Create an account - Bifrost
+
+
+
+
+ Public registration
+
Create a Bifrost account
+
A new account can chat. It has no vote and opens no member or governance surface.
+ {{summary}}
+
+
Without a script, or if the automatic check is slow, wait {{wait}} seconds after the page opened and press the button to skip it (or Create account when there is no script). Pressed sooner, the page comes back saying how many seconds remain and keeps your names; the consent box comes back unchecked, so tick it again if you want to agree. Without the automatic check only a few registrations per hour are accepted from one address.
+
After registering, Bifrost returns you to {{E(model.ReturnPath)}}.
+
+
+
+
+ """;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs b/src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs
new file mode 100644
index 0000000..d95e7f3
--- /dev/null
+++ b/src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs
@@ -0,0 +1,56 @@
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Features.Shared;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Registration;
+
+///
+/// The per-address permits on the registration endpoints (challenge and register share one budget), on the shared
+/// fixed-window budget. It exists so one address cannot fill the consumed-challenge set alone. It fails closed:
+/// anything it cannot decide is a 503, never a pass.
+///
+public sealed class RegistrationRateLimit(IOptions options, TimeProvider clock, ILogger logger)
+{
+ private readonly FixedWindowBudget addresses = new(
+ options.Value.Limits.PerAddressPermits,
+ options.Value.Limits.Window,
+ options.Value.Limits.MaxTrackedKeys,
+ clock);
+
+ // Time-lock submissions cost the client no work, so they get their own, much tighter budget per address.
+ private readonly FixedWindowBudget fallbacks = new(
+ options.Value.Limits.FallbackPermits,
+ options.Value.Limits.FallbackWindow,
+ options.Value.Limits.MaxTrackedKeys,
+ clock);
+
+ /// Null when the request may proceed; otherwise the refusal to return.
+ public IResult? Refuse(HttpContext http) => Refuse(http, addresses, "Too many registration requests from this address.");
+
+ /// The stricter budget for a submission that passed the time-lock instead of the proof of work.
+ public IResult? RefuseFallback(HttpContext http) =>
+ Refuse(http, fallbacks, "Too many registrations without the quick check from this address; try again later or let the page run its script.");
+
+ private IResult? Refuse(HttpContext http, FixedWindowBudget budget, string message)
+ {
+ try
+ {
+ if (budget.Spend(ClientAddress.BudgetKey(http.Connection.RemoteIpAddress)) is not { } denial)
+ {
+ return null;
+ }
+
+ http.Response.Headers.RetryAfter = RetryAfter(denial.RetryAfter);
+ return Results.Text(message, statusCode: StatusCodes.Status429TooManyRequests);
+ }
+ catch (Exception exception) when (exception is not OperationCanceledException)
+ {
+ logger.LogError("Registration rate limit could not decide ({ExceptionType}); the request is refused.", exception.GetType().Name);
+ http.Response.Headers.RetryAfter = "60";
+ return Results.Text("Registration is unavailable; try again shortly.", statusCode: StatusCodes.Status503ServiceUnavailable);
+ }
+ }
+
+ private static string RetryAfter(TimeSpan wait) =>
+ Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture);
+}
diff --git a/src/Bifrost.Web/Features/Registration/TrainingNotice.cs b/src/Bifrost.Web/Features/Registration/TrainingNotice.cs
new file mode 100644
index 0000000..a823426
--- /dev/null
+++ b/src/Bifrost.Web/Features/Registration/TrainingNotice.cs
@@ -0,0 +1,36 @@
+using System.Net;
+using System.Text;
+
+namespace Bifrost.Web.Features.Registration;
+
+///
+/// The training notice a person may agree to. Changing the wording in substance means a new (a
+/// positive integer, no leading zeros), because a receipt records the version the person agreed to; a receipt for any
+/// other version no longer counts, the chat sign-in is refused, and the person is asked again on the consent page.
+/// The text is frozen once served: a test pins its hash per version, so an edit without a version bump fails.
+///
+public static class TrainingNotice
+{
+ public const int Version = 1;
+
+ public const string Text =
+ "GameCult chat training notice, version 1\n\n" +
+ "GameCult may use messages you post in GameCult chat to train and evaluate AI models that GameCult builds and runs.\n\n" +
+ "What counts. The text of your messages, with their time and room, tied to your account name. Not your email address, your sign-in details or anything you did not post. Nothing that came from Discord is used, in any form.\n\n" +
+ "It is your choice. Agreement is needed to speak in a recorded room. You can have a GameCult account, see the members page and vote without agreeing. If you do not agree, you cannot speak in a recorded room and none of your messages are used.\n\n" +
+ "If you agree, we record your account, this notice's version number and the time. Nothing else is stored with it.\n\n" +
+ "If you withdraw, you can no longer speak in a recorded room, and we leave all your messages out of every training set made after that moment. Lines you have already spoken stay: withdrawing deletes nothing. Your messages stay in chat and on our servers, anything already used to train a model stays used, and a dataset already built is not recalled. We keep the record that you agreed and when you withdrew.\n\n" +
+ "You can agree or withdraw at any time on your consent page while signed in. If the notice changes, its version changes and we ask again; until you agree to the new version, you cannot speak in a recorded room and your messages are not used.";
+
+ /// The text as HTML-encoded paragraphs inside a div with the given id.
+ public static string Html(string id)
+ {
+ var html = new StringBuilder($"
").ToString();
+ }
+}
diff --git a/src/Bifrost.Web/Features/Shared/ApplicationBootstrapper.cs b/src/Bifrost.Web/Features/Shared/ApplicationBootstrapper.cs
index 1a3cd0f..f7cf59b 100644
--- a/src/Bifrost.Web/Features/Shared/ApplicationBootstrapper.cs
+++ b/src/Bifrost.Web/Features/Shared/ApplicationBootstrapper.cs
@@ -10,6 +10,7 @@ public sealed class ApplicationBootstrapper(
BifrostDbContext dbContext,
IOptions bootstrapOptions,
TimeProvider timeProvider,
+ AuditTrailService auditTrailService,
ILogger logger)
{
public async Task RunAsync(CancellationToken cancellationToken)
@@ -40,16 +41,11 @@ public sealed class ApplicationBootstrapper(
foreach (var adminUser in adminUsers.Where(x => x.Membership is not null))
{
- var membership = adminUser.Membership!;
- membership.Status = MembershipStatus.Active;
- membership.IsPlatformAdmin = true;
- membership.CanManageProjects = true;
- membership.CanManageLedger = true;
- membership.CanModerateMotions = true;
- membership.ApprovedAtUtc ??= now;
-
- EnsureRole(membership, MemberRole.PlatformAdmin, null, now, "Bootstrap admin");
- EnsureRole(membership, MemberRole.StandardMember, null, now, "Default active member role");
+ var before = adminUser.Membership!.Status;
+ if (TryPromoteBootstrapAdmin(adminUser, now, logger) && before != adminUser.Membership.Status)
+ {
+ await RecordPromotionAsync(auditTrailService, adminUser, before, cancellationToken);
+ }
}
if (dbContext.ChangeTracker.HasChanges())
@@ -58,6 +54,47 @@ public sealed class ApplicationBootstrapper(
}
}
+ ///
+ /// The one bootstrap-admin promotion, used at startup and at sign-in. A Merged or Suspended account is left exactly as it is (an admin's
+ /// decision; only the suspension service lifts it) and the refusal is logged by account id. Returns whether it promoted.
+ ///
+ public static bool TryPromoteBootstrapAdmin(UserAccount account, DateTimeOffset now, ILogger logger)
+ {
+ var membership = account.Membership!;
+ if (membership.IsMerged)
+ {
+ logger.LogWarning("Bootstrap admin promotion skipped for merged account {UserAccountId}.", account.Id);
+ return false;
+ }
+
+ if (membership.Status == MembershipStatus.Suspended)
+ {
+ logger.LogWarning("Bootstrap admin promotion skipped for suspended account {UserAccountId}.", account.Id);
+ return false;
+ }
+
+ membership.Status = MembershipStatus.Active;
+ membership.IsPlatformAdmin = true;
+ membership.CanManageProjects = true;
+ membership.CanManageLedger = true;
+ membership.CanModerateMotions = true;
+ membership.ApprovedAtUtc ??= now;
+
+ EnsureRole(membership, MemberRole.PlatformAdmin, null, now, "Bootstrap admin");
+ EnsureRole(membership, MemberRole.StandardMember, null, now, "Default active member role");
+ return true;
+ }
+
+ /// The receipt for a bootstrap promotion that changed membership status; saves together with the promotion.
+ public static Task RecordPromotionAsync(AuditTrailService auditTrailService, UserAccount account, MembershipStatus before, CancellationToken cancellationToken) =>
+ auditTrailService.RecordAsync(
+ null,
+ nameof(Bifrost.Web.Domain.Membership),
+ account.Membership!.Id,
+ "membership.bootstrap-promoted",
+ $"Bootstrap admin promotion of {account.DisplayName} ({before} -> {account.Membership.Status}).",
+ cancellationToken);
+
public static void EnsureRole(
Bifrost.Web.Domain.Membership membership,
MemberRole role,
diff --git a/src/Bifrost.Web/Features/Shared/BifrostCookies.cs b/src/Bifrost.Web/Features/Shared/BifrostCookies.cs
index 1c099e8..0a99cf0 100644
--- a/src/Bifrost.Web/Features/Shared/BifrostCookies.cs
+++ b/src/Bifrost.Web/Features/Shared/BifrostCookies.cs
@@ -12,6 +12,7 @@ public static class BifrostCookies
public const string Antiforgery = HostPrefix + "bifrost_antiforgery";
public const string Voter = HostPrefix + "bifrost_voter";
public const string HeimdallAttemptPrefix = HostPrefix + "bifrost_heimdall_";
+ public const string PasskeyTicket = HostPrefix + "bifrost_passkey_ticket";
public const string Path = "/";
}
diff --git a/src/Bifrost.Web/Features/Shared/ClientAddress.cs b/src/Bifrost.Web/Features/Shared/ClientAddress.cs
new file mode 100644
index 0000000..f959e24
--- /dev/null
+++ b/src/Bifrost.Web/Features/Shared/ClientAddress.cs
@@ -0,0 +1,32 @@
+using System.Net;
+
+namespace Bifrost.Web.Features.Shared;
+
+public static class ClientAddress
+{
+ ///
+ /// The partition key for a per-address budget: the connection's address, already corrected by the forwarded-headers
+ /// handling that trusts only the local proxy. An IPv6 caller owns its /64, so rotating the low bits buys nothing.
+ ///
+ public static string BudgetKey(IPAddress? address)
+ {
+ if (address is null)
+ {
+ return "unknown";
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
+ {
+ return address.ToString();
+ }
+
+ var bytes = address.GetAddressBytes();
+ Array.Clear(bytes, 8, 8);
+ return new IPAddress(bytes).ToString() + "/64";
+ }
+}
diff --git a/src/Bifrost.Web/Features/Shared/CurrentBifrostActor.cs b/src/Bifrost.Web/Features/Shared/CurrentBifrostActor.cs
index 648c662..412dada 100644
--- a/src/Bifrost.Web/Features/Shared/CurrentBifrostActor.cs
+++ b/src/Bifrost.Web/Features/Shared/CurrentBifrostActor.cs
@@ -1,9 +1,13 @@
using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
namespace Bifrost.Web.Features.Shared;
public sealed record CurrentBifrostActor(bool IsAuthenticated, UserAccount? UserAccount)
{
+ /// Set when the account behind this sign-in is frozen or folded by an account merge; the actor then has no account.
+ public MergeStanding? Merge { get; init; }
+
public static readonly CurrentBifrostActor Anonymous = new(false, null);
public Bifrost.Web.Domain.Membership? Membership => UserAccount?.Membership;
diff --git a/src/Bifrost.Web/Features/Shared/CurrentBifrostActorAccessor.cs b/src/Bifrost.Web/Features/Shared/CurrentBifrostActorAccessor.cs
index 5d34fad..ae9839b 100644
--- a/src/Bifrost.Web/Features/Shared/CurrentBifrostActorAccessor.cs
+++ b/src/Bifrost.Web/Features/Shared/CurrentBifrostActorAccessor.cs
@@ -12,7 +12,8 @@ public interface ICurrentBifrostActorAccessor
public sealed class CurrentBifrostActorAccessor(
IHttpContextAccessor httpContextAccessor,
- BifrostDbContext dbContext) : ICurrentBifrostActorAccessor
+ BifrostDbContext dbContext,
+ AccountMergeLedger ledger) : ICurrentBifrostActorAccessor
{
private const string CacheKey = "Bifrost.CurrentActor";
@@ -45,18 +46,41 @@ public sealed class CurrentBifrostActorAccessor(
return Cache(httpContext, CurrentBifrostActor.Anonymous);
}
- var userAccount = await dbContext.UserAccounts
+ // One credential names one row: identity first, then Heimdall id, then GitHub id; the first hit wins. Two rows matching
+ // one principal (a merge can leave a login on either side) must never throw or pick by luck.
+ var accounts = dbContext.UserAccounts
.AsNoTracking()
.Include(x => x.MemberProfile)
.Include(x => x.Membership!)
.ThenInclude(x => x.RoleAssignments)
.Include(x => x.Membership!)
- .ThenInclude(x => x.TierSnapshots)
- .SingleOrDefaultAsync(
- x => (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity) && x.NormalizedBifrostIdentity == normalizedBifrostIdentity) ||
- (!string.IsNullOrWhiteSpace(heimdallAccountId) && x.HeimdallAccountId == heimdallAccountId) ||
- (hasGitHubUserId && x.GitHubUserId == gitHubUserId),
- cancellationToken);
+ .ThenInclude(x => x.TierSnapshots);
+
+ Bifrost.Web.Domain.UserAccount? userAccount = null;
+ if (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity))
+ {
+ userAccount = await accounts.SingleOrDefaultAsync(x => x.NormalizedBifrostIdentity == normalizedBifrostIdentity, cancellationToken);
+ }
+
+ if (userAccount is null && !string.IsNullOrWhiteSpace(heimdallAccountId))
+ {
+ userAccount = await accounts.SingleOrDefaultAsync(x => x.HeimdallAccountId == heimdallAccountId, cancellationToken);
+ }
+
+ if (userAccount is null && hasGitHubUserId)
+ {
+ userAccount = await accounts.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
+ }
+
+ // A folded or frozen account acts as nobody on every route: this is the one gate (merge ledger standing, derived per request).
+ if (userAccount is not null)
+ {
+ var standing = await ledger.StandingAsync(userAccount.Id, cancellationToken);
+ if (standing is not null)
+ {
+ return Cache(httpContext, new CurrentBifrostActor(true, null) { Merge = standing });
+ }
+ }
return Cache(httpContext, new CurrentBifrostActor(true, userAccount));
}
diff --git a/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs b/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs
index 3a31269..0837f7e 100644
--- a/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs
+++ b/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs
@@ -92,6 +92,7 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
var recentActivity = await dbContext.AuditEvents
.AsNoTracking()
.Include(x => x.ActorUserAccount)
+ .Where(x => !x.Action.StartsWith("membership.suspended") && !x.Action.StartsWith("membership.unsuspended") && x.Action != "membership.bootstrap-promoted") // suspension reasons and the bootstrap-admin promotion are for admins, not the member dashboard
.OrderByDescending(x => x.OccurredAtUtc)
.Take(8)
.Select(x => new DashboardActivity(
diff --git a/src/Bifrost.Web/Features/Shared/RequestOriginGuard.cs b/src/Bifrost.Web/Features/Shared/RequestOriginGuard.cs
new file mode 100644
index 0000000..be1f701
--- /dev/null
+++ b/src/Bifrost.Web/Features/Shared/RequestOriginGuard.cs
@@ -0,0 +1,41 @@
+using Bifrost.Web.Configuration;
+using Microsoft.AspNetCore.Http;
+
+namespace Bifrost.Web.Features.Shared;
+
+// The one place that decides whether a state-changing request to an anonymous form (the vote page, the sign-up form) came from
+// the site itself. These flows carry no antiforgery token and no antiforgery cookie, so a cross-site form post is refused here instead
+// (OWASP Fetch Metadata): the Origin header must equal the configured site origin byte for byte, or, when the browser
+// sent no Origin, Sec-Fetch-Site must be exactly same-origin. Same-site, cross-site, none, absent and a repeated header
+// are all refused. Header values are compared, never echoed.
+public static class RequestOriginGuard
+{
+ public static bool Allows(HttpRequest request, BifrostHostOptions host)
+ {
+ if (!Uri.TryCreate(host.PublicBaseUrl, UriKind.Absolute, out var site))
+ {
+ return false;
+ }
+
+ var origin = request.Headers.Origin;
+ if (request.Headers.ContainsKey("Origin"))
+ {
+ return origin.Count == 1 && string.Equals(origin[0], site.GetLeftPart(UriPartial.Authority), StringComparison.Ordinal);
+ }
+
+ var fetchSite = request.Headers["Sec-Fetch-Site"];
+ return fetchSite.Count == 1 && string.Equals(fetchSite[0], "same-origin", StringComparison.Ordinal);
+ }
+
+ ///
+ /// For the no-script sign-up form only. Text browsers (Lynx, w3m, Links) send neither Origin nor Sec-Fetch-Site, so a
+ /// request with neither is let through when it carries no Bifrost session cookie: there is no session to replace.
+ /// Any Origin or Sec-Fetch-Site present is judged exactly as judges it, and a headerless request
+ /// that does carry a session cookie is refused.
+ ///
+ public static bool AllowsFormWithoutFetchMetadata(HttpRequest request, BifrostHostOptions host) =>
+ Allows(request, host) ||
+ (!request.Headers.ContainsKey("Origin") &&
+ !request.Headers.ContainsKey("Sec-Fetch-Site") &&
+ !request.Cookies.Keys.Any(name => name.StartsWith(BifrostCookies.Session, StringComparison.Ordinal)));
+}
diff --git a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs
index 98b8dc7..58fe2fb 100644
--- a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs
+++ b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs
@@ -1,5 +1,6 @@
using Bifrost.Web.Configuration;
using Bifrost.Web.Features.ConceptVotes;
+using Bifrost.Web.Features.Registration;
using Microsoft.Extensions.Options;
namespace Bifrost.Web.Features.Shared;
@@ -12,12 +13,18 @@ public sealed class StartupConfigurationValidator(
IOptions heimdallOptions,
IOptions stripeOptions,
IOptions hostOptions,
- IOptions conceptVoteOptions)
+ IOptions conceptVoteOptions,
+ IOptions deskOptions,
+ IOptions registrationOptions,
+ OidcIssuerOptions? oidcOptions = null)
{
public void Validate()
{
var failures = new List();
+ // Building the options resolves Heimdall:AppSecretFile, and a bad file stops startup in every environment.
+ _ = heimdallOptions.Value;
+
// Checked in every environment: a bad value here would otherwise pass startup and throw on every cast.
var conceptVotes = conceptVoteOptions.Value;
if (!NetworkPrefix.IsValidLength(conceptVotes.IPv4PrefixLength, NetworkPrefix.IPv4Bits))
@@ -45,6 +52,32 @@ public sealed class StartupConfigurationValidator(
failures.Add("ConceptVotes:MaxTrackedKeys must be at least 1.");
}
+ ValidateDesk(deskOptions.Value, failures);
+
+ var difficulty = registrationOptions.Value.Captcha.Difficulty;
+ if (difficulty < RegistrationOptions.MinDifficulty || difficulty > RegistrationOptions.MaxDifficulty)
+ {
+ failures.Add($"Bifrost:Registration:Captcha:Difficulty must be between {RegistrationOptions.MinDifficulty} and {RegistrationOptions.MaxDifficulty}.");
+ }
+
+ var wait = registrationOptions.Value.Captcha.FallbackWaitSeconds;
+ if (wait < RegistrationOptions.MinFallbackWaitSeconds || wait > RegistrationOptions.MaxFallbackWaitSeconds ||
+ wait >= RegistrationChallengeService.Lifetime.TotalSeconds)
+ {
+ failures.Add($"Bifrost:Registration:Captcha:FallbackWaitSeconds must be between {RegistrationOptions.MinFallbackWaitSeconds} and {RegistrationOptions.MaxFallbackWaitSeconds} and shorter than the challenge lifetime ({RegistrationChallengeService.Lifetime.TotalSeconds:0} seconds).");
+ }
+
+ var limits = registrationOptions.Value.Limits;
+ if (limits.PerAddressPermits < 1 || limits.Window <= TimeSpan.Zero || limits.MaxTrackedKeys < 1)
+ {
+ failures.Add("Bifrost:Registration:Limits:PerAddressPermits and MaxTrackedKeys must be at least 1 and Window must be positive.");
+ }
+
+ if (limits.FallbackPermits < 1 || limits.FallbackWindow <= TimeSpan.Zero)
+ {
+ failures.Add("Bifrost:Registration:Limits:FallbackPermits must be at least 1 and FallbackWindow must be positive.");
+ }
+
if (hostEnvironment.IsDevelopment() || hostEnvironment.IsEnvironment("Testing"))
{
Refuse(failures);
@@ -72,6 +105,13 @@ public sealed class StartupConfigurationValidator(
failures.Add("Heimdall:PatronSupportIntakeSecret is required when patron support intake is enabled.");
}
+ // The options are already resolved, so a secret from Heimdall:AppSecretFile or Heimdall:AppSecret lands in AppSecret.
+ // Blank would silently switch Discord and Patreon member sign-in off.
+ if (string.IsNullOrWhiteSpace(heimdallOptions.Value.AppSecret))
+ {
+ failures.Add("Heimdall:AppSecretFile (or Heimdall:AppSecret) must supply the Heimdall app secret outside development.");
+ }
+
if (stripeOptions.Value.EnableCheckout)
{
if (!stripeOptions.Value.IsCheckoutConfigured)
@@ -116,6 +156,112 @@ public sealed class StartupConfigurationValidator(
Refuse(failures);
}
+ // Checked in every environment: a bad Mind list or decider id would otherwise pass startup and misroute or
+ // mis-attribute answers. Account existence is a request-time question, not a startup one.
+ private void ValidateDesk(DeskOptions desk, List failures)
+ {
+ // The desk's bearer is validated against Bifrost's own issuer: without Bifrost:Oidc there is no credential to serve with.
+ if (oidcOptions is null && configuration.GetSection(DeskOptions.SectionName).Exists())
+ {
+ failures.Add("Bifrost:Oidc must be configured when the Desk section exists: the desk validates its bearer tokens against Bifrost's own issuer.");
+ }
+
+ if (!desk.IsConfigured)
+ {
+ if (configuration.GetSection(DeskOptions.SectionName).Exists())
+ {
+ failures.Add("Desk:Minds must list at least one Mind when the Desk section exists.");
+ }
+
+ return;
+ }
+
+ if (!Uri.TryCreate(desk.AllowedOrigin, UriKind.Absolute, out var origin) ||
+ origin.Scheme is not ("http" or "https") ||
+ !string.Equals(desk.AllowedOrigin, origin.GetLeftPart(UriPartial.Authority), StringComparison.Ordinal))
+ {
+ failures.Add("Desk:AllowedOrigin must be one http(s) origin: scheme, host and optional port, no path.");
+ }
+
+ if (desk.MaxBodyBytes < 1)
+ {
+ failures.Add("Desk:MaxBodyBytes must be at least 1.");
+ }
+
+ if (desk.RetryAfterSeconds < 1)
+ {
+ failures.Add("Desk:RetryAfterSeconds must be at least 1.");
+ }
+
+ var ids = new HashSet(StringComparer.Ordinal);
+ var sockets = new HashSet(StringComparer.Ordinal);
+ for (var i = 0; i < desk.Minds.Count; i++)
+ {
+ var mind = desk.Minds[i];
+ if (string.IsNullOrWhiteSpace(mind.Id))
+ {
+ failures.Add($"Desk:Minds:{i}:Id must not be blank.");
+ }
+ else if (!ids.Add(mind.Id))
+ {
+ failures.Add($"Desk:Minds:{i}:Id repeats an earlier Mind id.");
+ }
+
+ if (!Path.IsPathFullyQualified(mind.Socket))
+ {
+ failures.Add($"Desk:Minds:{i}:Socket must be an absolute path.");
+ }
+ else if (!sockets.Add(mind.Socket))
+ {
+ failures.Add($"Desk:Minds:{i}:Socket repeats an earlier Mind's socket.");
+ }
+
+ if (mind.Deciders.Count is < 1 or > DeskMindOptions.MaxDeciders)
+ {
+ failures.Add($"Desk:Minds:{i}:Deciders must hold 1 to {DeskMindOptions.MaxDeciders} account ids.");
+ }
+
+ var deciders = new HashSet(StringComparer.Ordinal);
+ foreach (var decider in mind.Deciders)
+ {
+ if (!IsLowercaseGuid(decider))
+ {
+ failures.Add($"Desk:Minds:{i}:Deciders entries must be lowercase D-format account ids.");
+ }
+ else if (!deciders.Add(decider))
+ {
+ failures.Add($"Desk:Minds:{i}:Deciders repeats an account id.");
+ }
+ }
+ }
+
+ var attribution = desk.Attribution;
+ if (!string.IsNullOrEmpty(attribution.Operator) && !IsLowercaseGuid(attribution.Operator))
+ {
+ failures.Add("Desk:Attribution:Operator must be a lowercase D-format account id.");
+ }
+
+ var stewards = new HashSet(StringComparer.Ordinal);
+ foreach (var steward in attribution.Stewards)
+ {
+ if (!IsLowercaseGuid(steward))
+ {
+ failures.Add("Desk:Attribution:Stewards entries must be lowercase D-format account ids.");
+ }
+ else if (!stewards.Add(steward))
+ {
+ failures.Add("Desk:Attribution:Stewards repeats an account id.");
+ }
+ else if (string.Equals(steward, attribution.Operator, StringComparison.Ordinal))
+ {
+ failures.Add("Desk:Attribution:Operator must not also be a steward.");
+ }
+ }
+ }
+
+ private static bool IsLowercaseGuid(string? value) =>
+ Guid.TryParseExact(value, "D", out var guid) && string.Equals(value, guid.ToString("D"), StringComparison.Ordinal);
+
private static void Refuse(List failures)
{
if (failures.Count > 0)
diff --git a/src/Bifrost.Web/Pages/App/Index.cshtml b/src/Bifrost.Web/Pages/App/Index.cshtml
index 889675a..c3406be 100644
--- a/src/Bifrost.Web/Pages/App/Index.cshtml
+++ b/src/Bifrost.Web/Pages/App/Index.cshtml
@@ -14,12 +14,7 @@
governance pressure, and recent team activity in one place.
diff --git a/src/Bifrost.Web/Pages/App/Index.cshtml.cs b/src/Bifrost.Web/Pages/App/Index.cshtml.cs
index ed0db5c..9d8a800 100644
--- a/src/Bifrost.Web/Pages/App/Index.cshtml.cs
+++ b/src/Bifrost.Web/Pages/App/Index.cshtml.cs
@@ -18,11 +18,4 @@ public sealed class IndexModel(
Actor = await actorAccessor.GetAsync(cancellationToken);
Snapshot = await snapshotService.GetAsync(Actor.UserAccount?.Id, cancellationToken);
}
-
- public async Task OnGetSummaryAsync(CancellationToken cancellationToken)
- {
- Actor = await actorAccessor.GetAsync(cancellationToken);
- Snapshot = await snapshotService.GetAsync(Actor.UserAccount?.Id, cancellationToken);
- return Partial("_SummaryCards", Snapshot);
- }
}
diff --git a/src/Bifrost.Web/Pages/App/Members/Index.cshtml b/src/Bifrost.Web/Pages/App/Members/Index.cshtml
index 0d9d546..12a5ab9 100644
--- a/src/Bifrost.Web/Pages/App/Members/Index.cshtml
+++ b/src/Bifrost.Web/Pages/App/Members/Index.cshtml
@@ -8,30 +8,37 @@
Members
-
Invite and approval gate
+
Chat invites and approval gate
- 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.
+ @if (!string.IsNullOrEmpty(Model.Notice))
+ {
+
@Model.Notice
+ }
+
@if (Model.Actor.CanManageMembership)
{
+ @if (Model.MintedLink is not null)
+ {
+
+ Invite link, shown once. Send it to one person; it works for 14 days and one account.
+
@Model.Invitations.Count active invitations tracked.
+
Outstanding chat invites
+
@Model.Invitations.Count unredeemed.
@if (Model.Invitations.Count == 0)
{
-
No invitations yet.
+
No unredeemed invites.
}
else
{
@@ -248,24 +270,24 @@
-
GitHub login
+
For
Issued
-
Accepted
-
Notes
+
Expires
+
- @foreach (var invitation in Model.Invitations)
+ @foreach (var invite in Model.Invitations)
{
-
@invitation.GitHubLogin
-
@invitation.IssuedAtUtc.ToString("dd MMM yyyy HH:mm") UTC
+
@invite.Note
+
@invite.IssuedAtUtc.ToString("dd MMM yyyy HH:mm") UTC
+
@invite.ExpiresAtUtc.ToString("dd MMM yyyy HH:mm") UTC
- @(invitation.AcceptedAtUtc is null
- ? "Waiting for sign-in"
- : invitation.AcceptedAtUtc.Value.ToString("dd MMM yyyy HH:mm") + " UTC")
+
-
@invitation.Notes
}
@@ -273,6 +295,7 @@
}
+}
@section Scripts {
diff --git a/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs b/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs
index 2f385b7..d21e794 100644
--- a/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs
+++ b/src/Bifrost.Web/Pages/App/Members/Index.cshtml.cs
@@ -1,6 +1,8 @@
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;
using Microsoft.AspNetCore.Mvc.RazorPages;
@@ -12,19 +14,45 @@ public sealed class IndexModel(
BifrostDbContext dbContext,
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();
+ /// Why the last membership action did nothing; one of , carried across the redirect.
+ [TempData]
+ public string? Notice { get; set; }
+
+ private static readonly IReadOnlyDictionary RefusalNotices = new Dictionary
+ {
+ [SuspensionOutcome.NoReason] = "Nothing changed: a reason is required to suspend or unsuspend an account.",
+ [SuspensionOutcome.ProtectedAccount] = "Nothing changed: you cannot suspend yourself or another platform admin.",
+ [SuspensionOutcome.NoSuchAccount] = "Nothing changed: that account or its membership does not exist.",
+ [SuspensionOutcome.NotApplicable] = "Nothing changed: the account is already in that state."
+ };
+
+ internal const string ApproveSuspendedNotice = "Nothing changed: a suspended account can only be lifted with Unsuspend.";
+ /// Admin-only text for a Suspended row whose reason predates the SuspensionReason column; the old text is never read back from the audit trail.
+ internal const string LegacySuspensionText = "Suspended before reasons were recorded";
+ internal const string ApproveMergedNotice = "Nothing changed: that account was merged into another and cannot be approved.";
+
+ internal const string NoMembershipNotice = "Nothing changed: that account has no membership yet.";
+ internal const string OwnAdminRoleNotice = "Nothing changed: you cannot remove or change your own platform admin role.";
+ internal const string RoleOnSuspendedNotice = "Nothing changed: a suspended account's roles cannot be changed until it is unsuspended.";
+
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
public IReadOnlyList Users { get; private set; } = [];
- public IReadOnlyList Invitations { get; private set; } = [];
+ public IReadOnlyList Invitations { get; private set; } = [];
+
+ /// The link just minted, present only on the response to the mint.
+ public string? MintedLink { get; private set; }
public async Task OnGetAsync(CancellationToken cancellationToken)
{
@@ -39,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 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();
}
@@ -100,9 +105,28 @@ public sealed class IndexModel(
var user = await dbContext.UserAccounts
.Include(x => x.Membership!)
.ThenInclude(x => x.RoleAssignments)
- .SingleAsync(x => x.Id == userAccountId, cancellationToken);
+ .SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
- user.Membership!.Status = MembershipStatus.Active;
+ // The chat tier holds no membership by design (docs/oidc-issuer.md); approval refuses rather than inventing one.
+ if (user is null || user.Membership is null)
+ {
+ Notice = user is null ? RefusalNotices[SuspensionOutcome.NoSuchAccount] : NoMembershipNotice;
+ return RedirectToPage();
+ }
+
+ if (user.Membership.Status == MembershipStatus.Suspended)
+ {
+ Notice = ApproveSuspendedNotice; // only Unsuspend lifts a suspension
+ return RedirectToPage();
+ }
+
+ if (user.Membership.IsMerged)
+ {
+ Notice = ApproveMergedNotice; // only the merge ledger leaves Merged
+ return RedirectToPage();
+ }
+
+ user.Membership.Status = MembershipStatus.Active;
user.Membership.ApprovedAtUtc = timeProvider.GetUtcNow();
ApplicationBootstrapper.EnsureRole(
user.Membership,
@@ -124,6 +148,27 @@ public sealed class IndexModel(
return RedirectToPage();
}
+ public async Task OnPostSuspendAsync(Guid userAccountId, string? reason, CancellationToken cancellationToken) =>
+ await ChangeSuspensionAsync(userAccountId, reason, suspend: true, cancellationToken);
+
+ public async Task OnPostUnsuspendAsync(Guid userAccountId, string? reason, CancellationToken cancellationToken) =>
+ await ChangeSuspensionAsync(userAccountId, reason, suspend: false, cancellationToken);
+
+ private async Task ChangeSuspensionAsync(Guid userAccountId, string? reason, bool suspend, CancellationToken cancellationToken)
+ {
+ Actor = await actorAccessor.GetAsync(cancellationToken);
+ var outcome = suspend
+ ? await suspension.SuspendAsync(Actor, userAccountId, reason, cancellationToken)
+ : await suspension.UnsuspendAsync(Actor, userAccountId, reason, cancellationToken);
+ if (outcome == SuspensionOutcome.NotAdmin)
+ {
+ return Forbid();
+ }
+
+ Notice = RefusalNotices.GetValueOrDefault(outcome);
+ return RedirectToPage();
+ }
+
public async Task OnPostToggleRoleAsync(Guid userAccountId, MemberRole role, CancellationToken cancellationToken)
{
Actor = await actorAccessor.GetAsync(cancellationToken);
@@ -135,10 +180,29 @@ public sealed class IndexModel(
var user = await dbContext.UserAccounts
.Include(x => x.Membership!)
.ThenInclude(x => x.RoleAssignments)
- .SingleAsync(x => x.Id == userAccountId, cancellationToken);
+ .SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
+
+ if (user is null)
+ {
+ Notice = RefusalNotices[SuspensionOutcome.NoSuchAccount];
+ return RedirectToPage();
+ }
if (user.Membership is null)
{
+ Notice = NoMembershipNotice;
+ return RedirectToPage();
+ }
+
+ if (user.Id == Actor.UserAccount.Id && role == MemberRole.PlatformAdmin)
+ {
+ Notice = OwnAdminRoleNotice;
+ return RedirectToPage();
+ }
+
+ if (user.Membership.Status == MembershipStatus.Suspended)
+ {
+ Notice = RoleOnSuspendedNotice;
return RedirectToPage();
}
@@ -153,8 +217,10 @@ public sealed class IndexModel(
Notes = "Assigned from the member admin page."
});
}
- else if (!(user.Id == Actor.UserAccount.Id && role == MemberRole.PlatformAdmin))
+ else
{
+ // Out of the collection too, so the flags below derive from the roles as they will stand after the save.
+ user.Membership.RoleAssignments.Remove(existingAssignment);
dbContext.RoleAssignments.Remove(existingAssignment);
}
@@ -198,7 +264,13 @@ public sealed class IndexModel(
var user = await dbContext.UserAccounts
.Include(x => x.Membership!)
.ThenInclude(x => x.TierSnapshots)
- .SingleAsync(x => x.Id == userAccountId, cancellationToken);
+ .SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
+
+ if (user is null)
+ {
+ Notice = RefusalNotices[SuspensionOutcome.NoSuchAccount];
+ return RedirectToPage();
+ }
if (user.Membership is null)
{
@@ -317,6 +389,7 @@ public sealed class IndexModel(
user.MemberProfile?.Skills ?? string.Empty,
user.MemberProfile?.Availability ?? string.Empty,
user.Membership?.Status ?? MembershipStatus.Authenticated,
+ Actor.CanManageMembership ? user.Membership?.SuspensionReason ?? string.Empty : string.Empty,
user.Membership?.RoleAssignments.Select(x => x.Role).OrderBy(x => x.ToString()).ToArray() ?? [],
patronTier?.Label ?? string.Empty,
patronTier?.Weight ?? 0m,
@@ -324,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)
{
@@ -358,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
@@ -404,6 +470,7 @@ public sealed class IndexModel(
string Skills,
string Availability,
MembershipStatus Status,
+ string SuspensionReason,
IReadOnlyList Roles,
string PatronTierLabel,
decimal PatronTierWeight,
diff --git a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml
new file mode 100644
index 0000000..1f8d341
--- /dev/null
+++ b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml
@@ -0,0 +1,72 @@
+@page
+@using Bifrost.Web.Domain
+@model Bifrost.Web.Pages.App.Merges.IndexModel
+@{
+ ViewData["Title"] = "Stuck merges";
+}
+
+
+
+ Merges
+
Stuck account merges
+
+ A merge listed here has stopped advancing on its own. Before ending one, read Heimdall's identity move by the move id shown
+ (docs/account-merge.md, Stuck merges). Ending a merge cannot be undone, and Bifrost never adopts a move Heimdall made.
+
+ @if (!merge.CanSettle)
+ {
+ Still being retried; nothing to end.
+ }
+ else
+ {
+
+ }
+
+
+ }
+
+
+
+ }
+
diff --git a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs
new file mode 100644
index 0000000..865cb42
--- /dev/null
+++ b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs
@@ -0,0 +1,82 @@
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Shared;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.RazorPages;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.Pages.App.Merges;
+
+/// One in-flight merge the sweeper has stopped advancing, as an operator may see it: no account, Heimdall id or login of either side.
+public sealed record StuckMerge(Guid Id, AccountMergeState State, string LastOutcome, int Attempts, string MoveId, bool CanSettle);
+
+///
+/// The operator's door for a stuck merge (ruling merge-stuck-end-only-typed-id), platform admins only. It lists in-flight merges that
+/// stopped on a settleable outcome or have been retried eight times, with the stored move id of the leg in flight, and passes an
+/// admin's choice and the typed move id to , the one writer. It calls no Heimdall.
+///
+public sealed class IndexModel(BifrostDbContext dbContext, ICurrentBifrostActorAccessor actorAccessor, AccountMergeSaga saga) : PageModel
+{
+ private const int RetriesBeforeListed = 8;
+
+ public const string Url = "/App/Merges";
+
+ private static readonly IReadOnlyDictionary ResultWords = new Dictionary
+ {
+ ["settled"] = "The merge was ended and the sweeper will not touch it again.",
+ ["not_stuck"] = "Nothing changed: that merge is not stuck on a state this choice can end.",
+ ["wrong_move_id"] = "Nothing changed: the move id typed is not the stored one of that leg.",
+ ["lost"] = "Nothing changed: the merge moved on by itself while you were settling it."
+ };
+
+ public IReadOnlyList Merges { get; private set; } = [];
+
+ /// The words for the closed ?result= code of the last settle; null for no code or one this page does not know.
+ public string? Notice { get; private set; }
+
+ public async Task OnGetAsync(string? result, CancellationToken cancellationToken)
+ {
+ if (!(await actorAccessor.GetAsync(cancellationToken)).IsPlatformAdmin)
+ {
+ return Forbid();
+ }
+
+ Notice = result is not null && ResultWords.TryGetValue(result, out var words) ? words : null;
+ var rows = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => (x.State == AccountMergeState.Confirmed || x.State == AccountMergeState.UndoRequested)
+ && (AccountMergeSaga.SettleableOutcomes.Contains(x.LastOutcome) || x.Attempts >= RetriesBeforeListed))
+ .OrderBy(x => x.CreatedUtc)
+ .ToListAsync(cancellationToken);
+ Merges = [.. rows.Select(x => new StuckMerge(
+ x.Id, x.State, x.LastOutcome, x.Attempts,
+ (x.State == AccountMergeState.UndoRequested ? x.HeimdallReverseMoveId : x.HeimdallMoveId) ?? string.Empty,
+ AccountMergeSaga.IsSettleable(x)))];
+ return Page();
+ }
+
+ public Task OnPostFailForwardAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) =>
+ SettleAsync(mergeId, SettleChoice.FailForward, moveId, cancellationToken);
+
+ public Task OnPostAbandonUndoAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) =>
+ SettleAsync(mergeId, SettleChoice.AbandonUndo, moveId, cancellationToken);
+
+ private async Task SettleAsync(Guid mergeId, SettleChoice choice, string? moveId, CancellationToken cancellationToken)
+ {
+ var actor = await actorAccessor.GetAsync(cancellationToken);
+ if (!actor.CanManageMembership || actor.UserAccount is null)
+ {
+ return Forbid();
+ }
+
+ var outcome = await saga.SettleStuckAsync(mergeId, choice, moveId ?? string.Empty, actor.UserAccount.Id, cancellationToken);
+ var code = outcome switch
+ {
+ SettleOutcome.Settled => "settled",
+ SettleOutcome.WrongMoveId => "wrong_move_id",
+ SettleOutcome.Lost => "lost",
+ _ => "not_stuck"
+ };
+ return Redirect($"{Url}?result={code}");
+ }
+}
diff --git a/src/Bifrost.Web/Pages/Index.cshtml b/src/Bifrost.Web/Pages/Index.cshtml
index 76dd401..cfaaacd 100644
--- a/src/Bifrost.Web/Pages/Index.cshtml
+++ b/src/Bifrost.Web/Pages/Index.cshtml
@@ -64,7 +64,7 @@
Stack
- ASP.NET Core 8 + Razor Pages + HTMX
+ ASP.NET Core 8 + Razor PagesSystem of record
diff --git a/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml b/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml
new file mode 100644
index 0000000..ad86138
--- /dev/null
+++ b/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml
@@ -0,0 +1,237 @@
+@page
+@model Bifrost.Web.Pages.Membership.LinkedAccountsModel
+@{
+ ViewData["Title"] = "Linked accounts";
+}
+
+
+ Heimdall
+
Linked accounts
+
+ The provider logins that sign in to this account. Heimdall holds them and decides what may change; Bifrost keeps none of
+ your Heimdall sign-in, so each action sends you through Heimdall once more.
+
+
+ @if (Model.ResultMessage is not null)
+ {
+
@Model.ResultMessage
+ }
+
+ @if (!Model.HasHeimdallAccount)
+ {
+
+ This session is not a Heimdall account, so there are no provider logins to manage here. Sign in with Discord or Patreon
+ through Heimdall to see them.
+
+ }
+ else
+ {
+
Your logins
+ @if (Model.Identities is null)
+ {
+
+ Bifrost does not hold the list: it asks Heimdall, which means signing in to Heimdall again, and keeps the answer for
+ five minutes. It also cannot tell which logins this account holds right now, so it will not choose one for you.
+ Pick a login you know it holds. Signing in through Discord or Patreon when the account no longer holds that login
+ would create a separate Heimdall account holding it. Google cannot do that: Heimdall refuses a Google sign-in for a
+ login no account holds.
+
+
+ @foreach (var provider in Model.LinkableProviders.OrderBy(x => x == "google" ? 0 : 1))
+ {
+
+ }
+
+ }
+ else
+ {
+
+ @foreach (var identity in Model.Identities)
+ {
+
+ This account has a passkey, so unlinking needs it, but passkeys are not available on this server right now (a
+ configuration fault the operator must fix), so nothing can be unlinked from here at the moment. Nothing is lost:
+ try again later. If you cannot wait, revoke your passkeys below; unlinking then falls back to a fresh Google sign-in,
+ if a Google login is linked to this account.
+
+ }
+ else if (Model.HasStrongPasskey)
+ {
+
Unlinking asks for one of your passkeys, then signs you in to Heimdall once more and removes only the login you picked.
+ }
+ else if (Model.HasGoogle)
+ {
+
Unlinking asks you to sign in with Google again as proof, then removes only the login you picked. A passkey, once it has cooled off, is stronger proof and takes over from Google.
+ }
+ else
+ {
+
+ Unlinking needs strong proof, and none is available. Add a passkey below@(Model.NextStrongAt is { } waiting
+ ? $" (your newest one counts from {waiting.UtcDateTime:dd MMM yyyy HH:mm} UTC)"
+ : " (it counts after a 48 hour cooling-off)"),
+ or link a Google login once Heimdall has Google set up. Discord and Patreon cannot give that proof.
+
+ }
+
+
+ }
+
+
Passkeys
+ @if (!Model.PasskeysAvailable)
+ {
+
Passkeys are not available on this server right now, so none can be added or used. You can still revoke the ones listed.
+ }
+ @if (Model.PasskeysAvailable)
+ {
+
+ A passkey is the strong proof for unlinking a login: it stays on your device, and a site that is not Bifrost cannot use it.
+ A new passkey is added only right after you sign in to Heimdall again, and it counts as strong proof 48 hours later, so
+ someone who borrows your open browser cannot add one and use it at once. You can revoke a passkey here at any time.
+
+ }
+ @if (Model.Passkeys.Count > 0)
+ {
+
+ @foreach (var key in Model.Passkeys)
+ {
+
+ @key.Label
+ @if (key.IsStrong)
+ {
+ active
+ }
+ else
+ {
+ cooling off until @key.StrongFromUtc.UtcDateTime.ToString("dd MMM yyyy HH:mm") UTC; cannot unlink yet
+ }
+ added @key.CreatedUtc.UtcDateTime.ToString("dd MMM yyyy") UTC
+ @if (key.LastUsedUtc is { } used)
+ {
+ last used @used.UtcDateTime.ToString("dd MMM yyyy") UTC
+ }
+
+
This is the most passkeys an account can hold. Revoke one to add another.
+ }
+ else if (Model.CanEnrol)
+ {
+
+
+ }
+ else if (Model.Identities is not null)
+ {
+
+ }
+ else
+ {
+
Read your linked logins first; adding a passkey then asks you to sign in to Heimdall once more.
+ }
+ }
+
+
+ @if (Model.Identities is not null)
+ {
+
Link another login
+
+ You will sign in to Heimdall again, then to the provider you pick. If that login already belongs to another account,
+ nothing is linked and nothing is merged.
+
+
+
+@section Scripts {
+ @if (Model.HasHeimdallAccount && Model.PasskeysAvailable)
+ {
+
+ }
+}
diff --git a/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml.cs b/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml.cs
new file mode 100644
index 0000000..bfc44c5
--- /dev/null
+++ b/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml.cs
@@ -0,0 +1,316 @@
+using System.Security.Claims;
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Features.Heimdall;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Passkeys;
+using Bifrost.Web.Features.Shared;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Filters;
+using Microsoft.AspNetCore.Mvc.RazorPages;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Pages.Membership;
+
+///
+/// The member's provider logins (docs/linked-accounts.md). Bifrost keeps no Heimdall token, so every action here begins a
+/// fresh Heimdall sign-in for the account already signed in and finishes inside that sign-in's completion
+/// (POST /auth/heimdall/complete); this page only starts them and shows what the last read found. Every handler is a
+/// POST with antiforgery. Nothing from the query or the form is ever shown: the outcome is a code from a closed set.
+///
+[Authorize]
+[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
+public sealed class LinkedAccountsModel(
+ HeimdallAuthService heimdallAuthService,
+ LinkedAccountsSnapshots snapshots,
+ PasskeyService passkeys,
+ ICurrentBifrostActorAccessor actors,
+ IOptions hostOptions,
+ IOptions mergeOptions,
+ ILogger logger) : PageModel
+{
+ private static readonly Dictionary ProviderNames = new(StringComparer.Ordinal)
+ {
+ ["discord"] = "Discord",
+ ["patreon"] = "Patreon",
+ ["google"] = "Google"
+ };
+
+ ///
+ /// A folded or frozen account manages no logins and enrols no passkey: the page's handlers all begin a Heimdall flow on the
+ /// account's raw claim, so the one gate is here, on the actor accessor's standing, before any handler runs.
+ ///
+ public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
+ {
+ if ((await actors.GetAsync(context.HttpContext.RequestAborted)).Merge is not null)
+ {
+ context.Result = Forbid();
+ return;
+ }
+
+ await base.OnPageHandlerExecutionAsync(context, next);
+ }
+
+ private string? AccountId => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 } id ? id : null;
+
+ /// Whether the merge page exists on this server (a flag, dark until Heimdall can move logins).
+ public bool MergeEnabled => mergeOptions.Value.Enabled;
+
+ /// The wording of the outcome the page was sent back with: a closed set, null for anything else.
+ public string? ResultMessage { get; private set; }
+
+ /// Whether this session is a Heimdall account. A Bifrost-native GitHub session has none, so there is nothing to list.
+ public bool HasHeimdallAccount => AccountId is not null;
+
+ /// The logins the last read found, or null when there is none or it has expired.
+ public IReadOnlyList? Identities { get; private set; }
+
+ /// Whether a fresh Google sign-in can be had for this account: without a strong passkey, unlinking needs one, and only Google can give it.
+ public bool HasGoogle => Identities?.Any(x => x.Provider == HeimdallAuthService.StepUpProvider) == true;
+
+ /// The account's passkeys that are not revoked, with their cooling-off state.
+ public IReadOnlyList Passkeys { get; private set; } = [];
+
+ /// Whether a passkey past its cooling-off exists: unlinking then needs it and no longer accepts Google as the proof.
+ public bool HasStrongPasskey => Passkeys.Any(x => x.IsStrong);
+
+ /// When the first passkey still cooling off becomes strong.
+ public DateTimeOffset? NextStrongAt => Passkeys.Where(x => !x.IsStrong).Select(x => (DateTimeOffset?)x.StrongFromUtc).Min();
+
+ /// Whether this browser holds a live ticket from a fresh sign-in, so a passkey can be added now.
+ public bool CanEnrol { get; private set; }
+
+ /// Whether this server can run passkey ceremonies at all (https and the host it expects).
+ public bool PasskeysAvailable => passkeys.IsAvailable;
+
+ public bool PasskeyLimitReached => Passkeys.Count >= PasskeyService.MaxActive;
+
+ public bool CanUnlink => HasStrongPasskey || HasGoogle;
+
+ public IReadOnlyList LinkableProviders => HeimdallAuthService.LinkableProviders;
+
+ public static string ProviderName(string provider) => ProviderNames.GetValueOrDefault(provider, provider);
+
+ public async Task OnGetAsync(CancellationToken cancellationToken)
+ {
+ ResultMessage = HeimdallLinkOutcomes.Wording(Request.Query[HeimdallLinkOutcomes.ResultParameter].ToString());
+ Identities = AccountId is { } id ? snapshots.Get(id) : null;
+ if (AccountId is { } account)
+ {
+ Passkeys = await passkeys.ListAsync(account, cancellationToken);
+ CanEnrol = passkeys.HasTicket(account, Request.Cookies[BifrostCookies.PasskeyTicket]);
+ }
+ }
+
+ /// Reads the account's logins: an ordinary Heimdall sign-in, then the list inside its completion.
+ public Task OnPostRefreshAsync(string? via, CancellationToken cancellationToken)
+ {
+ // With no current list Bifrost cannot tell which provider the account still holds, so the member names one.
+ if (AccountId is not { } id || (snapshots.Get(id) is null && (via is null || !HeimdallAuthService.LinkableProviders.Contains(via))))
+ {
+ return Task.FromResult(Done(HeimdallLinkOutcome.ProviderNeeded));
+ }
+
+ return BeginAsync(
+ (account, ct) => heimdallAuthService.StartListAsync(account, via, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
+ HeimdallLinkOutcome.Error,
+ cancellationToken);
+ }
+
+ /// Links another provider. The provider is one Heimdall's bifrost profile admits; anything else starts nothing, and so does a missing list.
+ public Task OnPostLinkAsync(string? provider, CancellationToken cancellationToken)
+ {
+ if (provider is null || !HeimdallAuthService.LinkableProviders.Contains(provider))
+ {
+ return Task.FromResult(Done(HeimdallLinkOutcome.Error));
+ }
+
+ if (AccountId is not { } id || snapshots.Get(id) is null)
+ {
+ return Task.FromResult(Done(HeimdallLinkOutcome.ListExpired));
+ }
+
+ return BeginAsync(
+ (account, ct) => heimdallAuthService.StartLinkAsync(account, provider, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
+ HeimdallLinkOutcome.Error,
+ cancellationToken);
+ }
+
+ ///
+ /// Unlinks one login with fresh proof. The identity must be on the list this account was last shown and the account must
+ /// hold a Google login to prove with; otherwise Heimdall is not asked, and the page says so.
+ ///
+ public async Task OnPostUnlinkAsync(string? identityId, CancellationToken cancellationToken)
+ {
+ var shown = AccountId is { } id ? snapshots.Get(id) : null;
+ if (shown is null || identityId is null || !shown.Any(x => x.Id == identityId))
+ {
+ return Done(HeimdallLinkOutcome.ListExpired);
+ }
+
+ // A strong passkey replaces Google as the proof: a member who has one is never asked for the weaker one.
+ if (await passkeys.HasStrongAsync(AccountId!, cancellationToken))
+ {
+ return Done(HeimdallLinkOutcome.PasskeyRequired);
+ }
+
+ if (!shown.Any(x => x.Provider == HeimdallAuthService.StepUpProvider))
+ {
+ return Done(HeimdallLinkOutcome.ProofUnavailable);
+ }
+
+ return await BeginAsync(
+ (account, ct) => heimdallAuthService.StartUnlinkAsync(account, identityId, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
+ HeimdallLinkOutcome.ProofUnavailable,
+ cancellationToken);
+ }
+
+ /// Begins the fresh sign-in whose completion issues the enrolment ticket. Needs a current list: the proof provider is never guessed.
+ public async Task OnPostPasskeyEnrolStartAsync(CancellationToken cancellationToken)
+ {
+ if (AccountId is not { } id)
+ {
+ return Done(HeimdallLinkOutcome.Error);
+ }
+
+ if (snapshots.Get(id) is null)
+ {
+ return Done(HeimdallLinkOutcome.ListExpired);
+ }
+
+ if (await passkeys.PreflightEnrolStartAsync(id, cancellationToken) is { } refused)
+ {
+ return Done(refused);
+ }
+
+ return await BeginAsync(
+ (account, ct) => heimdallAuthService.StartEnrolProofAsync(account, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
+ HeimdallLinkOutcome.Error,
+ cancellationToken);
+ }
+
+ /// The WebAuthn creation options for the ticket this browser holds, as JSON for the page's script.
+ public async Task OnPostPasskeyEnrolOptionsAsync(CancellationToken cancellationToken)
+ {
+ if (AccountId is not { } id)
+ {
+ return Options(HeimdallLinkOutcome.Error, null);
+ }
+
+ var (refusal, json) = await passkeys.BeginEnrolAsync(id, Request.Cookies[BifrostCookies.PasskeyTicket], cancellationToken);
+ return Options(refusal, json);
+ }
+
+ /// Verifies the registration the script posted. The ticket cookie is spent whatever the outcome.
+ public async Task OnPostPasskeyEnrolAsync(
+ string? id, string? rawId, string? attestationObject, string? clientDataJson, string? transports, string? label, CancellationToken cancellationToken)
+ {
+ if (AccountId is not { } account)
+ {
+ return Done(HeimdallLinkOutcome.Error);
+ }
+
+ var outcome = await passkeys.EnrolAsync(
+ account, Request.Cookies[BifrostCookies.PasskeyTicket],
+ new PasskeyFields(id, rawId, null, clientDataJson, null, null, attestationObject, transports), label, cancellationToken);
+ Response.Cookies.Delete(BifrostCookies.PasskeyTicket, HeimdallAttemptCookie.DeleteOptions());
+ return Done(outcome);
+ }
+
+ public async Task OnPostPasskeyRevokeAsync(Guid credentialId, CancellationToken cancellationToken) =>
+ AccountId is { } id ? Done(await passkeys.RevokeAsync(id, credentialId, cancellationToken)) : Done(HeimdallLinkOutcome.Error);
+
+ /// The WebAuthn request options for unlinking one identity, as JSON for the page's script.
+ public async Task OnPostPasskeyChallengeAsync(string? identityId, CancellationToken cancellationToken)
+ {
+ if (AccountId is not { } id)
+ {
+ return Options(HeimdallLinkOutcome.Error, null);
+ }
+
+ if (snapshots.Get(id) is not { } shown || identityId is null || !shown.Any(x => x.Id == identityId))
+ {
+ return Options(HeimdallLinkOutcome.ListExpired, null);
+ }
+
+ var (refusal, json) = await passkeys.BeginAssertionAsync(id, identityId, cancellationToken);
+ return Options(refusal, json);
+ }
+
+ ///
+ /// Unlinks one login on a passkey assertion. The assertion is verified here; only then does Bifrost start the fresh Heimdall sign-in
+ /// whose completion asks Heimdall for the step-up and unlinks. A refused or unverifiable assertion starts no sign-in.
+ ///
+ public async Task OnPostUnlinkPasskeyAsync(
+ string? identityId, string? id, string? rawId, string? authenticatorData, string? clientDataJson, string? signature, string? userHandle,
+ CancellationToken cancellationToken)
+ {
+ var shown = AccountId is { } account ? snapshots.Get(account) : null;
+ if (shown is null || identityId is null || !shown.Any(x => x.Id == identityId))
+ {
+ return Done(HeimdallLinkOutcome.ListExpired);
+ }
+
+ var (refusal, factId) = await passkeys.VerifyAssertionAsync(
+ AccountId!, identityId, new PasskeyFields(id, rawId, authenticatorData, clientDataJson, signature, userHandle, null, null), cancellationToken);
+ if (refusal is { } failed)
+ {
+ return Done(failed);
+ }
+
+ try
+ {
+ var started = await heimdallAuthService.StartUnlinkPasskeyAsync(
+ AccountId!, identityId, factId!, hostOptions.Value.PublicBaseUrl, Request.Cookies, cancellationToken);
+ Response.Cookies.Append(started.CookieName, started.CookieValue, HeimdallAttemptCookie.Options());
+ return Redirect(started.AuthorizationUrl.ToString());
+ }
+ catch (HeimdallAuthException error)
+ {
+ logger.LogWarning("Linked accounts start refused: {Reason}", error.Message);
+ passkeys.DiscardFact(factId);
+ return Done(HeimdallLinkOutcome.ProofUnavailable);
+ }
+ }
+
+ /// JSON for the page's script: the options, or only a closed outcome code with the status that fits.
+ private IActionResult Options(HeimdallLinkOutcome? refusal, string? json)
+ {
+ if (refusal is null && json is not null)
+ {
+ return Content(json, "application/json");
+ }
+
+ var status = refusal == HeimdallLinkOutcome.RateLimited ? StatusCodes.Status429TooManyRequests : StatusCodes.Status400BadRequest;
+ return new ContentResult
+ {
+ StatusCode = status,
+ ContentType = "application/json",
+ Content = "{\"error\":\"" + HeimdallLinkOutcomes.Code(refusal ?? HeimdallLinkOutcome.Error) + "\"}"
+ };
+ }
+
+ private IActionResult Done(HeimdallLinkOutcome outcome) =>
+ RedirectToPage(null, new Dictionary { [HeimdallLinkOutcomes.ResultParameter] = HeimdallLinkOutcomes.Code(outcome) });
+
+ private async Task BeginAsync(
+ Func> start, HeimdallLinkOutcome onRefusal, CancellationToken cancellationToken)
+ {
+ if (AccountId is not { } accountId)
+ {
+ return Done(HeimdallLinkOutcome.Error);
+ }
+
+ try
+ {
+ var started = await start(accountId, cancellationToken);
+ Response.Cookies.Append(started.CookieName, started.CookieValue, HeimdallAttemptCookie.Options());
+ return Redirect(started.AuthorizationUrl.ToString());
+ }
+ catch (HeimdallAuthException error)
+ {
+ logger.LogWarning("Linked accounts start refused: {Reason}", error.Message);
+ return Done(onRefusal);
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml b/src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml
new file mode 100644
index 0000000..1b72e29
--- /dev/null
+++ b/src/Bifrost.Web/Pages/Membership/MergeAccounts.cshtml
@@ -0,0 +1,148 @@
+@page
+@model Bifrost.Web.Pages.Membership.MergeAccountsModel
+@{
+ ViewData["Title"] = "Merge two accounts";
+}
+
+
+ Account merge
+
Merge two accounts
+
+ If one person holds two accounts, they can be merged into one. You prove both accounts with a fresh sign-in each, choose
+ which one stays, see what changes and confirm; nothing is named until both proofs exist, and the other account is only
+ ever the one Heimdall identified from your second sign-in.
+
+
+ @if (Model.ResultMessage is not null)
+ {
+
@Model.ResultMessage
+ }
+
+ @if (Model.ConfirmMessage is not null)
+ {
+
+ Sign-ins are held in memory for a few minutes and then dropped. For each account, name a provider that account holds:
+ signing in through a provider it does not hold would make an unrelated account.
+
To undo, sign in again through each login that moved. The sign-ins are held in memory for a few minutes.
+ @foreach (var provider in merge.NeedProof)
+ {
+
+ }
+ }
+ }
+
+ }
+
diff --git a/src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml.cs b/src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml.cs
new file mode 100644
index 0000000..00cc86f
--- /dev/null
+++ b/src/Bifrost.Web/Pages/Membership/MergeStatus.cshtml.cs
@@ -0,0 +1,206 @@
+using System.Security.Claims;
+using System.Text.Json;
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Heimdall;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Shared;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.RazorPages;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Pages.Membership;
+
+///
+/// The member's own merge page: the merges that kept this account (up to five) and the one its frozen or folded standing names, in
+/// 's closed words, and the undo. It reads merge rows and writes none: undo is the saga's
+/// followed by its own , with fresh proofs
+/// of every moved login held by . A person who signed in through a login that moved is the survivor here, so
+/// there is no separate folded-side undo. Nothing the query, the form or the store holds is shown except as a closed code's words, and
+/// no account name, id, email or login of either side is rendered.
+///
+[Authorize]
+[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
+public sealed class MergeStatusModel(
+ ICurrentBifrostActorAccessor actors,
+ BifrostDbContext dbContext,
+ AccountMergeSaga saga,
+ MergeProofs proofs,
+ HeimdallAuthService heimdallAuthService,
+ IOptions hostOptions,
+ TimeProvider timeProvider,
+ ILogger logger) : PageModel
+{
+ private const int MaxListed = 5;
+ private const string UndoParameter = "undo";
+ private const string LoginsUnproved = "logins_unproved";
+
+ public sealed record MergeRow(
+ Guid Id,
+ string State,
+ string? Why,
+ string? Outcome,
+ string? Confirmed,
+ string? Committed,
+ string? GraceEnds,
+ string? Final,
+ string? DaysLeft,
+ string? TierNote,
+ IReadOnlyList SurvivorProofs,
+ IReadOnlyList FoldedProofs,
+ bool CanUndo,
+ bool Ready,
+ IReadOnlyList NeedProof);
+
+ public IReadOnlyList Merges { get; private set; } = [];
+
+ public string? ResultMessage { get; private set; }
+
+ public string? UndoMessage { get; private set; }
+
+ public static string ProviderName(string provider) =>
+ HeimdallAuthService.LinkableProviders.Contains(provider) ? LinkedAccountsModel.ProviderName(provider) : provider == "passkey" ? "Passkey" : "another provider";
+
+ public async Task OnGetAsync(CancellationToken cancellationToken)
+ {
+ ResultMessage = HeimdallLinkOutcomes.Wording(Request.Query[HeimdallLinkOutcomes.ResultParameter].ToString());
+ UndoMessage = MergeWording.Undo(Request.Query[UndoParameter].ToString()) is { Length: > 0 } words ? words : null;
+
+ var actor = await actors.GetAsync(cancellationToken);
+ var me = actor.UserAccount?.Id;
+ var rows = me is { } id
+ ? await dbContext.AccountMerges.AsNoTracking().Where(x => x.SurvivorUserAccountId == id).OrderByDescending(x => x.CreatedUtc).Take(MaxListed).ToListAsync(cancellationToken)
+ : [];
+ if (actor.Merge is { } standing && rows.All(x => x.Id != standing.MergeId)
+ && await dbContext.AccountMerges.AsNoTracking().SingleOrDefaultAsync(x => x.Id == standing.MergeId, cancellationToken) is { } named)
+ {
+ rows.Add(named);
+ }
+
+ Merges = [.. rows.Select(x => Row(x, me))];
+ }
+
+ /// Starts a fresh sign-in of this account through , held in memory until the undo takes it.
+ public async Task OnPostProveForUndoAsync(string? via, CancellationToken cancellationToken)
+ {
+ if (User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is not { Length: > 0 } accountId)
+ {
+ return Result(HeimdallLinkOutcome.Error);
+ }
+
+ try
+ {
+ var started = await heimdallAuthService.StartMergeProveSelfAsync(
+ accountId, via, HeimdallLinkReturn, hostOptions.Value.PublicBaseUrl, Request.Cookies, cancellationToken);
+ Response.Cookies.Append(started.CookieName, started.CookieValue, HeimdallAttemptCookie.Options());
+ return Redirect(started.AuthorizationUrl.ToString());
+ }
+ catch (HeimdallAuthException error)
+ {
+ logger.LogWarning("Merge undo proof start refused: {Reason}", error.Message);
+ return Result(HeimdallLinkOutcome.Error);
+ }
+ }
+
+ /// Asks the saga to undo one merge with the proofs this member holds, then runs its step function once, as the sweeper would.
+ public async Task OnPostUndoAsync(string? mergeId, CancellationToken cancellationToken)
+ {
+ var actor = await actors.GetAsync(cancellationToken);
+ if (actor.UserAccount is not { } me || !Guid.TryParse(mergeId, out var id)
+ || await dbContext.AccountMerges.AsNoTracking().SingleOrDefaultAsync(x => x.Id == id, cancellationToken) is not { } merge
+ || merge.SurvivorUserAccountId != me.Id)
+ {
+ return Undone("not_survivor");
+ }
+
+ if (proofs.PeekUndo(me.Id, MovedIds(merge)) is not UndoPeekResult.Ready { Proofs.Count: > 0 } ready)
+ {
+ return Undone(LoginsUnproved);
+ }
+
+ var outcome = await saga.RequestUndoAsync(id, me.Id, ready.Proofs, cancellationToken);
+ if (outcome is UndoOutcome.Requested)
+ {
+ proofs.Clear(me.Id);
+ try
+ {
+ await saga.AdvanceAsync(id, cancellationToken);
+ }
+ catch (Exception error) when (error is not OperationCanceledException)
+ {
+ // The saga's stored state is the truth and the sweeper resumes it.
+ logger.LogWarning("Account merge {MergeId} inline advance failed: {Error}", id, error.GetType().Name);
+ }
+ }
+
+ return Undone(MergeWording.UndoCode(outcome));
+ }
+
+ private const string HeimdallLinkReturn = "/Membership/MergeStatus";
+
+ private MergeRow Row(AccountMerge merge, Guid? me)
+ {
+ var now = timeProvider.GetUtcNow();
+ var open = merge.State == AccountMergeState.Committed && merge.GraceEndsUtc is { } end && now < end;
+ var canUndo = open && me == merge.SurvivorUserAccountId;
+ var ready = false;
+ IReadOnlyList need = [];
+ if (canUndo)
+ {
+ switch (proofs.PeekUndo(me!.Value, MovedIds(merge)))
+ {
+ case UndoPeekResult.Ready { Proofs.Count: > 0 }:
+ ready = true;
+ break;
+ case UndoPeekResult.LoginsUnproved { Providers.Count: > 0 } unproved:
+ need = unproved.Providers;
+ break;
+ default:
+ need = HeimdallAuthService.LinkableProviders;
+ break;
+ }
+ }
+
+ var inGrace = merge.State is AccountMergeState.Committed or AccountMergeState.UndoRequested && merge.GraceEndsUtc > now;
+ return new MergeRow(
+ merge.Id,
+ MergeWording.State(merge.State),
+ merge.State == AccountMergeState.Failed ? MergeWording.Failure(merge.FailureCode) : null,
+ merge.State is AccountMergeState.Committed or AccountMergeState.Failed or AccountMergeState.Confirmed or AccountMergeState.HeimdallMoved
+ or AccountMergeState.UndoRequested or AccountMergeState.HeimdallReversed
+ ? MergeWording.Outcome(merge.LastOutcome)
+ : null,
+ merge.ConfirmedUtc is { } confirmed ? MergeWording.Date(confirmed) : null,
+ merge.CommittedUtc is { } committed ? MergeWording.Date(committed) : null,
+ merge.GraceEndsUtc is { } graceEnds ? MergeWording.Date(graceEnds) : null,
+ merge.FinalizedUtc is { } final ? MergeWording.Date(final) : null,
+ inGrace && merge.GraceEndsUtc is { } until ? MergeWording.DaysLeft(MergeWording.DaysUntil(until, now)) : null,
+ inGrace && merge.GraceEndsUtc is { } by ? MergeWording.TierNote(merge.ProofFromTier, by) : null,
+ merge.SurvivorProofProvider.Length > 0 ? [ProviderName(merge.SurvivorProofProvider)] : [],
+ [.. merge.FoldedProofProviders.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(ProviderName)],
+ canUndo,
+ ready,
+ need);
+ }
+
+ private static IReadOnlyCollection MovedIds(AccountMerge merge)
+ {
+ try
+ {
+ return merge.MovedIdentityIds is { } json ? JsonSerializer.Deserialize(json) ?? [] : [];
+ }
+ catch (JsonException)
+ {
+ return [];
+ }
+ }
+
+ private IActionResult Undone(string code) =>
+ RedirectToPage(null, new Dictionary { [UndoParameter] = code });
+
+ private IActionResult Result(HeimdallLinkOutcome outcome) =>
+ RedirectToPage(null, new Dictionary { [HeimdallLinkOutcomes.ResultParameter] = HeimdallLinkOutcomes.Code(outcome) });
+}
diff --git a/src/Bifrost.Web/Pages/Membership/Status.cshtml b/src/Bifrost.Web/Pages/Membership/Status.cshtml
index 2c1ab8f..587eeb1 100644
--- a/src/Bifrost.Web/Pages/Membership/Status.cshtml
+++ b/src/Bifrost.Web/Pages/Membership/Status.cshtml
@@ -24,11 +24,19 @@
@Model.StatusMessage
- @if (Model.Invitation is not null)
+ @if (Model.CanManageLogins)
{
-
- Invitation tracked for @Model.Invitation.GitHubLogin.
- Issued @Model.Invitation.IssuedAtUtc.ToString("dd MMM yyyy") UTC.
+
+ Linked accounts
+ See, add and remove the provider logins that sign in to this account.
+
+ }
+
+ @if (Model.HasMerges)
+ {
+
+ Merge status
+ See an account merge and, for seven days, undo it.
}
diff --git a/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs b/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
index d579dd3..cfc6078 100644
--- a/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
+++ b/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
@@ -1,5 +1,7 @@
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
+using System.Security.Claims;
+using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
@@ -12,9 +14,13 @@ public sealed class StatusModel(
ICurrentBifrostActorAccessor actorAccessor,
BifrostDbContext dbContext) : PageModel
{
- public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
+ /// Whether this session belongs to a Heimdall account whose logins the Linked accounts page can manage.
+ public bool CanManageLogins => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 };
- public MembershipInvitation? Invitation { get; private set; }
+ /// Whether this account is in, or was in, a merge: the link to Merge status is shown only then.
+ public bool HasMerges { get; private set; }
+
+ public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
public string StatusLabel => Actor.Membership?.Status switch
{
@@ -36,26 +42,17 @@ 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."
};
public async Task OnGetAsync(CancellationToken cancellationToken)
{
Actor = await actorAccessor.GetAsync(cancellationToken);
-
- if (Actor.UserAccount is null)
- {
- return;
- }
-
- Invitation = await dbContext.MembershipInvitations
- .AsNoTracking()
- .SingleOrDefaultAsync(
- x => x.NormalizedGitHubLogin == Actor.UserAccount.NormalizedGitHubLogin &&
- x.RevokedAtUtc == null,
- cancellationToken);
+ HasMerges = Actor.Merge is not null
+ || (Actor.UserAccount is { } account
+ && await dbContext.AccountMerges.AnyAsync(x => x.SurvivorUserAccountId == account.Id || x.FoldedUserAccountId == account.Id, cancellationToken));
}
}
diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml b/src/Bifrost.Web/Pages/Mill/Vote.cshtml
index fe75338..d9e67f2 100644
--- a/src/Bifrost.Web/Pages/Mill/Vote.cshtml
+++ b/src/Bifrost.Web/Pages/Mill/Vote.cshtml
@@ -28,15 +28,15 @@
-
-
@if (stance is not null)
{
-
}
diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs
index dd87f6d..41ed934 100644
--- a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs
+++ b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs
@@ -29,7 +29,7 @@ public sealed class VoteModel(
// The single gate before any handler runs. A request that selects no handler (a POST with no or an unknown handler,
// any other method) is a client error, never a view over a null subject. A cast is accepted only from the site's own
- // origin (CastRequestGuard); no antiforgery cookie or token exists on this flow.
+ // origin (RequestOriginGuard); no antiforgery cookie or token exists on this flow.
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
var method = context.HttpContext.Request.Method;
@@ -50,7 +50,7 @@ public sealed class VoteModel(
return;
}
- if (HttpMethods.IsPost(method) && !CastRequestGuard.Allows(context.HttpContext.Request, host.Value))
+ if (HttpMethods.IsPost(method) && !RequestOriginGuard.Allows(context.HttpContext.Request, host.Value))
{
context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
return;
diff --git a/src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml b/src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml
new file mode 100644
index 0000000..c9ea380
--- /dev/null
+++ b/src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml
@@ -0,0 +1,5 @@
+@model string
+
diff --git a/src/Bifrost.Web/Pages/Shared/_Layout.cshtml b/src/Bifrost.Web/Pages/Shared/_Layout.cshtml
index 34c68cb..232bc65 100644
--- a/src/Bifrost.Web/Pages/Shared/_Layout.cshtml
+++ b/src/Bifrost.Web/Pages/Shared/_Layout.cshtml
@@ -17,7 +17,7 @@
-
+
-
@await RenderSectionAsync("Scripts", required: false)
diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs
index bf6103a..116871a 100644
--- a/src/Bifrost.Web/Program.cs
+++ b/src/Bifrost.Web/Program.cs
@@ -7,12 +7,14 @@ using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Bridge;
using Bifrost.Web.Features.ConceptVotes;
+using Bifrost.Web.Features.Desk;
using Bifrost.Web.Features.GitHub;
using Bifrost.Web.Features.Heimdall;
using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Motions;
using Bifrost.Web.Features.Oidc;
using Bifrost.Web.Features.Patronage;
+using Bifrost.Web.Features.Registration;
using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
@@ -62,7 +64,8 @@ builder.Services
builder.Services
.AddOptions()
- .BindConfiguration(HeimdallOptions.SectionName);
+ .BindConfiguration(HeimdallOptions.SectionName)
+ .PostConfigure>(HeimdallOptions.ResolveAppSecret);
builder.Services
.AddOptions()
@@ -76,6 +79,10 @@ builder.Services
.AddOptions()
.BindConfiguration(ConceptVoteOptions.SectionName);
+builder.Services
+ .AddOptions()
+ .BindConfiguration(DeskOptions.SectionName);
+
builder.Services.AddAntiforgery(options =>
{
options.Cookie.Name = BifrostCookies.Antiforgery;
@@ -86,6 +93,7 @@ builder.Services.AddAntiforgery(options =>
builder.Services.AddRazorPages(options =>
{
options.Conventions.AuthorizePage("/Membership/Status");
+ options.Conventions.AuthorizePage("/Membership/LinkedAccounts");
options.Conventions.AuthorizeFolder("/App", ActiveMemberRequirement.PolicyName);
options.Conventions.AllowAnonymousToFolder("/Mill");
});
@@ -112,6 +120,7 @@ builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped();
builder.Services.AddScoped();
+builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
@@ -125,7 +134,19 @@ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddOptions().BindConfiguration(MindIntakeOptions.SectionName);
builder.Services.AddSingleton(); // TimeProvider and options resolve from the container
+builder.Services.AddOptions().BindConfiguration(RegistrationOptions.SectionName);
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddScoped();
+builder.Services.AddScoped();
builder.Services.AddHostedService();
+builder.Services.AddOptions().BindConfiguration(AccountMergeOptions.SectionName);
+builder.Services.AddScoped();
+builder.Services.AddScoped();
+builder.Services.AddScoped();
+builder.Services.AddOptions().BindConfiguration(ChatNoticesOptions.SectionName);
+builder.Services.AddSingleton();
+builder.Services.AddHostedService();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
@@ -138,9 +159,13 @@ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddSingleton();
builder.Services.AddScoped();
-builder.Services.AddHttpClient((serviceProvider, client) =>
- HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value))
- .RedactLoggedHeaders(header => string.Equals(header, HeimdallAuthService.AppSecretHeader, StringComparison.OrdinalIgnoreCase));
+// The app-secret and member-bearer clients and the mover: no redirects (see HeimdallClientServices).
+builder.Services.AddHeimdallClients();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddScoped();
builder.Services.AddSingleton();
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService>().Value));
@@ -252,10 +277,19 @@ if (oidcOptions is not null)
builder.Services.AddBifrostOidc(oidcOptions);
}
+// The desk is mapped only when the Desk section exists, and a configured desk needs its credential and door ports.
+var deskConfigured = builder.Configuration.GetSection(DeskOptions.SectionName).Exists();
+if (deskConfigured)
+{
+ builder.Services.AddBifrostDesk(oidcConfigured: oidcOptions is not null);
+}
+
var app = builder.Build();
var appJsonSerializerOptions = CreateAppJsonSerializerOptions();
app.Services.GetRequiredService().Validate();
+// Resolved now so a misconfigured RP (not https, host differs, a port in ExpectedHost) is logged once at boot, not on the first ceremony.
+_ = app.Services.GetRequiredService();
await using (var scope = app.Services.CreateAsyncScope())
{
await scope.ServiceProvider
@@ -273,6 +307,11 @@ if (!app.Environment.IsDevelopment())
app.UseHttpLogging();
app.UseHttpsRedirection();
+if (oidcOptions is not null)
+{
+ app.UseMiddleware(); // before authentication: OpenIddict answers /connect/* inside it
+}
+
app.UseStaticFiles();
app.UseRouting();
app.UseConceptTallyCors();
@@ -293,12 +332,18 @@ app.MapGet("/readyz", async (ReadinessService readinessService, CancellationToke
}).AllowAnonymous();
app.MapConceptTallyExport();
+app.MapConceptRankedExport();
if (oidcOptions is not null)
{
app.MapBifrostOidc();
}
+if (deskConfigured)
+{
+ app.MapDesk();
+}
+
app.MapPost("/github/webhooks", async (
HttpRequest request,
GitHubWebhookService gitHubWebhookService,
@@ -330,6 +375,76 @@ app.MapPost("/github/webhooks", async (
};
}).AllowAnonymous();
+// The invite link is /invite#: 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(
+ """
+ Invite - Bifrost
+
Opening your invite
+
+
+ """,
+ "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 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() 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(
+ """
+ Invite - Bifrost
+
+ """);
+ return;
+ }
+
if (!gitHubOptions.Value.IsConfigured)
{
httpContext.Response.Redirect("/?auth=github-not-configured");
@@ -361,35 +490,173 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions
{
+ if (rateLimit.Refuse(httpContext) is { } refused)
+ {
+ return refused;
+ }
+
+ var outcome = await registration.RunAsync(
+ httpContext,
+ new RegistrationAttempt(request.Identity, request.DisplayName, request.Challenge, request.Nonce, request.Waited == true, request.AcceptedNoticeVersion),
+ cancellationToken);
+ if (outcome.Refusal is not null)
+ {
+ return outcome.Refusal;
+ }
+
+ if (outcome.Account is not { } userAccount)
+ {
+ return Results.Text(outcome.Message!, statusCode: outcome.Status);
+ }
+
+ var returnUrl = string.IsNullOrWhiteSpace(request.ReturnUrl) ? "/App" : request.ReturnUrl;
+ return JsonResult(
+ new NativeBifrostRegistrationResponse(
+ userAccount.Id,
+ userAccount.BifrostIdentity,
+ userAccount.DisplayName,
+ userAccount.Membership?.Status.ToString() ?? MembershipStatus.Authenticated.ToString(),
+ returnUrl),
+ appJsonSerializerOptions);
+}).AllowAnonymous();
+
+// GET issues a challenge, so it spends the same per-address budget as /auth/bifrost/challenge.
+app.MapGet("/auth/bifrost/register", (
+ HttpContext httpContext,
+ RegistrationChallengeService challenges,
+ RegistrationRateLimit rateLimit,
+ IOptions registrationOptions) =>
+{
+ if (rateLimit.Refuse(httpContext) is { } refused)
+ {
+ return refused;
+ }
+
+ var returnPath = LocalReturnPath.Parse(httpContext.Request.Query["returnUrl"].ToString());
+ return RegistrationFormResult(httpContext, challenges, registrationOptions.Value, new RegistrationPageModel(returnPath.Value, "", 0, registrationOptions.Value.Captcha.FallbackWaitSeconds), null, StatusCodes.Status200OK);
+}).AllowAnonymous();
+
+// No antiforgery token or cookie exists for an anonymous visitor, so a cross-site post is refused by origin instead
+// (RequestOriginGuard, the same Fetch Metadata check as the vote page, except that a request with no Origin and no
+// Sec-Fetch-Site and no session cookie passes: text browsers send neither, and there is no session to replace). Without it a foreign page could post here with
+// a challenge of its own and replace the visitor's session cookie with an empty account holding a forged consent.
+// Order: origin, then the general address budget, then the body cap, then the form; a refusal sets no cookie.
+app.MapPost("/auth/bifrost/register/form", async (
+ HttpContext httpContext,
+ NativeRegistration registration,
+ RegistrationChallengeService challenges,
+ RegistrationRateLimit rateLimit,
+ IOptions hostOptions,
+ IOptions registrationOptions,
+ CancellationToken cancellationToken) =>
+{
+ if (!RequestOriginGuard.AllowsFormWithoutFetchMetadata(httpContext.Request, hostOptions.Value))
+ {
+ return Results.Text("Cross-site registration is refused.", statusCode: StatusCodes.Status403Forbidden);
+ }
+
+ if (rateLimit.Refuse(httpContext) is { } refused)
+ {
+ return refused;
+ }
+
+ if (!(httpContext.Request.ContentType ?? "").StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
+ {
+ return Results.Text("Send the form as application/x-www-form-urlencoded.", statusCode: StatusCodes.Status415UnsupportedMediaType);
+ }
+
+ // The form is a handful of short fields: refuse a big body before reading any of it.
+ const int MaxFormBytes = 16 * 1024;
+ if (httpContext.Request.ContentLength > MaxFormBytes)
+ {
+ return Results.Text("The form is too large.", statusCode: StatusCodes.Status413PayloadTooLarge);
+ }
+
+ if (httpContext.Features.Get() is { IsReadOnly: false } limit)
+ {
+ limit.MaxRequestBodySize = MaxFormBytes;
+ }
+
+ IFormCollection form;
try
{
- var userAccount = await bifrostIdentityService.RegisterNativeAsync(
- request.Identity,
- request.DisplayName,
- cancellationToken);
- await httpContext.SignInAsync(
- CookieAuthenticationDefaults.AuthenticationScheme,
- bifrostIdentityService.BuildPrincipal(userAccount));
-
- var returnUrl = string.IsNullOrWhiteSpace(request.ReturnUrl) ? "/App" : request.ReturnUrl;
- return JsonResult(
- new NativeBifrostRegistrationResponse(
- userAccount.Id,
- userAccount.BifrostIdentity,
- userAccount.DisplayName,
- userAccount.Membership?.Status.ToString() ?? MembershipStatus.Authenticated.ToString(),
- returnUrl),
- appJsonSerializerOptions);
+ form = await httpContext.Request.ReadFormAsync(cancellationToken);
}
- catch (BifrostIdentityException error)
+ catch (BadHttpRequestException error) when (error.StatusCode == StatusCodes.Status413PayloadTooLarge)
{
- return Results.Text(error.Message, statusCode: StatusCodes.Status400BadRequest);
+ return Results.Text("The form is too large.", statusCode: StatusCodes.Status413PayloadTooLarge);
}
+ catch (Exception error) when (error is InvalidDataException or BadHttpRequestException)
+ {
+ return Results.Text("The form could not be read.", statusCode: StatusCodes.Status400BadRequest);
+ }
+
+ string Field(string name) => form[name].FirstOrDefault() ?? "";
+ var returnPath = LocalReturnPath.Parse(Field("returnUrl"));
+ // The checkbox is the consent act and is optional: unticked, the posted notice version is ignored and no receipt is made.
+ // Anything but the canonical decimal of the version in force ("02" included) with the box ticked is sent as -1 and refused, never read as "did not agree".
+ int? accepted = Field("consent") != "yes"
+ ? null
+ : Field("acceptedNoticeVersion") == TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture) ? TrainingNotice.Version : -1;
+ var identity = Field("identity");
+ var displayName = Field("displayName");
+ var challenge = Field("challenge");
+
+ var outcome = await registration.RunAsync(
+ httpContext,
+ new RegistrationAttempt(identity, displayName, challenge, Field("nonce"), Field("waited") == "true", accepted),
+ cancellationToken);
+ if (outcome.Refusal is not null)
+ {
+ return outcome.Refusal;
+ }
+
+ if (outcome.Account is not null)
+ {
+ // A Location header takes ASCII only; anything else is not a path worth keeping.
+ var target = returnPath.Value.All(c => c > ' ' && c < '\u007f') ? returnPath.Value : LocalReturnPath.Default.Value;
+ httpContext.Response.Headers.CacheControl = "no-store";
+ httpContext.Response.Headers.Location = target;
+ return Results.StatusCode(StatusCodes.Status303SeeOther);
+ }
+
+ // A refusal that spent nothing and needs only a correction (a taken identity, a too-early time-lock) keeps its
+ // challenge, whose clock must not restart. Any other failure gets a fresh challenge. The consent box always comes back unchecked.
+ var options = registrationOptions.Value;
+ return RegistrationFormResult(
+ httpContext,
+ challenges,
+ options,
+ new RegistrationPageModel(returnPath.Value, "", 0, options.Captcha.FallbackWaitSeconds, Truncate(identity), Truncate(displayName), outcome.Message, outcome.Field),
+ outcome.KeepChallenge && challenges.IsLive(challenge) ? challenge : null,
+ outcome.Status);
+
+ static string Truncate(string text) => text.Length <= 256 ? text : text[..256];
}).AllowAnonymous();
+app.MapGet("/auth/bifrost/challenge", (HttpContext httpContext, RegistrationChallengeService challenges, RegistrationRateLimit rateLimit) =>
+{
+ if (rateLimit.Refuse(httpContext) is { } refused)
+ {
+ return refused;
+ }
+
+ httpContext.Response.Headers.CacheControl = "no-store";
+ var challenge = challenges.Issue();
+ return challenge is null
+ ? Results.Text("Registration is busy; try again shortly.", statusCode: StatusCodes.Status503ServiceUnavailable)
+ : JsonResult(challenge, appJsonSerializerOptions);
+}).AllowAnonymous();
+
+app.MapGet("/auth/bifrost/notice", () =>
+ JsonResult(new { version = TrainingNotice.Version, text = TrainingNotice.Text }, appJsonSerializerOptions)).AllowAnonymous();
+
+app.MapConsent();
+
app.MapGet("/auth/heimdall/{provider}", async (
string provider,
HttpContext httpContext,
@@ -641,6 +908,8 @@ app.MapPost("/api/sealed-motions/{id:guid}/mind", async (
: await SealedCall(async () => await service.HandleAsync(id, envelope, ct));
}).AllowAnonymous();
+MergeNoticeEndpoints.Map(app);
+
app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
{
httpContext.Response.Headers.CacheControl = "no-store";
@@ -651,15 +920,58 @@ app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
app.MapPost("/auth/heimdall/complete", async (
HttpContext httpContext,
HeimdallAuthService heimdallAuthService,
+ Bifrost.Web.Features.Invites.ChatInviteService chatInvites,
IOptions hostOptions,
ILogger logger,
CancellationToken cancellationToken) =>
{
+ // Every answer here sets or clears an attempt cookie or signs someone in: none may be stored.
+ httpContext.Response.Headers.CacheControl = "no-store";
var form = await ReadFormOrNullAsync(httpContext.Request, cancellationToken);
var attempt = form?["attempt"].ToString();
var held = heimdallAuthService.FindAttemptCookie(httpContext.Request.Cookies, attempt);
+ var linking = held is not null
+ && heimdallAuthService.PurposeOf(held.Value.Value, attempt) is not (null or HeimdallAttemptPurpose.SignIn);
try
{
+ if (linking)
+ {
+ // A link step never signs anyone in: the session in this browser is the one being linked.
+ var step = await heimdallAuthService.ContinueLinkAsync(
+ hostOptions.Value.PublicBaseUrl,
+ attempt,
+ held!.Value.Name,
+ held.Value.Value,
+ form?["code"].ToString(),
+ form?["pendingLinkId"].ToString(),
+ // A folded or frozen account links nothing: the actor accessor's standing decides, not the raw claim.
+ (await httpContext.RequestServices.GetRequiredService().GetAsync(cancellationToken)).Merge is null
+ ? httpContext.User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId)
+ : null,
+ cancellationToken);
+ if (step.Next is not null)
+ {
+ httpContext.Response.Cookies.Append(step.CookieName, step.CookieValue!, HeimdallAttemptCookie.Options());
+ return Results.Redirect(step.Next.ToString());
+ }
+
+ if (step.EnrolTicket is not null)
+ {
+ // The ticket id goes only to the browser that completed the fresh sign-in; the server holds what it is bound to.
+ httpContext.Response.Cookies.Append(BifrostCookies.PasskeyTicket, step.EnrolTicket, new CookieOptions
+ {
+ HttpOnly = true,
+ Secure = true,
+ SameSite = SameSiteMode.Lax,
+ Path = BifrostCookies.Path,
+ MaxAge = Bifrost.Web.Features.Passkeys.PasskeyCeremonies.TicketLifetime
+ });
+ }
+
+ httpContext.Response.Cookies.Delete(step.CookieName, HeimdallAttemptCookie.DeleteOptions());
+ return Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(step.Outcome!.Value, step.ReturnPath));
+ }
+
var signIn = await heimdallAuthService.CompleteAsync(
hostOptions.Value.PublicBaseUrl,
attempt,
@@ -667,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);
}
@@ -678,7 +995,9 @@ app.MapPost("/auth/heimdall/complete", async (
httpContext.Response.Cookies.Delete(held.Value.Name, HeimdallAttemptCookie.DeleteOptions());
}
- return Results.Redirect(HeimdallAuthService.ErrorRedirect);
+ return linking
+ ? Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(HeimdallLinkOutcome.Error, heimdallAuthService.MergeReturnPathOf(held?.Value, attempt)))
+ : Results.Redirect(HeimdallAuthService.ErrorRedirect);
}
}).AllowAnonymous();
@@ -715,11 +1034,45 @@ static async Task ReadFormOrNullAsync(HttpRequest request, Can
}
}
+// Renders the sign-up page with a challenge: the kept one when given, else a fresh one (null when the issuing set is full).
+static IResult RegistrationFormResult(
+ HttpContext httpContext,
+ RegistrationChallengeService challenges,
+ RegistrationOptions options,
+ RegistrationPageModel model,
+ string? keepChallenge,
+ int statusCode)
+{
+ var token = keepChallenge;
+ var difficulty = options.Captcha.Difficulty;
+ if (token is null)
+ {
+ var issued = challenges.Issue();
+ if (issued is null)
+ {
+ return Results.Text("Registration is busy; try again shortly.", statusCode: StatusCodes.Status503ServiceUnavailable);
+ }
+
+ token = issued.Challenge;
+ difficulty = issued.Difficulty;
+ }
+
+ httpContext.Response.Headers.CacheControl = "no-store";
+ return Results.Content(
+ RegistrationPage.Render(model with { Challenge = token, Difficulty = difficulty }),
+ "text/html; charset=utf-8",
+ statusCode: statusCode);
+}
+
static async Task WriteSignInChooserAsync(HttpContext httpContext, string returnUrl)
{
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
+ : $"""GitHub OAuth""";
await httpContext.Response.WriteAsync($$"""
@@ -744,7 +1097,7 @@ static async Task WriteSignInChooserAsync(HttpContext httpContext, string return
Create or use a Bifrost patron account
Choose a provider to attach this checkout to a Bifrost account. Patron accounts do not automatically grant active member access.
- GitHub OAuth
+ {{gitHubChoice}}
Discord HeimdallPatreon HeimdallTwitch Heimdall
@@ -768,7 +1121,11 @@ public partial class Program;
public sealed record NativeBifrostRegistrationRequest(
string Identity,
string? DisplayName,
- string? ReturnUrl);
+ string? ReturnUrl,
+ string? Challenge,
+ string? Nonce,
+ int? AcceptedNoticeVersion,
+ bool? Waited = null);
public sealed record NativeBifrostRegistrationResponse(
Guid UserAccountId,
diff --git a/src/Bifrost.Web/ViewComponents/MergeNotice.cs b/src/Bifrost.Web/ViewComponents/MergeNotice.cs
new file mode 100644
index 0000000..5a3c779
--- /dev/null
+++ b/src/Bifrost.Web/ViewComponents/MergeNotice.cs
@@ -0,0 +1,57 @@
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Shared;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.ViewComponents;
+
+///
+/// The layout's merge notice for a signed-in actor: the survivor of a Committed or UndoRequested merge inside its grace (days left), a
+/// frozen account (a merge is in progress) or a folded one (where to sign in). It reads the merge row once per page view and keeps no
+/// state of its own; the words are 's, and no account name or id is ever in them.
+///
+public sealed class MergeNotice(ICurrentBifrostActorAccessor actors, BifrostDbContext dbContext, TimeProvider timeProvider) : ViewComponent
+{
+ public async Task InvokeAsync()
+ {
+ var actor = await actors.GetAsync(HttpContext.RequestAborted);
+ var text = await TextAsync(actor, HttpContext.RequestAborted);
+ return text is null ? Content(string.Empty) : View("Default", text);
+ }
+
+ private async Task TextAsync(CurrentBifrostActor actor, CancellationToken cancellationToken)
+ {
+ var now = timeProvider.GetUtcNow();
+ if (actor.Merge is { } standing)
+ {
+ if (standing is MergeStanding.Frozen)
+ {
+ return MergeWording.FrozenNotice();
+ }
+
+ var mergedOn = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => x.Id == standing.MergeId)
+ .Select(x => x.CommittedUtc ?? x.CreatedUtc)
+ .FirstOrDefaultAsync(cancellationToken);
+ return MergeWording.FoldedNotice(mergedOn);
+ }
+
+ if (actor.UserAccount is not { } account)
+ {
+ return null;
+ }
+
+ var open = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => x.SurvivorUserAccountId == account.Id
+ && (x.State == AccountMergeState.Committed || x.State == AccountMergeState.UndoRequested)
+ && x.GraceEndsUtc > now)
+ .OrderBy(x => x.GraceEndsUtc)
+ .Select(x => new { x.State, x.GraceEndsUtc })
+ .FirstOrDefaultAsync(cancellationToken);
+ return open is null ? null
+ : open.State == AccountMergeState.UndoRequested ? MergeWording.UndoRequestedNotice()
+ : MergeWording.SurvivorNotice(MergeWording.DaysUntil(open.GraceEndsUtc!.Value, now));
+ }
+}
diff --git a/src/Bifrost.Web/appsettings.json b/src/Bifrost.Web/appsettings.json
index 47bbb7b..09b3310 100644
--- a/src/Bifrost.Web/appsettings.json
+++ b/src/Bifrost.Web/appsettings.json
@@ -28,6 +28,7 @@
"BaseUrl": "https://heimdall.gamecult.org",
"AppSlug": "bifrost",
"AppSecret": "",
+ "AppSecretFile": "",
"DiscordGuildId": "",
"DiscordAllowedRoleIds": [],
"PatreonTierTitle": "Inner Sanctum",
diff --git a/src/Bifrost.Web/packages.lock.json b/src/Bifrost.Web/packages.lock.json
index bd15130..796baa1 100644
--- a/src/Bifrost.Web/packages.lock.json
+++ b/src/Bifrost.Web/packages.lock.json
@@ -8,6 +8,30 @@
"resolved": "2.4.0",
"contentHash": "SwXsAV3sMvAU/Nn31pbjhWurYSjJ+/giI/0n6tCrYoupEK34iIHCuk3STAd9fx8yudM85KkLSVdn951vTng/vQ=="
},
+ "Fido2": {
+ "type": "Direct",
+ "requested": "[4.3.3, )",
+ "resolved": "4.3.3",
+ "contentHash": "++G8ohXlhp9AH49FXIvYqziXUAEpuCtT+z5HBevX6+Pl6sYz9zfDHGTgvne6t3UEhM0hudesgMudyNG7RlpaEA==",
+ "dependencies": {
+ "Fido2.Models": "4.3.3",
+ "Microsoft.Extensions.Http": "9.0.0",
+ "Microsoft.IdentityModel.JsonWebTokens": "8.2.0",
+ "NSec.Cryptography": "25.4.0",
+ "System.Formats.Cbor": "9.0.24"
+ }
+ },
+ "MessagePack": {
+ "type": "Direct",
+ "requested": "[3.1.12, )",
+ "resolved": "3.1.12",
+ "contentHash": "m1QEsd59gUj82ji5tEQbZiyjV6y0F7cYfGVhil6pAlNZpyzR7ze9TucMu4lPpi8cZAV8aNl3D9/T9J1HbFz15Q==",
+ "dependencies": {
+ "MessagePack.Annotations": "3.1.12",
+ "MessagePackAnalyzer": "3.1.12",
+ "Microsoft.NET.StringTools": "17.11.4"
+ }
+ },
"Microsoft.EntityFrameworkCore.Design": {
"type": "Direct",
"requested": "[8.0.0, )",
@@ -75,17 +99,59 @@
"OpenIddict.Server": "7.7.1"
}
},
+ "OpenIddict.Validation.AspNetCore": {
+ "type": "Direct",
+ "requested": "[7.7.1, )",
+ "resolved": "7.7.1",
+ "contentHash": "9Gpw13k6KRif6LCeIfzS5cfDPxzEvg5I4l8JKwMxNL4mqal8eT00T069RnuXuDY8CwOO43FLD55JY7Wh3an5cg==",
+ "dependencies": {
+ "OpenIddict.Validation": "7.7.1"
+ }
+ },
+ "OpenIddict.Validation.ServerIntegration": {
+ "type": "Direct",
+ "requested": "[7.7.1, )",
+ "resolved": "7.7.1",
+ "contentHash": "tZd5oqlVHftWjo3gthwXRvDE09NGmOjo5yjyRH8W2q4Yw9Hntkfi70+T2ESFKJ++oqueQT4YG5ilyot/o0OBMA==",
+ "dependencies": {
+ "OpenIddict.Server": "7.7.1",
+ "OpenIddict.Validation": "7.7.1"
+ }
+ },
"System.Text.Json": {
"type": "Direct",
"requested": "[8.0.5, )",
"resolved": "8.0.5",
"contentHash": "0f1B50Ss7rqxXiaBJyzUu9bWFOO2/zSlifZ/UNMdiIpDYe4cY4LQQicP4nirK1OS31I43rn062UIJ1Q9bpmHpg=="
},
+ "Fido2.Models": {
+ "type": "Transitive",
+ "resolved": "4.3.3",
+ "contentHash": "G/Q8MYgptOwMrbWgDoGsy90u3J5GTdNAHub8aZRg/mQrUETzB5CqFzstGdTXE9UhL0qD6sRynOoPUnqCwKRnMw==",
+ "dependencies": {
+ "Microsoft.Bcl.Memory": "9.0.14"
+ }
+ },
"Humanizer.Core": {
"type": "Transitive",
"resolved": "2.14.1",
"contentHash": "lQKvtaTDOXnoVJ20ibTuSIOf2i0uO0MPbDhd1jm238I+U/2ZnRENj0cktKZhtchBMtCUSRQ5v4xBCUbKNmyVMw=="
},
+ "libsodium": {
+ "type": "Transitive",
+ "resolved": "1.0.20.1",
+ "contentHash": "pkiceEqJDQFHjbga3k/oPfTVX9g+GKJZ1VrkuiLhaymt9YNw1Dr7cX9hNuZuNaWcr9WD0moW55k4pMwzQ7JaZQ=="
+ },
+ "MessagePack.Annotations": {
+ "type": "Transitive",
+ "resolved": "3.1.12",
+ "contentHash": "LdI67sY7F3KK+JsrG02+DP1XFkowaZSoyfL2M88hjm1MOOsjf8amBLAJolV+zxoPUZf3uGbKzq1cMQD8PlpSpA=="
+ },
+ "MessagePackAnalyzer": {
+ "type": "Transitive",
+ "resolved": "3.1.12",
+ "contentHash": "iNSNatPh6bafRUbkQKlClExjpPpd8hiZgfZsodGf7bheIlkizGbMzsJ2mPui8jOHRe4Ky9eg5ou/fFzI7CT3fg=="
+ },
"Microsoft.Bcl.AsyncInterfaces": {
"type": "Transitive",
"resolved": "6.0.0",
@@ -99,6 +165,11 @@
"System.Formats.Asn1": "10.0.2"
}
},
+ "Microsoft.Bcl.Memory": {
+ "type": "Transitive",
+ "resolved": "9.0.14",
+ "contentHash": "laQCcjTM2FnbyznkAu9hwBuQh3z2/OtJKwjGkJOUevylFpFXZIUVq/+MU2jM0HQm1n5wsjjwtLIDOiWJ6Nai3A=="
+ },
"Microsoft.CodeAnalysis.Analyzers": {
"type": "Transitive",
"resolved": "3.3.3",
@@ -186,26 +257,43 @@
"Microsoft.Extensions.Primitives": "8.0.0"
}
},
+ "Microsoft.Extensions.Configuration": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "YIMO9T3JL8MeEXgVozKt2v79hquo/EFtnY0vgxmLnUvk1Rei/halI7kOWZL2RBeV9FMGzgM9LZA8CVaNwFMaNA==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Primitives": "9.0.0"
+ }
+ },
"Microsoft.Extensions.Configuration.Abstractions": {
"type": "Transitive",
- "resolved": "8.0.0",
- "contentHash": "3lE/iLSutpgX1CC0NOW70FJoGARRHbyKmG7dc0klnUZ9Dd9hS6N/POPWhKhMLCEuNN5nXEY5agmlFtH562vqhQ==",
+ "resolved": "9.0.0",
+ "contentHash": "lqvd7W3FGKUO1+ZoUEMaZ5XDJeWvjpy2/M/ptCGz3tXLD4HWVaSzjufsAsjemasBEg+2SxXVtYVvGt5r2nKDlg==",
"dependencies": {
- "Microsoft.Extensions.Primitives": "8.0.0"
+ "Microsoft.Extensions.Primitives": "9.0.0"
+ }
+ },
+ "Microsoft.Extensions.Configuration.Binder": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "RiScL99DcyngY9zJA2ROrri7Br8tn5N4hP4YNvGdTN/bvg1A3dwvDOxHnNZ3Im7x2SJ5i4LkX1uPiR/MfSFBLQ==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration.Abstractions": "9.0.0"
}
},
"Microsoft.Extensions.DependencyInjection": {
"type": "Transitive",
- "resolved": "8.0.1",
- "contentHash": "BmANAnR5Xd4Oqw7yQ75xOAYODybZQRzdeNucg7kS5wWKd2PNnMdYtJ2Vciy0QLylRmv42DGl5+AFL9izA6F1Rw==",
+ "resolved": "9.0.0",
+ "contentHash": "MCPrg7v3QgNMr0vX4vzRXvkNGgLg8vKWX0nKCWUxu2uPyMsaRgiRc1tHBnbTcfJMhMKj2slE/j2M9oGkd25DNw==",
"dependencies": {
- "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0"
}
},
"Microsoft.Extensions.DependencyInjection.Abstractions": {
"type": "Transitive",
- "resolved": "8.0.2",
- "contentHash": "3iE7UF7MQkCv1cxzCahz+Y/guQbTqieyxyaWKhrRO91itI9cOKO76OHeQDahqG4MmW5umr3CcCvGmK92lWNlbg=="
+ "resolved": "9.0.0",
+ "contentHash": "+6f2qv2a3dLwd5w6JanPIPs47CxRbnk+ZocMJUhv9NxP88VlOcJYZs9jY+MYSjxvady08bUZn6qgiNh7DadGgg=="
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
@@ -216,37 +304,83 @@
"System.Text.Json": "8.0.0"
}
},
+ "Microsoft.Extensions.Diagnostics": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "0CF9ZrNw5RAlRfbZuVIvzzhP8QeWqHiUmMBU/2H7Nmit8/vwP3/SbHeEctth7D4Gz2fBnEbokPc1NU8/j/1ZLw==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration": "9.0.0",
+ "Microsoft.Extensions.Diagnostics.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options.ConfigurationExtensions": "9.0.0"
+ }
+ },
+ "Microsoft.Extensions.Diagnostics.Abstractions": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "1K8P7XzuzX8W8pmXcZjcrqS6x5eSSdvhQohmcpgiQNY/HlDAlnrhR9dvlURfFz428A+RTCJpUyB+aKTA6AgVcQ==",
+ "dependencies": {
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options": "9.0.0",
+ "System.Diagnostics.DiagnosticSource": "9.0.0"
+ }
+ },
+ "Microsoft.Extensions.Http": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "DqI4q54U4hH7bIAq9M5a/hl5Odr/KBAoaZ0dcT4OgutD8dook34CbkvAfAIzkMVjYXiL+E5ul9etwwqiX4PHGw==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Diagnostics": "9.0.0",
+ "Microsoft.Extensions.Logging": "9.0.0",
+ "Microsoft.Extensions.Logging.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options": "9.0.0"
+ }
+ },
"Microsoft.Extensions.Logging": {
"type": "Transitive",
- "resolved": "8.0.1",
- "contentHash": "4x+pzsQEbqxhNf1QYRr5TDkLP9UsLT3A6MdRKDDEgrW7h1ljiEPgTNhKYUhNCCAaVpQECVQ+onA91PTPnIp6Lw==",
+ "resolved": "9.0.0",
+ "contentHash": "crjWyORoug0kK7RSNJBTeSE6VX8IQgLf3nUpTB9m62bPXp/tzbnOsnbe8TXEG0AASNaKZddnpHKw7fET8E++Pg==",
"dependencies": {
- "Microsoft.Extensions.DependencyInjection": "8.0.1",
- "Microsoft.Extensions.Logging.Abstractions": "8.0.2",
- "Microsoft.Extensions.Options": "8.0.2"
+ "Microsoft.Extensions.DependencyInjection": "9.0.0",
+ "Microsoft.Extensions.Logging.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options": "9.0.0"
}
},
"Microsoft.Extensions.Logging.Abstractions": {
"type": "Transitive",
- "resolved": "8.0.2",
- "contentHash": "nroMDjS7hNBPtkZqVBbSiQaQjWRDxITI8Y7XnDs97rqG3EbzVTNLZQf7bIeUJcaHOV8bca47s1Uxq94+2oGdxA==",
+ "resolved": "9.0.0",
+ "contentHash": "g0UfujELzlLbHoVG8kPKVBaW470Ewi+jnptGS9KUi6jcb+k2StujtK3m26DFSGGwQ/+bVgZfsWqNzlP6YOejvw==",
"dependencies": {
- "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "System.Diagnostics.DiagnosticSource": "9.0.0"
}
},
"Microsoft.Extensions.Options": {
"type": "Transitive",
- "resolved": "8.0.2",
- "contentHash": "dWGKvhFybsaZpGmzkGCbNNwBD1rVlWzrZKANLW/CcbFJpCEceMCGzT7zZwHOGBCbwM0SzBuceMj5HN1LKV1QqA==",
+ "resolved": "9.0.0",
+ "contentHash": "y2146b3jrPI3Q0lokKXdKLpmXqakYbDIPDV6r3M8SqvSf45WwOTzkyfDpxnZXJsJQEpAsAqjUq5Pu8RCJMjubg==",
"dependencies": {
- "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0",
- "Microsoft.Extensions.Primitives": "8.0.0"
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Primitives": "9.0.0"
+ }
+ },
+ "Microsoft.Extensions.Options.ConfigurationExtensions": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "Ob3FXsXkcSMQmGZi7qP07EQ39kZpSBlTcAZLbJLdI4FIf0Jug8biv2HTavWmnTirchctPlq9bl/26CXtQRguzA==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Configuration.Binder": "9.0.0",
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options": "9.0.0",
+ "Microsoft.Extensions.Primitives": "9.0.0"
}
},
"Microsoft.Extensions.Primitives": {
"type": "Transitive",
- "resolved": "8.0.0",
- "contentHash": "bXJEZrW9ny8vjMF1JV253WeLhpEVzFo1lyaZu1vQ4ZxWUlVvknZ/+ftFgVheLubb4eZPSwwxBeqS1JkCOjxd8g=="
+ "resolved": "9.0.0",
+ "contentHash": "N3qEBzmLMYiASUlKxxFIISP4AiwuPTHF5uCh+2CWSwwzAJiIYx0kBJsS30cp1nvhSySFAVi30jecD307jV+8Kg=="
},
"Microsoft.IdentityModel.Abstractions": {
"type": "Transitive",
@@ -269,6 +403,14 @@
"Microsoft.IdentityModel.Abstractions": "8.19.2"
}
},
+ "Microsoft.IdentityModel.Protocols": {
+ "type": "Transitive",
+ "resolved": "8.19.2",
+ "contentHash": "sGxSsSrZXNmca6D+jHH2rVRyo2nNRd/g4H9CFbPmLLq0xgoH1U0orLWE5minfijw7+zq49tBs7txenbfAErRoQ==",
+ "dependencies": {
+ "Microsoft.IdentityModel.Tokens": "8.19.2"
+ }
+ },
"Microsoft.IdentityModel.Tokens": {
"type": "Transitive",
"resolved": "8.19.2",
@@ -279,6 +421,11 @@
"Microsoft.IdentityModel.Logging": "8.19.2"
}
},
+ "Microsoft.NET.StringTools": {
+ "type": "Transitive",
+ "resolved": "17.11.4",
+ "contentHash": "mudqUHhNpeqIdJoUx2YDWZO/I9uEDYVowan89R6wsomfnUJQk6HteoQTlNjZDixhT2B4IXMkMtgZtoceIjLRmA=="
+ },
"Mono.TextTemplating": {
"type": "Transitive",
"resolved": "2.2.1",
@@ -287,6 +434,14 @@
"System.CodeDom": "4.4.0"
}
},
+ "NSec.Cryptography": {
+ "type": "Transitive",
+ "resolved": "25.4.0",
+ "contentHash": "Z3wPpG0xefMLmhn9T+Ka/EzAmMQPT0THL/5E4lf9cXI/N9rbGH0G23ZFpRcPnD0ast2k7ieG6QSVNIjmfPCXBQ==",
+ "dependencies": {
+ "libsodium": "[1.0.20.1, 1.0.21)"
+ }
+ },
"OpenIddict.Abstractions": {
"type": "Transitive",
"resolved": "7.7.1",
@@ -323,6 +478,17 @@
"OpenIddict.Abstractions": "7.7.1"
}
},
+ "OpenIddict.Validation": {
+ "type": "Transitive",
+ "resolved": "7.7.1",
+ "contentHash": "09FOsvek+iSKrNbEehH2c1uBWSFurZk1U8vyTKk5aiaCV2bbj+j/68KRA/iHOgSe8qV3+0ZrquhmjFMpcojVSw==",
+ "dependencies": {
+ "Microsoft.Extensions.Logging": "8.0.1",
+ "Microsoft.IdentityModel.JsonWebTokens": "8.19.2",
+ "Microsoft.IdentityModel.Protocols": "8.19.2",
+ "OpenIddict.Abstractions": "7.7.1"
+ }
+ },
"System.CodeDom": {
"type": "Transitive",
"resolved": "4.4.0",
@@ -384,11 +550,21 @@
"System.Composition.Runtime": "6.0.0"
}
},
+ "System.Diagnostics.DiagnosticSource": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "ddppcFpnbohLWdYKr/ZeLZHmmI+DXFgZ3Snq+/E7SwcdW4UnvxmaugkwGywvGVWkHPGCSZjCP+MLzu23AL5SDw=="
+ },
"System.Formats.Asn1": {
"type": "Transitive",
"resolved": "10.0.2",
"contentHash": "9Hee6iQ74pDgdRNIL6lO8Vlx2onVWd5aDnqwk4Pvo0h5FklBd7QwcQDKgxeLuhiy0o3ibzUVO0KFQe0/hPXU+Q=="
},
+ "System.Formats.Cbor": {
+ "type": "Transitive",
+ "resolved": "9.0.24",
+ "contentHash": "SEfEvHu6qXcXoDsDKagddLDf8A9iHIhHUD0hGemdmwlP206KLLCI5ksskOpeXMgNpQCs2diB0fOBKcnjySHFUQ=="
+ },
"System.IO.Pipelines": {
"type": "Transitive",
"resolved": "6.0.3",
diff --git a/src/Bifrost.Web/wwwroot/js/passkeys.js b/src/Bifrost.Web/wwwroot/js/passkeys.js
new file mode 100644
index 0000000..3d898f0
--- /dev/null
+++ b/src/Bifrost.Web/wwwroot/js/passkeys.js
@@ -0,0 +1,125 @@
+// The Linked accounts page's passkey ceremonies (docs/passkeys.md). First-party, no dependency. It asks the server for
+// WebAuthn options, calls navigator.credentials, and posts back only base64url strings in a same-origin form. Nothing it
+// reads from the options is shown or evaluated; the server checks the origin, the challenge and the signature.
+(function () {
+ "use strict";
+
+ var status = document.getElementById("passkey-status");
+
+ function say(text) {
+ if (status) {
+ status.textContent = text;
+ }
+ }
+
+ function toBytes(value) {
+ var padded = value.replace(/-/g, "+").replace(/_/g, "/");
+ while (padded.length % 4) {
+ padded += "=";
+ }
+ var raw = atob(padded);
+ var bytes = new Uint8Array(raw.length);
+ for (var i = 0; i < raw.length; i++) {
+ bytes[i] = raw.charCodeAt(i);
+ }
+ return bytes.buffer;
+ }
+
+ function toText(buffer) {
+ var bytes = new Uint8Array(buffer);
+ var raw = "";
+ for (var i = 0; i < bytes.length; i++) {
+ raw += String.fromCharCode(bytes[i]);
+ }
+ return btoa(raw).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+ }
+
+ function token(form) {
+ var field = form.querySelector("input[name=__RequestVerificationToken]");
+ return field ? field.value : "";
+ }
+
+ // Posts to a handler of this page with the form's antiforgery token and returns the parsed JSON, or throws.
+ function options(handler, form, fields) {
+ return fetch(location.pathname + "?handler=" + handler, {
+ method: "POST",
+ credentials: "same-origin",
+ headers: { "RequestVerificationToken": token(form), "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams(fields)
+ }).then(function (response) {
+ return response.json().then(function (body) {
+ if (!response.ok) {
+ throw new Error(body && body.error ? body.error : "error");
+ }
+ return body;
+ });
+ });
+ }
+
+ function descriptors(list) {
+ return (list || []).map(function (item) {
+ var copy = { type: item.type, id: toBytes(item.id) };
+ if (item.transports) {
+ copy.transports = item.transports;
+ }
+ return copy;
+ });
+ }
+
+ function set(form, name, value) {
+ form.elements[name].value = value;
+ }
+
+ function failed(error) {
+ var code = error && error.message ? error.message : "error";
+ location.assign(location.pathname + "?result=" + (/^[a-z_]+$/.test(code) && code !== "error" ? encodeURIComponent(code) : "passkey_failed"));
+ }
+
+ document.querySelectorAll("form[data-passkey-enrol]").forEach(function (form) {
+ form.addEventListener("submit", function (event) {
+ if (form.dataset.ready === "1") {
+ return;
+ }
+ event.preventDefault();
+ say("Waiting for your device...");
+ options("PasskeyEnrolOptions", form, {}).then(function (created) {
+ created.challenge = toBytes(created.challenge);
+ created.user.id = toBytes(created.user.id);
+ created.excludeCredentials = descriptors(created.excludeCredentials);
+ return navigator.credentials.create({ publicKey: created });
+ }).then(function (credential) {
+ set(form, "id", credential.id);
+ set(form, "rawId", toText(credential.rawId));
+ set(form, "attestationObject", toText(credential.response.attestationObject));
+ set(form, "clientDataJson", toText(credential.response.clientDataJSON));
+ set(form, "transports", credential.response.getTransports ? credential.response.getTransports().join(",") : "");
+ form.dataset.ready = "1";
+ form.submit();
+ }).catch(failed);
+ });
+ });
+
+ document.querySelectorAll("form[data-passkey-unlink]").forEach(function (form) {
+ form.addEventListener("submit", function (event) {
+ if (form.dataset.ready === "1") {
+ return;
+ }
+ event.preventDefault();
+ say("Waiting for your device...");
+ options("PasskeyChallenge", form, { identityId: form.elements.identityId.value }).then(function (requested) {
+ requested.challenge = toBytes(requested.challenge);
+ requested.allowCredentials = descriptors(requested.allowCredentials);
+ return navigator.credentials.get({ publicKey: requested });
+ }).then(function (credential) {
+ set(form, "id", credential.id);
+ set(form, "rawId", toText(credential.rawId));
+ set(form, "authenticatorData", toText(credential.response.authenticatorData));
+ set(form, "clientDataJson", toText(credential.response.clientDataJSON));
+ set(form, "signature", toText(credential.response.signature));
+ set(form, "userHandle", credential.response.userHandle ? toText(credential.response.userHandle) : "");
+ form.dataset.ready = "1";
+ form.submit();
+ }).catch(failed);
+ });
+ });
+})();
diff --git a/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs b/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs
new file mode 100644
index 0000000..e148132
--- /dev/null
+++ b/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs
@@ -0,0 +1,439 @@
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Tests.Support;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Bifrost.Web.Tests;
+
+/// A folded member's browser and Heimdall's patron intake, over HTTP: the merge ledger is the single gate behind both.
+public sealed class AccountMergeHttpTests(TestWebApplicationFactory factory) : IClassFixture
+{
+ private sealed record Seeded(Guid Survivor, Guid Folded, Guid Motion, string FoldedHeimdallId, long SurvivorGitHubId, long FoldedGitHubId);
+
+ private async Task SeedAsync()
+ {
+ using var scope = factory.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var seed = Random.Shared.NextInt64(1_000_000, 900_000_000);
+ UserAccount Make(string name, long gitHubId) => new()
+ {
+ DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = name, GitHubUserId = gitHubId, GitHubLogin = name, NormalizedGitHubLogin = name,
+ HeimdallAccountId = "hd-" + name,
+ MemberProfile = new MemberProfile { Nickname = name, Headline = "seed", UpdatedAtUtc = DateTimeOffset.UtcNow },
+ Membership = new Bifrost.Web.Domain.Membership { Status = MembershipStatus.Active, ApprovedAtUtc = DateTimeOffset.UtcNow }
+ };
+ var survivor = Make($"surv-{seed}", seed);
+ var folded = Make($"fold-{seed}", seed + 1);
+ db.UserAccounts.AddRange(survivor, folded);
+ var motion = new Motion
+ {
+ CreatedByUserAccountId = survivor.Id, Title = "Open motion", Status = MotionStatus.Open, OpensAtUtc = DateTimeOffset.UtcNow.AddHours(-1),
+ ClosesAtUtc = DateTimeOffset.UtcNow.AddDays(2), CreatedAtUtc = DateTimeOffset.UtcNow
+ };
+ db.Motions.Add(motion);
+ await db.SaveChangesAsync();
+ return new Seeded(survivor.Id, folded.Id, motion.Id, folded.HeimdallAccountId, seed, seed + 1);
+ }
+
+ private HttpClient ClientFor(long gitHubId, string login)
+ {
+ var client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, BaseAddress = new Uri("https://localhost"), HandleCookies = true });
+ client.DefaultRequestHeaders.Add("X-Test-GitHub-Id", gitHubId.ToString());
+ client.DefaultRequestHeaders.Add("X-Test-GitHub-Login", login);
+ return client;
+ }
+
+ private static async Task TokenAsync(HttpClient client)
+ {
+ using var page = await client.GetAsync("/App/Motions");
+ var html = await page.Content.ReadAsStringAsync();
+ var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
+ Assert.NotEmpty(token);
+ return token;
+ }
+
+ private static Task VoteAsync(HttpClient client, Guid motion, string token) =>
+ client.PostAsync("/App/Motions?handler=Vote", new FormUrlEncodedContent(new Dictionary
+ {
+ ["motionId"] = motion.ToString(), ["choice"] = "For", ["comment"] = "yes", ["__RequestVerificationToken"] = token
+ }));
+
+ private async Task WithDb(Func> read)
+ {
+ using var scope = factory.Services.CreateScope();
+ return await read(scope.ServiceProvider.GetRequiredService());
+ }
+
+ private Task VoteRowsAsync(Guid motion) => WithDb(db => db.Votes.IgnoreQueryFilters().CountAsync(x => x.MotionId == motion));
+
+ private async Task MergeAsync(Seeded s, AccountMergeState state)
+ {
+ using var scope = factory.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var merge = new AccountMerge { SurvivorUserAccountId = s.Survivor, FoldedUserAccountId = s.Folded, State = state, CreatedUtc = DateTimeOffset.UtcNow };
+ db.AccountMerges.Add(merge);
+ await db.SaveChangesAsync();
+ return merge.Id;
+ }
+
+ private async Task SetStateAsync(Guid mergeId, AccountMergeState state) =>
+ await WithDb(async db =>
+ {
+ (await db.AccountMerges.SingleAsync(x => x.Id == mergeId)).State = state;
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ [Fact]
+ public async Task A_folded_session_cookie_acts_as_nobody_while_Frozen_and_after_Committed_and_the_survivor_still_votes()
+ {
+ var s = await SeedAsync();
+ using var folded = ClientFor(s.FoldedGitHubId, $"fold-{s.SurvivorGitHubId}");
+ var token = await TokenAsync(folded); // a live, valid form from before the merge: the cookie outlives the merge
+ var merge = await MergeAsync(s, AccountMergeState.Confirmed);
+
+ using (var whileFrozen = await VoteAsync(folded, s.Motion, token))
+ {
+ Assert.NotEqual(HttpStatusCode.OK, whileFrozen.StatusCode);
+ }
+
+ Assert.Equal(0, await VoteRowsAsync(s.Motion));
+ using (var page = await folded.GetAsync("/App/Motions"))
+ {
+ Assert.NotEqual(HttpStatusCode.OK, page.StatusCode);
+ }
+
+ await SetStateAsync(merge, AccountMergeState.HeimdallMoved);
+ await SetStateAsync(merge, AccountMergeState.Committed);
+ using (var afterCommit = await VoteAsync(folded, s.Motion, token))
+ {
+ Assert.NotEqual(HttpStatusCode.OK, afterCommit.StatusCode);
+ }
+
+ Assert.Equal(0, await VoteRowsAsync(s.Motion));
+
+ using var survivor = ClientFor(s.SurvivorGitHubId, $"surv-{s.SurvivorGitHubId}");
+ using var control = await VoteAsync(survivor, s.Motion, await TokenAsync(survivor));
+ Assert.Equal(HttpStatusCode.Redirect, control.StatusCode);
+ Assert.Equal(1, await VoteRowsAsync(s.Motion));
+ }
+
+ private async Task IntakeAsync(Seeded s, string eventId)
+ {
+ var payload = JsonSerializer.Serialize(new
+ {
+ heimdallAccountId = s.FoldedHeimdallId, provider = "PayPal", providerEventId = eventId, kind = "OneTimeDonation",
+ amount = 25m, currencyCode = "USD", externalSupportId = "CAPTURE-1", supportedAtUtc = DateTimeOffset.UtcNow, isCurrentRecurringSupport = false
+ });
+ using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes("test-heimdall-intake-secret"));
+ using var request = new HttpRequestMessage(HttpMethod.Post, "/heimdall/patron-support/events");
+ request.Headers.Add("X-Heimdall-Signature-256", "sha256=" + Convert.ToHexString(hasher.ComputeHash(Encoding.UTF8.GetBytes(payload))).ToLowerInvariant());
+ request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
+ using var client = factory.CreateClient();
+ using var response = await client.SendAsync(request);
+ return response.StatusCode;
+ }
+
+ private Task> EventOwnersAsync(Seeded s) =>
+ WithDb(db => db.PatronSupportEvents.Where(x => x.UserAccountId == s.Survivor || x.UserAccountId == s.Folded).Select(x => x.UserAccountId).ToListAsync());
+
+ /// Lands the merge through the ledger's own commit, as the saga will: the move done, then the Bifrost records reduced.
+ private async Task CommitMergeAsync(Seeded s)
+ {
+ var merge = await MergeAsync(s, AccountMergeState.HeimdallMoved);
+ await WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().CommitAsync(merge, default);
+ return 0;
+ });
+ return merge;
+ }
+
+ [Fact]
+ public async Task Patron_intake_for_a_folded_heimdall_id_records_on_the_survivor()
+ {
+ var s = await SeedAsync();
+ await MergeAsync(s, AccountMergeState.Final);
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, $"WH-{Guid.NewGuid():N}"));
+
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task A_patron_event_that_lands_during_grace_is_journalled_once_and_undo_moves_it_back_to_the_folded_account()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+ var eventId = $"WH-{Guid.NewGuid():N}";
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId));
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId)); // the provider retries: nothing doubles
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ Assert.Equal(1, await WithDb(db => db.AccountMergeEntries.CountAsync(x => x.MergeId == merge && x.Kind == AccountMergeEntryKind.PatronSupportEvent)));
+
+ await SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default);
+ return 0;
+ });
+
+ Assert.Equal([s.Folded], await EventOwnersAsync(s));
+ }
+
+ private Task> PatronJournalAsync(Guid merge) =>
+ WithDb(db => db.AccountMergeEntries.Where(x => x.MergeId == merge).OrderBy(x => x.Seq).ToListAsync());
+
+ [Fact]
+ public async Task A_single_patron_event_during_grace_is_journalled_by_its_own_delivery_and_undo_moves_it_back()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, $"WH-{Guid.NewGuid():N}")); // no retry follows
+
+ var journal = await PatronJournalAsync(merge);
+ Assert.Single(journal, x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count()); // the new entry takes its own Seq
+ await SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default);
+ return 0;
+ });
+ Assert.Equal([s.Folded], await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task A_provider_retry_journals_an_event_the_first_delivery_left_unjournalled()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+ var eventId = $"WH-{Guid.NewGuid():N}";
+ await WithDb(async db => // the first delivery recorded on the survivor, then died before journalling
+ {
+ db.PatronSupportEvents.Add(new PatronSupportEvent
+ {
+ UserAccountId = s.Survivor, Provider = ExternalPatronProvider.PayPal, ProviderEventId = eventId, ExternalSupportId = "CAPTURE-1",
+ Kind = PatronSupportEventKind.OneTimeDonation, Amount = 25m, SupportedAtUtc = DateTimeOffset.UtcNow, RecordedAtUtc = DateTimeOffset.UtcNow
+ });
+ await db.SaveChangesAsync();
+ return 0;
+ });
+ Assert.DoesNotContain(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId));
+
+ Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task A_stripe_checkout_opened_by_an_account_that_folded_pays_the_survivor_and_is_journalled()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+ using var response = await StripeCheckoutAsync(s);
+
+ Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ var entry = Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal(s.Folded, entry.PriorUserAccountId); // the journal names the folded account as the previous owner
+
+ await SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await UndoAsync(merge);
+ Assert.Equal([s.Folded], await EventOwnersAsync(s)); // so an undo sends the donation back where it was opened
+ }
+
+ private async Task StripeCheckoutAsync(Seeded s)
+ {
+ var payload = JsonSerializer.Serialize(new
+ {
+ id = $"evt_{Guid.NewGuid():N}", type = "checkout.session.completed", created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
+ data = new { @object = new { id = $"cs_{Guid.NewGuid():N}", customer = "cus_1", currency = "usd", amount_total = 1900, payment_status = "paid",
+ metadata = new Dictionary { ["bifrost_user_account_id"] = s.Folded.ToString("N") } } }
+ });
+ var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
+ using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes("whsec_test_webhook_secret"));
+ using var request = new HttpRequestMessage(HttpMethod.Post, "/patronage/stripe/webhook");
+ request.Headers.Add("Stripe-Signature", $"t={timestamp},v1={Convert.ToHexString(hasher.ComputeHash(Encoding.UTF8.GetBytes($"{timestamp}.{payload}"))).ToLowerInvariant()}");
+ request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
+ using var client = factory.CreateClient();
+
+ return await client.SendAsync(request);
+ }
+
+ private Task UndoAsync(Guid merge) =>
+ WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default);
+ return 0;
+ });
+
+ [Fact]
+ public async Task A_stripe_checkout_opened_by_an_account_that_folded_into_a_suspended_survivor_is_refused_as_not_configured_and_records_nothing()
+ {
+ var s = await SeedAsync();
+ await CommitMergeAsync(s);
+ await WithDb(async db =>
+ {
+ (await db.Memberships.SingleAsync(x => x.UserAccountId == s.Survivor)).Status = MembershipStatus.Suspended;
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ using var response = await StripeCheckoutAsync(s);
+
+ Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
+ Assert.Empty(await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task The_admin_ledgers_manual_patron_record_for_a_folded_account_lands_on_the_survivor_and_is_journalled()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+
+ await WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().RecordSupportEventAsync(
+ s.Survivor, s.Folded, PatronSupportEventKind.OneTimeDonation, 10m, "USD", "manual-1", ExternalPatronProvider.Manual,
+ string.Empty, string.Empty, string.Empty, DateTimeOffset.UtcNow, false, string.Empty, default); // as Pages/App/Ledger records it
+ return 0;
+ });
+
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ var entry = Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal(s.Folded, entry.PriorUserAccountId);
+ }
+
+ [Fact]
+ public async Task A_provider_retry_of_an_event_stranded_on_the_folded_account_journals_nothing_because_nothing_moved()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+ var eventId = $"WH-{Guid.NewGuid():N}";
+ await WithDb(async db => // recorded on the folded account by a delivery that straddled the commit
+ {
+ db.PatronSupportEvents.Add(new PatronSupportEvent
+ {
+ UserAccountId = s.Folded, Provider = ExternalPatronProvider.PayPal, ProviderEventId = eventId, ExternalSupportId = "CAPTURE-1",
+ Kind = PatronSupportEventKind.OneTimeDonation, Amount = 25m, SupportedAtUtc = DateTimeOffset.UtcNow, RecordedAtUtc = DateTimeOffset.UtcNow
+ });
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId));
+
+ Assert.DoesNotContain(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal([s.Folded], await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task A_folded_bootstrap_admins_sign_in_does_not_reactivate_the_merged_membership_and_an_approval_is_refused()
+ {
+ var s = await SeedAsync();
+ await CommitMergeAsync(s);
+ using var folded = ClientFor(s.FoldedGitHubId, "test-admin"); // the bootstrap login: every request would re-promote it
+
+ using (await folded.GetAsync("/"))
+ {
+ }
+
+ Assert.Equal((MembershipStatus.Merged, false), await WithDb(async db =>
+ {
+ var membership = await db.Memberships.SingleAsync(x => x.UserAccountId == s.Folded);
+ return (membership.Status, membership.IsPlatformAdmin);
+ }));
+
+ using var admin = ClientFor(Random.Shared.NextInt64(1_000_000_000, 2_000_000_000), "test-admin");
+ var token = await TokenAsync(admin);
+ using var approve = await admin.PostAsync("/App/Members?handler=Approve", new FormUrlEncodedContent(new Dictionary
+ {
+ ["userAccountId"] = s.Folded.ToString(), ["__RequestVerificationToken"] = token
+ }));
+ Assert.Equal(HttpStatusCode.Redirect, approve.StatusCode);
+ Assert.Equal(MembershipStatus.Merged, await WithDb(async db => (await db.Memberships.SingleAsync(x => x.UserAccountId == s.Folded)).Status));
+ }
+
+ /// Forbid answers 403 or sends the browser to the access-denied page; either way the page and its Heimdall flows are not served.
+ private static void AssertRefused(HttpResponseMessage response)
+ {
+ Assert.True(response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.Found, response.StatusCode.ToString());
+ Assert.DoesNotContain("heimdall", response.Headers.Location?.ToString() ?? "", StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Theory]
+ [InlineData(AccountMergeState.Confirmed)]
+ [InlineData(AccountMergeState.Committed)]
+ public async Task A_frozen_or_folded_cookie_cannot_reach_the_linked_accounts_page_or_start_one_of_its_flows(AccountMergeState state)
+ {
+ var s = await SeedAsync();
+ using var folded = ClientFor(s.FoldedGitHubId, $"fold-{s.SurvivorGitHubId}");
+ var token = await TokenAsync(folded);
+ using (var control = await folded.GetAsync("/Membership/LinkedAccounts"))
+ {
+ Assert.Equal(HttpStatusCode.OK, control.StatusCode); // before the merge the page is theirs
+ }
+
+ await MergeAsync(s, state);
+
+ using var page = await folded.GetAsync("/Membership/LinkedAccounts");
+ AssertRefused(page);
+ using var refresh = await folded.PostAsync("/Membership/LinkedAccounts?handler=Refresh", new FormUrlEncodedContent(new Dictionary
+ {
+ ["via"] = "google", ["__RequestVerificationToken"] = token
+ }));
+ AssertRefused(refresh);
+
+ using var survivor = ClientFor(s.SurvivorGitHubId, $"surv-{s.SurvivorGitHubId}");
+ using var other = await survivor.GetAsync("/Membership/LinkedAccounts");
+ Assert.Equal(HttpStatusCode.OK, other.StatusCode);
+ }
+}
+
+/// The desk's bearer door judges standing the way the cookie gate and the chat refusal do.
+public sealed class AccountMergeDeskTests
+{
+ [Theory]
+ [InlineData(AccountMergeState.Confirmed)]
+ [InlineData(AccountMergeState.Committed)]
+ public async Task A_frozen_or_folded_subjects_live_desk_token_is_forbidden(AccountMergeState state)
+ {
+ using var factory = new DeskWebApplicationFactory();
+ DeskReplay.HoldVectorForks(factory.Door);
+ await factory.EnsureAccountAsync(DeskWebApplicationFactory.Alice, true);
+ var token = factory.Token(DeskWebApplicationFactory.Alice, "bifrost-desk", "desk.read");
+ Task ListAsync() => factory.SendAsync("GET", DeskReplay.Target("list", "gamecult-chat", null), null, token);
+
+ Assert.Equal(200, (await ListAsync()).Status); // the live member, before the merge
+
+ using (var scope = factory.Services.CreateScope())
+ {
+ var db = scope.ServiceProvider.GetRequiredService();
+ var survivor = new UserAccount { BifrostIdentity = "desk-survivor", NormalizedBifrostIdentity = "desk-survivor", GitHubLogin = "desk-survivor", NormalizedGitHubLogin = "desk-survivor" };
+ db.UserAccounts.Add(survivor);
+ db.AccountMerges.Add(new AccountMerge
+ {
+ SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = Guid.Parse(DeskWebApplicationFactory.Alice), State = state, CreatedUtc = DateTimeOffset.UtcNow
+ });
+ await db.SaveChangesAsync();
+ }
+
+ Assert.Equal(403, (await ListAsync()).Status);
+ }
+}
diff --git a/tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs b/tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs
new file mode 100644
index 0000000..3185be5
--- /dev/null
+++ b/tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs
@@ -0,0 +1,1121 @@
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.ConceptVotes;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Motions;
+using Bifrost.Web.Features.Patronage;
+using Bifrost.Web.Features.Shared;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Diagnostics;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Tests;
+
+///
+/// The merge ledger from its consumers' side: the motion state and close a member sees, the concept tallies a visitor sees, the actor
+/// a sign-in resolves to, the patron weight, and the undo. Each operation opens its own context, as a request scope would.
+///
+public sealed class AccountMergeLedgerTests
+{
+ public static readonly DateTimeOffset T0 = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero);
+
+ public sealed class Clock(DateTimeOffset start) : TimeProvider
+ {
+ public DateTimeOffset Now { get; set; } = start;
+
+ public override DateTimeOffset GetUtcNow() => Now;
+ }
+
+ /// The merge fixtures. In memory by default; points the same fixtures at a real database, where unique indexes, transactions, tokens and triggers exist.
+ public sealed class World
+ {
+ private readonly string _name = $"merge-{Guid.NewGuid():N}";
+ private readonly SaveChangesInterceptor[] _interceptors;
+ private readonly string? _postgres;
+
+ public World(params SaveChangesInterceptor[] interceptors) => _interceptors = interceptors;
+
+ private World(string postgres, SaveChangesInterceptor[] interceptors) : this(interceptors) => _postgres = postgres;
+
+ public static World OnPostgres(string connectionString, params SaveChangesInterceptor[] interceptors) => new(connectionString, interceptors);
+
+ public Clock Clock { get; } = new(T0);
+
+ public BifrostDbContext Db()
+ {
+ var options = new DbContextOptionsBuilder().AddInterceptors(_interceptors);
+ if (_postgres is null)
+ {
+ options.UseInMemoryDatabase(_name).ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning));
+ }
+ else
+ {
+ options.UseNpgsql(_postgres);
+ }
+
+ return new BifrostDbContext(options.Options);
+ }
+
+ public AccountMergeLedger Ledger(BifrostDbContext db) => new(db, new PatronageService(db, new AuditTrailService(db, Clock), Clock), Clock);
+
+ public MotionGovernanceService Motions(BifrostDbContext db) => new(db, new AuditTrailService(db, Clock), Clock);
+
+ public ConceptAppraisalService Concepts(BifrostDbContext db) =>
+ new(db, new AuditTrailService(db, Clock), Clock, Options.Create(new ConceptVoteOptions()));
+
+ public async Task AccountAsync(string name, MembershipStatus status = MembershipStatus.Active, bool heimdall = true, bool moderator = false, params MemberRole[] roles)
+ {
+ await using var db = Db();
+ var account = new UserAccount
+ {
+ DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = BifrostIdentityService.NormalizeIdentity(name),
+ HeimdallAccountId = heimdall ? $"hd-{name}-{Guid.NewGuid():N}" : string.Empty,
+ CreatedAtUtc = T0, LastSeenAtUtc = T0
+ };
+ account.Membership = new Membership { UserAccountId = account.Id, Status = status, CanModerateMotions = moderator };
+ foreach (var role in roles)
+ {
+ account.Membership.RoleAssignments.Add(new RoleAssignment { Role = role });
+ }
+
+ db.UserAccounts.Add(account);
+ await db.SaveChangesAsync();
+ return account;
+ }
+
+ public async Task MotionAsync(string title = "m", MotionStatus status = MotionStatus.Open, MotionKind kind = MotionKind.Standard)
+ {
+ await using var db = Db();
+ var author = await AccountAsync("author-" + Guid.NewGuid().ToString("N")[..6]);
+ var motion = new Motion
+ {
+ CreatedByUserAccountId = author.Id, Title = title, Status = status, Kind = kind, OpensAtUtc = T0,
+ ClosesAtUtc = T0.AddDays(3), CreatedAtUtc = T0, ApprovalThreshold = 0.5m
+ };
+ db.Motions.Add(motion);
+ await db.SaveChangesAsync();
+ return motion;
+ }
+
+ public async Task VoteAsync(Motion motion, UserAccount who, VoteChoice choice, decimal weight = 1m, DateTimeOffset? at = null)
+ {
+ await using var db = Db();
+ db.Votes.Add(new Vote { MotionId = motion.Id, UserAccountId = who.Id, Choice = choice, Weight = weight, CastAtUtc = at ?? T0.AddHours(1) });
+ await db.SaveChangesAsync();
+ }
+
+ public async Task MergeAsync(UserAccount survivor, UserAccount folded, AccountMergeState state = AccountMergeState.HeimdallMoved)
+ {
+ await using var db = Db();
+ var merge = new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = state, CreatedUtc = T0 };
+ db.AccountMerges.Add(merge);
+ await db.SaveChangesAsync();
+ return merge;
+ }
+
+ public async Task CommitAsync(AccountMerge merge)
+ {
+ await using var db = Db();
+ return await Ledger(db).CommitAsync(merge.Id, default);
+ }
+
+ public async Task SetStateAsync(AccountMerge merge, AccountMergeState state)
+ {
+ await using var db = Db();
+ (await db.AccountMerges.SingleAsync(x => x.Id == merge.Id)).State = state;
+ await db.SaveChangesAsync();
+ }
+
+ public async Task StateOfAsync(Motion motion, UserAccount viewer)
+ {
+ await using var db = Db();
+ var actorAccount = await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments)
+ .SingleAsync(x => x.Id == viewer.Id);
+ var state = await Motions(db).GetStateAsync(new CurrentBifrostActor(true, actorAccount), default);
+ return state.Motions.Single(x => x.Id == motion.Id);
+ }
+
+ public async Task ActorAsync(Guid accountId)
+ {
+ await using var db = Db();
+ var account = await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments)
+ .SingleAsync(x => x.Id == accountId);
+ return new CurrentBifrostActor(true, account);
+ }
+
+ public async Task CloseAsync(Motion motion, UserAccount moderator)
+ {
+ await using var db = Db();
+ await Motions(db).CloseMotionAsync(await ActorAsync(moderator.Id), motion.Id, default);
+ await using var check = Db();
+ return (await check.Motions.SingleAsync(x => x.Id == motion.Id)).Status;
+ }
+
+ public async Task> AllVotesAsync(Motion motion)
+ {
+ await using var db = Db();
+ return await db.Votes.IgnoreQueryFilters().AsNoTracking().Where(x => x.MotionId == motion.Id).ToListAsync();
+ }
+
+ public async Task> JournalAsync(AccountMerge merge)
+ {
+ await using var db = Db();
+ return await db.AccountMergeEntries.AsNoTracking().Where(x => x.MergeId == merge.Id).OrderBy(x => x.Seq).ToListAsync();
+ }
+
+ public async Task MembershipOfAsync(UserAccount account)
+ {
+ await using var db = Db();
+ return await db.Memberships.AsNoTracking().Include(x => x.TierSnapshots).Include(x => x.RoleAssignments).SingleAsync(x => x.UserAccountId == account.Id);
+ }
+ }
+
+ // ---- votes ----
+
+ [Fact]
+ public async Task Both_voted_on_an_open_motion_only_the_survivors_weight_counts_in_state_and_close()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, survivor, VoteChoice.Against, 1m);
+ await world.VoteAsync(motion, folded, VoteChoice.For, 3m);
+ var before = await world.StateOfAsync(motion, moderator);
+ Assert.Equal((3m, 1m), (before.VotesFor, before.VotesAgainst));
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ var after = await world.StateOfAsync(motion, moderator);
+ Assert.Equal((0m, 1m), (after.VotesFor, after.VotesAgainst));
+ Assert.Equal(MotionStatus.Failed, await world.CloseAsync(motion, moderator));
+ Assert.Equal(2, (await world.AllVotesAsync(motion)).Count); // nothing is deleted
+ }
+
+ [Fact]
+ public async Task A_vote_only_the_folded_account_cast_moves_and_a_later_survivor_cast_replaces_it_never_doubling()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For, 1m);
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ Assert.Equal(1m, (await world.StateOfAsync(motion, moderator)).VotesFor);
+ await using (var db = world.Db())
+ {
+ await world.Motions(db).CastVoteAsync(await world.ActorAsync(survivor.Id), motion.Id, VoteChoice.Against, "changed my mind", default);
+ }
+
+ var item = await world.StateOfAsync(motion, moderator);
+ Assert.Equal((0m, 1m), (item.VotesFor, item.VotesAgainst));
+ var row = Assert.Single(await world.AllVotesAsync(motion));
+ Assert.Equal(survivor.Id, row.UserAccountId);
+ Assert.Null(row.VoidedByMergeId);
+ }
+
+ [Fact]
+ public async Task A_vote_only_the_folded_account_cast_is_voided_when_the_survivor_is_not_active()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor", MembershipStatus.PendingApproval);
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For, 1m);
+
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ Assert.Equal(0m, (await world.StateOfAsync(motion, moderator)).VotesFor);
+ var row = Assert.Single(await world.AllVotesAsync(motion));
+ Assert.Equal(merge.Id, row.VoidedByMergeId);
+ Assert.Equal(folded.Id, row.UserAccountId);
+ }
+
+ [Fact]
+ public async Task Closed_motions_keep_every_vote_and_tally()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync(status: MotionStatus.Passed);
+ await world.VoteAsync(motion, survivor, VoteChoice.For, 1m);
+ await world.VoteAsync(motion, folded, VoteChoice.For, 2m);
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ Assert.Equal(3m, (await world.StateOfAsync(motion, moderator)).VotesFor);
+ Assert.All(await world.AllVotesAsync(motion), v => Assert.Null(v.VoidedByMergeId));
+ }
+
+ // ---- concept appraisals ----
+
+ [Fact]
+ public async Task Appraisals_reduce_to_one_voice_per_person_and_the_tallies_count_the_person_once()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ Guid both, onlyFolded;
+ await using (var db = world.Db())
+ {
+ var s1 = new ConceptSubject { Collection = "c", Key = "both", Title = "Both", RegisteredAtUtc = T0 };
+ var s2 = new ConceptSubject { Collection = "c", Key = "only-folded", Title = "Only folded", RegisteredAtUtc = T0 };
+ db.ConceptSubjects.AddRange(s1, s2);
+ ConceptAppraisal Row(ConceptSubject s, UserAccount who, ConceptStance stance) => new()
+ {
+ SubjectId = s.Id, UserAccountId = who.Id, VoterKey = "account:" + who.Id.ToString("N"), Stance = stance,
+ VoterClass = VoterClass.Member, CastAtUtc = T0
+ };
+ db.ConceptAppraisals.AddRange(Row(s1, survivor, ConceptStance.Up), Row(s1, folded, ConceptStance.Down), Row(s2, folded, ConceptStance.Down));
+ await db.SaveChangesAsync();
+ (both, onlyFolded) = (s1.Id, s2.Id);
+ }
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ await using var read = world.Db();
+ var tallies = await world.Concepts(read).GetTalliesAsync("c", default);
+ Assert.Equal((1, 0), (tallies["both"].Up, tallies["both"].Down));
+ Assert.Equal((0, 1), (tallies["only-folded"].Up, tallies["only-folded"].Down));
+ var moved = await read.ConceptAppraisals.SingleAsync(x => x.SubjectId == onlyFolded);
+ Assert.Equal(survivor.Id, moved.UserAccountId);
+ Assert.Equal("account:" + survivor.Id.ToString("N"), moved.VoterKey);
+ Assert.Equal(1, await read.ConceptAppraisals.IgnoreQueryFilters().CountAsync(x => x.SubjectId == both && x.VoidedByMergeId != null));
+ }
+
+ // ---- membership, standing, patronage ----
+
+ [Fact]
+ public async Task The_folded_membership_becomes_Merged_with_weight_zero_and_no_role_or_admin_flag_is_carried()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor", roles: MemberRole.StandardMember);
+ var folded = await world.AccountAsync("folded", roles: [MemberRole.PlatformAdmin, MemberRole.Producer]);
+ await using (var db = world.Db())
+ {
+ (await db.Memberships.SingleAsync(x => x.UserAccountId == folded.Id)).IsPlatformAdmin = true;
+ await db.SaveChangesAsync();
+ }
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ var foldedMembership = await world.MembershipOfAsync(folded);
+ Assert.Equal(MembershipStatus.Merged, foldedMembership.Status);
+ Assert.Equal(0m, foldedMembership.EffectiveVotingWeight);
+ var survivorMembership = await world.MembershipOfAsync(survivor);
+ Assert.Equal([MemberRole.StandardMember], survivorMembership.RoleAssignments.Select(x => x.Role));
+ Assert.False(survivorMembership.IsPlatformAdmin);
+ Assert.Equal(MembershipStatus.Active, survivorMembership.Status);
+ }
+
+ [Fact]
+ public async Task A_suspended_folded_account_suspends_the_survivor_and_undo_restores_it_only_if_unchanged()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded", MembershipStatus.Suspended);
+ var untouched = await world.MergeAsync(survivor, folded);
+ await world.CommitAsync(untouched);
+
+ var suspended = await world.MembershipOfAsync(survivor);
+ Assert.Equal(MembershipStatus.Suspended, suspended.Status);
+ Assert.Equal(AccountMergeLedger.SuspensionReason(untouched.Id), suspended.SuspensionReason);
+
+ await world.SetStateAsync(untouched, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ await world.Ledger(db).UndoLocalAsync(untouched.Id, default);
+ }
+
+ Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(survivor)).Status);
+ Assert.Equal(MembershipStatus.Suspended, (await world.MembershipOfAsync(folded)).Status);
+
+ // The same again, but a steward re-suspends the survivor for their own reason before the undo: that standing is theirs now.
+ var folded2 = await world.AccountAsync("folded2", MembershipStatus.Suspended);
+ var second = await world.MergeAsync(survivor, folded2);
+ await world.CommitAsync(second);
+ await using (var db = world.Db())
+ {
+ (await db.Memberships.SingleAsync(x => x.UserAccountId == survivor.Id)).SuspensionReason = "steward decision";
+ await db.SaveChangesAsync();
+ }
+
+ await world.SetStateAsync(second, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ await world.Ledger(db).UndoLocalAsync(second.Id, default);
+ }
+
+ Assert.Equal(MembershipStatus.Suspended, (await world.MembershipOfAsync(survivor)).Status);
+ Assert.Contains(await world.JournalAsync(second), e => e.Kind == AccountMergeEntryKind.Standing && e.Action == AccountMergeEntryAction.KeptAfterUndo);
+ }
+
+ [Fact]
+ public async Task Patron_events_follow_the_person_and_the_survivors_tier_derives_once_from_all_events_not_tier_plus_tier()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ await using (var db = world.Db())
+ {
+ PatronSupportEvent Event(UserAccount who, decimal amount) => new()
+ {
+ UserAccountId = who.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = amount,
+ ProviderEventId = Guid.NewGuid().ToString("N"), SupportedAtUtc = T0, RecordedAtUtc = T0
+ };
+ db.PatronSupportEvents.AddRange(Event(survivor, 90m), Event(folded, 1000m));
+ var memberships = await db.Memberships.ToListAsync();
+ foreach (var (who, weight) in new[] { (survivor, 1m), (folded, 3m) })
+ {
+ db.TierSnapshots.Add(new TierSnapshot { MembershipId = memberships.Single(m => m.UserAccountId == who.Id).Id, Kind = TierSnapshotKind.Patron, Label = "t", Weight = weight, IsCurrent = true, EffectiveFromUtc = T0, CapturedAtUtc = T0 });
+ }
+
+ await db.SaveChangesAsync();
+ }
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ var survivorMembership = await world.MembershipOfAsync(survivor);
+ Assert.Equal(3m, survivorMembership.EffectiveVotingWeight); // 1090 points: Gold, not Bronze 1 + Gold 3
+ Assert.Single(survivorMembership.TierSnapshots, x => x.Kind == TierSnapshotKind.Patron && x.IsCurrent);
+ Assert.DoesNotContain(( await world.MembershipOfAsync(folded)).TierSnapshots, x => x.IsCurrent);
+ await using var db2 = world.Db();
+ Assert.All(await db2.PatronSupportEvents.ToListAsync(), e => Assert.Equal(survivor.Id, e.UserAccountId));
+ }
+
+ // ---- who the actor is ----
+
+ [Fact]
+ public async Task A_principal_whose_identity_names_one_row_and_whose_heimdall_id_names_another_resolves_the_first_and_does_not_throw()
+ {
+ var world = new World();
+ var byIdentity = await world.AccountAsync("by-identity");
+ var byHeimdall = await world.AccountAsync("by-heimdall");
+ var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
+ http.User = new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity(
+ [
+ new System.Security.Claims.Claim(BifrostClaimTypes.BifrostIdentity, byIdentity.BifrostIdentity),
+ new System.Security.Claims.Claim(BifrostClaimTypes.HeimdallAccountId, byHeimdall.HeimdallAccountId)
+ ], "test"));
+ await using var db = world.Db();
+ var accessor = new CurrentBifrostActorAccessor(new Microsoft.AspNetCore.Http.HttpContextAccessor { HttpContext = http }, db, world.Ledger(db));
+
+ var actor = await accessor.GetAsync(default);
+
+ Assert.Equal(byIdentity.Id, actor.UserAccount!.Id);
+ }
+
+ [Theory]
+ [InlineData(AccountMergeState.Confirmed, true)]
+ [InlineData(AccountMergeState.HeimdallMoved, true)]
+ [InlineData(AccountMergeState.Committed, false)]
+ [InlineData(AccountMergeState.Final, false)]
+ [InlineData(AccountMergeState.UndoRequested, false)]
+ [InlineData(AccountMergeState.HeimdallReversed, false)]
+ public async Task A_folded_account_is_frozen_then_folded_and_acts_as_nobody_while_the_survivor_acts_normally(AccountMergeState state, bool frozen)
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded", roles: MemberRole.PlatformAdmin);
+ var merge = await world.MergeAsync(survivor, folded, state);
+
+ foreach (var (account, isFolded) in new[] { (folded, true), (survivor, false) })
+ {
+ var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
+ http.User = new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity(
+ [new System.Security.Claims.Claim(BifrostClaimTypes.HeimdallAccountId, account.HeimdallAccountId)], "test"));
+ await using var db = world.Db();
+ var actor = await new CurrentBifrostActorAccessor(new Microsoft.AspNetCore.Http.HttpContextAccessor { HttpContext = http }, db, world.Ledger(db)).GetAsync(default);
+
+ if (!isFolded)
+ {
+ Assert.Equal(survivor.Id, actor.UserAccount!.Id);
+ Assert.Null(actor.Merge);
+ continue;
+ }
+
+ Assert.True(actor.IsAuthenticated);
+ Assert.Null(actor.UserAccount);
+ Assert.False(actor.IsPlatformAdmin);
+ Assert.False(actor.IsActiveMember);
+ Assert.Equal(merge.Id, actor.Merge!.MergeId);
+ Assert.Equal(frozen, actor.Merge is MergeStanding.Frozen);
+ Assert.Equal(!frozen, actor.Merge is MergeStanding.Folded f && f.SurvivorId == survivor.Id);
+ }
+ }
+
+ [Theory]
+ [InlineData(AccountMergeState.Proposed)]
+ [InlineData(AccountMergeState.Failed)]
+ [InlineData(AccountMergeState.Undone)]
+ public async Task A_merge_that_never_reached_or_has_left_the_move_leaves_the_folded_account_standing_alone(AccountMergeState state)
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ await world.MergeAsync(survivor, folded, state);
+
+ await using var db = world.Db();
+ Assert.Null(await world.Ledger(db).StandingAsync(folded.Id, default));
+ }
+
+ // ---- plan ----
+
+ [Fact]
+ public async Task Plan_writes_nothing_and_says_what_a_commit_would_do()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For);
+
+ await using (var db = world.Db())
+ {
+ var plan = await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default);
+ Assert.Empty(plan.Blocks);
+ Assert.Contains(plan.Entries, e => e.Kind == AccountMergeEntryKind.Vote && e.Action == AccountMergeEntryAction.Moved);
+ Assert.Contains(plan.Entries, e => e.Kind == AccountMergeEntryKind.Membership && e.Action == AccountMergeEntryAction.Closed);
+ }
+
+ await using var check = world.Db();
+ Assert.Empty(check.AccountMerges);
+ Assert.Empty(check.AccountMergeEntries);
+ Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(folded)).Status);
+ Assert.Equal(folded.Id, Assert.Single(await world.AllVotesAsync(motion)).UserAccountId);
+ }
+
+ public static IEnumerable