""");
- }
-
- 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
deleted file mode 100644
index d95e7f3..0000000
--- a/src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-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
deleted file mode 100644
index a823426..0000000
--- a/src/Bifrost.Web/Features/Registration/TrainingNotice.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-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($"
- Chat is by invitation: mint a single-use link and send it yourself. Approval remains human
+ Invite-first onboarding keeps the alpha intentionally small. 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.
-
- 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
deleted file mode 100644
index e70d4e1..0000000
--- a/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml.cs
+++ /dev/null
@@ -1,295 +0,0 @@
-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.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,
- IOptions hostOptions,
- ILogger logger) : PageModel
-{
- private static readonly Dictionary ProviderNames = new(StringComparer.Ordinal)
- {
- ["discord"] = "Discord",
- ["patreon"] = "Patreon",
- ["google"] = "Google"
- };
-
- private string? AccountId => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 } id ? id : null;
-
- /// 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/Status.cshtml b/src/Bifrost.Web/Pages/Membership/Status.cshtml
index 78612c6..2c1ab8f 100644
--- a/src/Bifrost.Web/Pages/Membership/Status.cshtml
+++ b/src/Bifrost.Web/Pages/Membership/Status.cshtml
@@ -24,11 +24,11 @@
@Model.StatusMessage
- @if (Model.CanManageLogins)
+ @if (Model.Invitation is not null)
{
-
- Linked accounts
- See, add and remove the provider logins that sign in to this account.
+
+ Invitation tracked for @Model.Invitation.GitHubLogin.
+ Issued @Model.Invitation.IssuedAtUtc.ToString("dd MMM yyyy") UTC.
}
diff --git a/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs b/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
index 34bda99..d579dd3 100644
--- a/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
+++ b/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
@@ -1,20 +1,21 @@
+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;
+using Microsoft.EntityFrameworkCore;
namespace Bifrost.Web.Pages.Membership;
[Authorize]
-public sealed class StatusModel(ICurrentBifrostActorAccessor actorAccessor) : PageModel
+public sealed class StatusModel(
+ ICurrentBifrostActorAccessor actorAccessor,
+ BifrostDbContext dbContext) : PageModel
{
- /// 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 CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
+ public MembershipInvitation? Invitation { get; private set; }
+
public string StatusLabel => Actor.Membership?.Status switch
{
MembershipStatus.Active => "Active member",
@@ -35,14 +36,26 @@ public sealed class StatusModel(ICurrentBifrostActorAccessor actorAccessor) : Pa
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 => "An admin still needs to approve active participation.",
+ MembershipStatus.PendingApproval => "Your GitHub sign-in matched an invite, but 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 approval on your account yet.",
+ MembershipStatus.Authenticated => "You are signed in, but there is no active invite or 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);
}
}
diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml b/src/Bifrost.Web/Pages/Mill/Vote.cshtml
index d9e67f2..fe75338 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 41ed934..dd87f6d 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 (RequestOriginGuard); no antiforgery cookie or token exists on this flow.
+ // origin (CastRequestGuard); 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) && !RequestOriginGuard.Allows(context.HttpContext.Request, host.Value))
+ if (HttpMethods.IsPost(method) && !CastRequestGuard.Allows(context.HttpContext.Request, host.Value))
{
context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
return;
diff --git a/src/Bifrost.Web/Pages/Shared/_Layout.cshtml b/src/Bifrost.Web/Pages/Shared/_Layout.cshtml
index 6c757c9..34c68cb 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/Pages/Shared/_ValidationScriptsPartial.cshtml b/src/Bifrost.Web/Pages/Shared/_ValidationScriptsPartial.cshtml
new file mode 100644
index 0000000..5d1f685
--- /dev/null
+++ b/src/Bifrost.Web/Pages/Shared/_ValidationScriptsPartial.cshtml
@@ -0,0 +1,2 @@
+
+
diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs
index c579b53..d0656d3 100644
--- a/src/Bifrost.Web/Program.cs
+++ b/src/Bifrost.Web/Program.cs
@@ -5,15 +5,14 @@ using System.Text.Json.Serialization;
using Bifrost.Web.Configuration;
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;
@@ -63,32 +62,23 @@ builder.Services
builder.Services
.AddOptions()
- .BindConfiguration(HeimdallOptions.SectionName)
- .PostConfigure>(HeimdallOptions.ResolveAppSecret);
+ .BindConfiguration(HeimdallOptions.SectionName);
builder.Services
.AddOptions()
.BindConfiguration(StripeOptions.SectionName);
builder.Services
- .AddOptions()
- .BindConfiguration(ConceptVoteOptions.SectionName);
+ .AddOptions()
+ .BindConfiguration(BridgeOptions.SectionName);
builder.Services
- .AddOptions()
- .BindConfiguration(DeskOptions.SectionName);
-
-builder.Services.AddAntiforgery(options =>
-{
- options.Cookie.Name = BifrostCookies.Antiforgery;
- options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
- options.Cookie.Path = BifrostCookies.Path;
-});
+ .AddOptions()
+ .BindConfiguration(ConceptVoteOptions.SectionName);
builder.Services.AddRazorPages(options =>
{
options.Conventions.AuthorizePage("/Membership/Status");
- options.Conventions.AuthorizePage("/Membership/LinkedAccounts");
options.Conventions.AuthorizeFolder("/App", ActiveMemberRequirement.PolicyName);
options.Conventions.AllowAnonymousToFolder("/Mill");
});
@@ -115,22 +105,16 @@ 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();
+builder.Services.AddScoped();
+builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
-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.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
@@ -142,13 +126,9 @@ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddSingleton();
builder.Services.AddScoped();
-// The app-secret and member-bearer clients: no redirects (see HeimdallClientServices).
-builder.Services.AddHeimdallClients();
-builder.Services.AddSingleton();
-builder.Services.AddSingleton();
-builder.Services.AddSingleton();
-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));
builder.Services.AddSingleton();
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService>().Value));
@@ -187,10 +167,6 @@ var authenticationBuilder = builder.Services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
- options.Cookie.Name = BifrostCookies.Session;
- options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
- options.Cookie.Path = BifrostCookies.Path;
- options.Cookie.Domain = null;
options.LoginPath = "/auth/sign-in";
options.AccessDeniedPath = "/Membership/Status";
options.SlidingExpiration = true;
@@ -207,9 +183,6 @@ if (configuredGitHubOAuthOptions.IsConfigured)
options.TokenEndpoint = "https://github.com/login/oauth/access_token";
options.UserInformationEndpoint = "https://api.github.com/user";
options.SaveTokens = true;
- options.CorrelationCookie.Name = BifrostCookies.OAuthCorrelation;
- options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
- options.CorrelationCookie.Path = BifrostCookies.Path;
options.Scope.Add("read:user");
options.Scope.Add("user:email");
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
@@ -260,19 +233,10 @@ 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
@@ -290,11 +254,6 @@ 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();
@@ -315,18 +274,12 @@ 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,
@@ -358,76 +311,6 @@ 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
-
` all receive top and bottom margins. We nuke the top\n// margin for easier control within type scales as it avoids margin collapsing.\n\n%heading {\n margin-top: 0; // 1\n margin-bottom: $headings-margin-bottom;\n font-family: $headings-font-family;\n font-style: $headings-font-style;\n font-weight: $headings-font-weight;\n line-height: $headings-line-height;\n color: var(--#{$prefix}heading-color);\n}\n\nh1 {\n @extend %heading;\n @include font-size($h1-font-size);\n}\n\nh2 {\n @extend %heading;\n @include font-size($h2-font-size);\n}\n\nh3 {\n @extend %heading;\n @include font-size($h3-font-size);\n}\n\nh4 {\n @extend %heading;\n @include font-size($h4-font-size);\n}\n\nh5 {\n @extend %heading;\n @include font-size($h5-font-size);\n}\n\nh6 {\n @extend %heading;\n @include font-size($h6-font-size);\n}\n\n\n// Reset margins on paragraphs\n//\n// Similarly, the top margin on `
`s get reset. However, we also reset the\n// bottom margin to use `rem` units instead of `em`.\n\np {\n margin-top: 0;\n margin-bottom: $paragraph-margin-bottom;\n}\n\n\n// Abbreviations\n//\n// 1. Add the correct text decoration in Chrome, Edge, Opera, and Safari.\n// 2. Add explicit cursor to indicate changed behavior.\n// 3. Prevent the text-decoration to be skipped.\n\nabbr[title] {\n text-decoration: underline dotted; // 1\n cursor: help; // 2\n text-decoration-skip-ink: none; // 3\n}\n\n\n// Address\n\naddress {\n margin-bottom: 1rem;\n font-style: normal;\n line-height: inherit;\n}\n\n\n// Lists\n\nol,\nul {\n padding-left: 2rem;\n}\n\nol,\nul,\ndl {\n margin-top: 0;\n margin-bottom: 1rem;\n}\n\nol ol,\nul ul,\nol ul,\nul ol {\n margin-bottom: 0;\n}\n\ndt {\n font-weight: $dt-font-weight;\n}\n\n// 1. Undo browser default\n\ndd {\n margin-bottom: .5rem;\n margin-left: 0; // 1\n}\n\n\n// Blockquote\n\nblockquote {\n margin: 0 0 1rem;\n}\n\n\n// Strong\n//\n// Add the correct font weight in Chrome, Edge, and Safari\n\nb,\nstrong {\n font-weight: $font-weight-bolder;\n}\n\n\n// Small\n//\n// Add the correct font size in all browsers\n\nsmall {\n @include font-size($small-font-size);\n}\n\n\n// Mark\n\nmark {\n padding: $mark-padding;\n color: var(--#{$prefix}highlight-color);\n background-color: var(--#{$prefix}highlight-bg);\n}\n\n\n// Sub and Sup\n//\n// Prevent `sub` and `sup` elements from affecting the line height in\n// all browsers.\n\nsub,\nsup {\n position: relative;\n @include font-size($sub-sup-font-size);\n line-height: 0;\n vertical-align: baseline;\n}\n\nsub { bottom: -.25em; }\nsup { top: -.5em; }\n\n\n// Links\n\na {\n color: rgba(var(--#{$prefix}link-color-rgb), var(--#{$prefix}link-opacity, 1));\n text-decoration: $link-decoration;\n\n &:hover {\n --#{$prefix}link-color-rgb: var(--#{$prefix}link-hover-color-rgb);\n text-decoration: $link-hover-decoration;\n }\n}\n\n// And undo these styles for placeholder links/named anchors (without href).\n// It would be more straightforward to just use a[href] in previous block, but that\n// causes specificity issues in many other styles that are too complex to fix.\n// See https://github.com/twbs/bootstrap/issues/19402\n\na:not([href]):not([class]) {\n &,\n &:hover {\n color: inherit;\n text-decoration: none;\n }\n}\n\n\n// Code\n\npre,\ncode,\nkbd,\nsamp {\n font-family: $font-family-code;\n @include font-size(1em); // Correct the odd `em` font sizing in all browsers.\n}\n\n// 1. Remove browser default top margin\n// 2. Reset browser default of `1em` to use `rem`s\n// 3. Don't allow content to break outside\n\npre {\n display: block;\n margin-top: 0; // 1\n margin-bottom: 1rem; // 2\n overflow: auto; // 3\n @include font-size($code-font-size);\n color: $pre-color;\n\n // Account for some code outputs that place code tags in pre tags\n code {\n @include font-size(inherit);\n color: inherit;\n word-break: normal;\n }\n}\n\ncode {\n @include font-size($code-font-size);\n color: var(--#{$prefix}code-color);\n word-wrap: break-word;\n\n // Streamline the style when inside anchors to avoid broken underline and more\n a > & {\n color: inherit;\n }\n}\n\nkbd {\n padding: $kbd-padding-y $kbd-padding-x;\n @include font-size($kbd-font-size);\n color: $kbd-color;\n background-color: $kbd-bg;\n @include border-radius($border-radius-sm);\n\n kbd {\n padding: 0;\n @include font-size(1em);\n font-weight: $nested-kbd-font-weight;\n }\n}\n\n\n// Figures\n//\n// Apply a consistent margin strategy (matches our type styles).\n\nfigure {\n margin: 0 0 1rem;\n}\n\n\n// Images and content\n\nimg,\nsvg {\n vertical-align: middle;\n}\n\n\n// Tables\n//\n// Prevent double borders\n\ntable {\n caption-side: bottom;\n border-collapse: collapse;\n}\n\ncaption {\n padding-top: $table-cell-padding-y;\n padding-bottom: $table-cell-padding-y;\n color: $table-caption-color;\n text-align: left;\n}\n\n// 1. Removes font-weight bold by inheriting\n// 2. Matches default `
` alignment by inheriting `text-align`.\n// 3. Fix alignment for Safari\n\nth {\n font-weight: $table-th-font-weight; // 1\n text-align: inherit; // 2\n text-align: -webkit-match-parent; // 3\n}\n\nthead,\ntbody,\ntfoot,\ntr,\ntd,\nth {\n border-color: inherit;\n border-style: solid;\n border-width: 0;\n}\n\n\n// Forms\n//\n// 1. Allow labels to use `margin` for spacing.\n\nlabel {\n display: inline-block; // 1\n}\n\n// Remove the default `border-radius` that macOS Chrome adds.\n// See https://github.com/twbs/bootstrap/issues/24093\n\nbutton {\n // stylelint-disable-next-line property-disallowed-list\n border-radius: 0;\n}\n\n// Explicitly remove focus outline in Chromium when it shouldn't be\n// visible (e.g. as result of mouse click or touch tap). It already\n// should be doing this automatically, but seems to currently be\n// confused and applies its very visible two-tone outline anyway.\n\nbutton:focus:not(:focus-visible) {\n outline: 0;\n}\n\n// 1. Remove the margin in Firefox and Safari\n\ninput,\nbutton,\nselect,\noptgroup,\ntextarea {\n margin: 0; // 1\n font-family: inherit;\n @include font-size(inherit);\n line-height: inherit;\n}\n\n// Remove the inheritance of text transform in Firefox\nbutton,\nselect {\n text-transform: none;\n}\n// Set the cursor for non-`