From 9c4ab5646a940edebfe575f8db8ec270111975b6 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 10:26:24 +0000 Subject: [PATCH] Registration: server-rendered sign-up form with script solver and time-lock fallback GET /auth/bifrost/register renders the form (notice in full, unchecked consent box); POST /auth/bifrost/register/form and the JSON endpoint share NativeRegistration. Challenge payload gains issued-at; waited path needs FallbackWaitSeconds and a stricter per-address FallbackPermits budget. Co-Authored-By: Claude Sonnet 5.5 --- .../Configuration/RegistrationOptions.cs | 12 + .../Registration/NativeRegistration.cs | 118 ++++ .../RegistrationChallengeService.cs | 93 ++- .../Features/Registration/RegistrationPage.cs | 156 +++++ .../Registration/RegistrationRateLimit.cs | 19 +- .../Shared/StartupConfigurationValidator.cs | 13 + src/Bifrost.Web/Program.cs | 158 ++++- .../Fixtures/registration-page-harness.cjs | 56 ++ .../RegistrationFormTests.cs | 589 ++++++++++++++++++ 9 files changed, 1146 insertions(+), 68 deletions(-) create mode 100644 src/Bifrost.Web/Features/Registration/NativeRegistration.cs create mode 100644 src/Bifrost.Web/Features/Registration/RegistrationPage.cs create mode 100644 tests/Bifrost.Web.Tests/Fixtures/registration-page-harness.cjs create mode 100644 tests/Bifrost.Web.Tests/RegistrationFormTests.cs diff --git a/src/Bifrost.Web/Configuration/RegistrationOptions.cs b/src/Bifrost.Web/Configuration/RegistrationOptions.cs index 24ed26e..f1b7c5b 100644 --- a/src/Bifrost.Web/Configuration/RegistrationOptions.cs +++ b/src/Bifrost.Web/Configuration/RegistrationOptions.cs @@ -9,6 +9,10 @@ public sealed class RegistrationOptions public const int MaxDifficulty = 30; + public const int MinFallbackWaitSeconds = 5; + + public const int MaxFallbackWaitSeconds = 300; + public RegistrationCaptchaOptions Captcha { get; init; } = new(); public RegistrationLimitsOptions Limits { get; init; } = new(); @@ -22,10 +26,18 @@ public sealed class RegistrationLimitsOptions public TimeSpan Window { get; init; } = TimeSpan.FromMinutes(1); public int MaxTrackedKeys { get; init; } = 10_000; + + /// Time-lock submissions (no script, no proof of work) per address per ; far tighter than because they cost the client nothing. + public int FallbackPermits { get; init; } = 3; + + public TimeSpan FallbackWindow { get; init; } = TimeSpan.FromHours(1); } public sealed class RegistrationCaptchaOptions { /// Leading zero bits the SHA-256 of challenge:nonce must have. 18 is about 262k hashes, a second or two in a browser. public int Difficulty { get; init; } = 18; + + /// Seconds after the challenge was issued before a waited (no proof of work) submission is accepted. + public int FallbackWaitSeconds { get; init; } = 30; } diff --git a/src/Bifrost.Web/Features/Registration/NativeRegistration.cs b/src/Bifrost.Web/Features/Registration/NativeRegistration.cs new file mode 100644 index 0000000..d7c57db --- /dev/null +++ b/src/Bifrost.Web/Features/Registration/NativeRegistration.cs @@ -0,0 +1,118 @@ +using Bifrost.Web.Domain; +using Bifrost.Web.Features.Membership; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; + +namespace Bifrost.Web.Features.Registration; + +/// What a client sent to register. claims the time-lock path instead of a proof of work. +public sealed record RegistrationAttempt( + string? Identity, + string? DisplayName, + string? Challenge, + string? Nonce, + bool Waited, + int? AcceptedNoticeVersion); + +/// Which input a refusal is about, so the form can mark it invalid. +public enum RegistrationField { None, Identity, Consent } + +/// +/// Either a signed-in , or a to return as is (the rate limits), or a rejection +/// with a status and message. is set when the time-lock was not over; the challenge is then still unspent. +/// +public sealed record RegistrationOutcome( + UserAccount? Account, + IResult? Refusal, + int Status, + string? Message, + RegistrationField Field, + TimeSpan? WaitRemaining) +{ + public static RegistrationOutcome Reject(int status, string message, RegistrationField field = RegistrationField.None, TimeSpan? wait = null) => + new(null, null, status, message, field, wait); +} + +/// +/// The one registration gate, run by the JSON endpoint and the form alike. Order: address budget, consent, one proof only, +/// the challenge (proof of work, or the time-lock plus its tighter budget), then the account and receipt in one save, +/// then the cookie. A refusal at any step creates nothing. +/// +public sealed class NativeRegistration( + BifrostIdentityService identities, + RegistrationChallengeService challenges, + RegistrationRateLimit rateLimit) +{ + public async Task RunAsync(HttpContext http, RegistrationAttempt attempt, CancellationToken cancellationToken) + { + if (rateLimit.Refuse(http) is { } refused) + { + return new(null, refused, 0, null, RegistrationField.None, null); + } + + // Consent first, then the proof; a refusal here creates nothing. + if (attempt.AcceptedNoticeVersion != TrainingNotice.Version) + { + return RegistrationOutcome.Reject( + StatusCodes.Status400BadRequest, + $"Registration requires accepting the training notice, current version {TrainingNotice.Version}.", + RegistrationField.Consent); + } + + var hasNonce = !string.IsNullOrEmpty(attempt.Nonce); + if (hasNonce && attempt.Waited) + { + return RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, "Send a nonce or waited, not both."); + } + + var failed = RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, "Registration challenge failed."); + if (hasNonce) + { + if (!challenges.TryConsume(attempt.Challenge, attempt.Nonce)) + { + return failed; + } + } + else if (attempt.Waited) + { + if (challenges.WaitRemaining(attempt.Challenge) is not { } remaining) + { + return failed; + } + + if (remaining > TimeSpan.Zero) + { + var seconds = (int)Math.Ceiling(remaining.TotalSeconds); + return RegistrationOutcome.Reject( + StatusCodes.Status400BadRequest, + $"Too early: {seconds} more second{(seconds == 1 ? "" : "s")} to wait after the page opened. Nothing was spent; submit again then.", + wait: remaining); + } + + if (rateLimit.RefuseFallback(http) is { } fallbackRefused) + { + return new(null, fallbackRefused, 0, null, RegistrationField.None, null); + } + + if (!challenges.TryConsumeWaited(attempt.Challenge)) + { + return failed; + } + } + else + { + return failed; + } + + try + { + var account = await identities.RegisterNativeAsync(attempt.Identity ?? "", attempt.DisplayName, TrainingNotice.Version, cancellationToken); + await http.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identities.BuildPrincipal(account)); + return new(account, null, StatusCodes.Status200OK, null, RegistrationField.None, null); + } + catch (BifrostIdentityException error) + { + return RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, error.Message, RegistrationField.Identity); + } + } +} diff --git a/src/Bifrost.Web/Features/Registration/RegistrationChallengeService.cs b/src/Bifrost.Web/Features/Registration/RegistrationChallengeService.cs index c44c3fb..feb3cb9 100644 --- a/src/Bifrost.Web/Features/Registration/RegistrationChallengeService.cs +++ b/src/Bifrost.Web/Features/Registration/RegistrationChallengeService.cs @@ -50,58 +50,87 @@ public sealed class RegistrationChallengeService( var expiresAt = now + Lifetime; var difficulty = Difficulty; var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)); - var challenge = protector.Protect($"{id}.{expiresAt.ToUnixTimeMilliseconds()}.{difficulty}"); + var challenge = protector.Protect($"{id}.{expiresAt.ToUnixTimeMilliseconds()}.{difficulty}.{now.ToUnixTimeMilliseconds()}"); return new RegistrationChallenge(challenge, difficulty, expiresAt); } + /// Proof-of-work path: the nonce must meet the difficulty the challenge was issued with. Spends the challenge. public bool TryConsume(string? challenge, string? nonce) { - if (string.IsNullOrEmpty(challenge) || !IsNonce(nonce)) - { - return false; - } - - string id; - int difficulty; - DateTimeOffset expiresAt; - try - { - var payload = protector.Unprotect(challenge).Split('.'); - if (payload.Length != 3) - { - return false; - } - - id = payload[0]; - difficulty = int.Parse(payload[2], System.Globalization.CultureInfo.InvariantCulture); - expiresAt = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(payload[1], System.Globalization.CultureInfo.InvariantCulture)); - } - catch (Exception) - { - return false; - } - - var now = clock.GetUtcNow(); - if (now >= expiresAt) + if (!IsNonce(nonce) || Open(challenge) is not { } open) { return false; } var hash = SHA256.HashData(Encoding.UTF8.GetBytes(challenge + ":" + nonce)); - if (LeadingZeroBits(hash) < difficulty) + return LeadingZeroBits(hash) >= open.Difficulty && Spend(open); + } + + /// + /// Time-lock path, step one: how long until a waited submission of this challenge is accepted. Null when the + /// token is not a live challenge of ours; zero when the wait is over. Spends nothing. + /// + public TimeSpan? WaitRemaining(string? challenge) + { + if (Open(challenge) is not { } open) { - return false; + return null; } + var remaining = open.IssuedAt + TimeSpan.FromSeconds(options.Value.Captcha.FallbackWaitSeconds) - clock.GetUtcNow(); + return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero; + } + + /// Time-lock path, step two: spends the challenge if its wait is over. No proof of work is checked. + public bool TryConsumeWaited(string? challenge) => + WaitRemaining(challenge) == TimeSpan.Zero && Open(challenge) is { } open && Spend(open); + + private sealed record OpenChallenge(string Id, int Difficulty, DateTimeOffset ExpiresAt, DateTimeOffset IssuedAt); + + /// The payload of a challenge that we protected and that has not expired; null otherwise. + private OpenChallenge? Open(string? challenge) + { + if (string.IsNullOrEmpty(challenge)) + { + return null; + } + + OpenChallenge open; + try + { + var payload = protector.Unprotect(challenge).Split('.'); + if (payload.Length != 4) + { + return null; + } + + var culture = System.Globalization.CultureInfo.InvariantCulture; + open = new OpenChallenge( + payload[0], + int.Parse(payload[2], culture), + DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(payload[1], culture)), + DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(payload[3], culture))); + } + catch (Exception) + { + return null; + } + + return clock.GetUtcNow() >= open.ExpiresAt ? null : open; + } + + private bool Spend(OpenChallenge open) + { + var now = clock.GetUtcNow(); lock (gate) { Purge(now); - if (consumed.Count >= MaxConsumed || !consumed.Add(id)) + if (consumed.Count >= MaxConsumed || !consumed.Add(open.Id)) { return false; } - expiries.Enqueue(id, expiresAt); + expiries.Enqueue(open.Id, open.ExpiresAt); return true; } } diff --git a/src/Bifrost.Web/Features/Registration/RegistrationPage.cs b/src/Bifrost.Web/Features/Registration/RegistrationPage.cs new file mode 100644 index 0000000..6167ca1 --- /dev/null +++ b/src/Bifrost.Web/Features/Registration/RegistrationPage.cs @@ -0,0 +1,156 @@ +using System.Net; +using System.Text; + +namespace Bifrost.Web.Features.Registration; + +/// What the sign-up page shows. Everything user-supplied is HTML-encoded on the way out. +public sealed record RegistrationPageModel( + string ReturnPath, + string Challenge, + int Difficulty, + int WaitSeconds, + string Identity = "", + string DisplayName = "", + string? Error = null, + RegistrationField ErrorField = RegistrationField.None); + +/// +/// The server-rendered sign-up form. It works with no script (time-lock path); the inline script, when it can, replaces the +/// wait by solving the proof of work. No external asset, no cookie, no third party. +/// +public static class RegistrationPage +{ + // Hash rule is RegistrationChallengeService's: SHA-256 of challenge + ":" + nonce, leading zero bits >= difficulty. + // Hashes run in batches that yield to the UI between them. If the browser has no crypto.subtle, nothing here runs + // and the form submits on the time-lock path. + public const string Script = """ + (function () { + var form = document.getElementById("register"); + var status = document.getElementById("status"); + if (!form || !status || !window.crypto || !window.crypto.subtle || !window.TextEncoder) { return; } + var BATCH = 256; + var busy = false; + var solved = false; + + function zeroBits(bytes) { + var bits = 0; + for (var i = 0; i < bytes.length; i++) { + if (bytes[i] === 0) { bits += 8; continue; } + return bits + Math.clz32(bytes[i]) - 24; + } + return bits; + } + + async function solve(challenge, difficulty) { + var encoder = new TextEncoder(); + for (var start = 0; ; start += BATCH) { + var tries = []; + for (var n = start; n < start + BATCH; n++) { + tries.push(crypto.subtle.digest("SHA-256", encoder.encode(challenge + ":" + n))); + } + var hashes = await Promise.all(tries); + for (var i = 0; i < hashes.length; i++) { + if (zeroBits(new Uint8Array(hashes[i])) >= difficulty) { return String(start + i); } + } + await new Promise(function (resolve) { setTimeout(resolve, 0); }); + } + } + + form.addEventListener("submit", function (event) { + if (solved) { return; } + event.preventDefault(); + if (busy) { return; } + busy = true; + status.textContent = "Checking, a few seconds"; + solve(form.elements.challenge.value, parseInt(form.getAttribute("data-difficulty"), 10)).then(function (nonce) { + form.elements.nonce.value = nonce; + form.elements.waited.disabled = true; + solved = true; + status.textContent = "Creating your account"; + form.submit(); + }, function () { + solved = true; + busy = false; + status.textContent = "The quick check did not run in this browser. Press Create account again after the wait described below."; + }); + }); + })(); + """; + + public static string Render(RegistrationPageModel model) + { + static string E(string? text) => WebUtility.HtmlEncode(text ?? ""); + var notice = TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture); + var summary = new StringBuilder(); + if (model.Error is not null) + { + summary.Append($""""""); + } + + 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}} +
+
+ Your account + + + + +
+
+ Training notice, version {{notice}} +

{{E(TrainingNotice.Text)}}

+ + +
+ + + + +

+ +
+

Without a script, this page cannot run its quick check. Then wait {{wait}} seconds after the page opened and press Create account; pressed sooner, the page comes back saying how many seconds remain, and nothing is lost. Without the quick 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 index 6dc57d6..d95e7f3 100644 --- a/src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs +++ b/src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs @@ -17,18 +17,31 @@ public sealed class RegistrationRateLimit(IOptions options, 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) + 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 (addresses.Spend(ClientAddress.BudgetKey(http.Connection.RemoteIpAddress)) is not { } denial) + if (budget.Spend(ClientAddress.BudgetKey(http.Connection.RemoteIpAddress)) is not { } denial) { return null; } http.Response.Headers.RetryAfter = RetryAfter(denial.RetryAfter); - return Results.Text("Too many registration requests from this address.", statusCode: StatusCodes.Status429TooManyRequests); + return Results.Text(message, statusCode: StatusCodes.Status429TooManyRequests); } catch (Exception exception) when (exception is not OperationCanceledException) { diff --git a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs index 6689ce1..3181450 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; @@ -55,12 +56,24 @@ public sealed class StartupConfigurationValidator( 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); diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index 7fc1854..17dcd56 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -135,6 +135,7 @@ builder.Services.AddSingleton(); // TimeProvider and option builder.Services.AddOptions().BindConfiguration(RegistrationOptions.SectionName); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -389,54 +390,114 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions +{ + 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, - CancellationToken cancellationToken) => + IOptions registrationOptions) => { if (rateLimit.Refuse(httpContext) is { } refused) { return refused; } - // Consent first, then the proof of work; a refusal here creates nothing. - if (request.AcceptedNoticeVersion != TrainingNotice.Version) + 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(); + +// Antiforgery is not used: the form carries nothing of a session (an anonymous visitor has none) and the single-use +// signed challenge in it is the only credential, so there is no session to ride. +app.MapPost("/auth/bifrost/register/form", async ( + HttpContext httpContext, + NativeRegistration registration, + RegistrationChallengeService challenges, + IOptions registrationOptions, + CancellationToken cancellationToken) => +{ + if (!(httpContext.Request.ContentType ?? "").StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { - return Results.Text( - $"Registration requires accepting the training notice, current version {TrainingNotice.Version}.", - statusCode: StatusCodes.Status400BadRequest); - } - - if (!challenges.TryConsume(request.Challenge, request.Nonce)) - { - return Results.Text("Registration challenge failed.", statusCode: StatusCodes.Status400BadRequest); + return Results.Text("Send the form as application/x-www-form-urlencoded.", statusCode: StatusCodes.Status415UnsupportedMediaType); } + IFormCollection form; try { - var userAccount = await bifrostIdentityService.RegisterNativeAsync( - request.Identity, - request.DisplayName, - TrainingNotice.Version, - 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 (Exception error) when (error is InvalidDataException or BadHttpRequestException) { - return Results.Text(error.Message, statusCode: StatusCodes.Status400BadRequest); + 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: without it the posted notice version is not taken as accepted. + int? accepted = Field("consent") == "yes" && int.TryParse(Field("acceptedNoticeVersion"), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var version) + ? version + : null; + 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); + } + + // Only a time-lock refusal leaves the challenge unspent and worth keeping: its clock must not restart. Any other + // failure gets a fresh challenge, and the consent box 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.WaitRemaining is not null ? 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) => @@ -814,6 +875,36 @@ 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"; @@ -870,7 +961,8 @@ public sealed record NativeBifrostRegistrationRequest( string? ReturnUrl, string? Challenge, string? Nonce, - int? AcceptedNoticeVersion); + int? AcceptedNoticeVersion, + bool? Waited = null); public sealed record NativeBifrostRegistrationResponse( Guid UserAccountId, diff --git a/tests/Bifrost.Web.Tests/Fixtures/registration-page-harness.cjs b/tests/Bifrost.Web.Tests/Fixtures/registration-page-harness.cjs new file mode 100644 index 0000000..facc26a --- /dev/null +++ b/tests/Bifrost.Web.Tests/Fixtures/registration-page-harness.cjs @@ -0,0 +1,56 @@ +// Runs the sign-up page's real inline script against a simulated browser and prints what it did as JSON. +// Usage: node registration-page-harness.cjs +const fs = require("fs"); +const vm = require("vm"); +const { webcrypto } = require("crypto"); + +const html = fs.readFileSync(process.argv[2], "utf8"); +const scripts = [...html.matchAll(/\">"; + + using var response = await FormKit.PostAsync(client, FormKit.Fields(html, hostile, consent: false)); + var again = await response.Content.ReadAsStringAsync(); + + Assert.DoesNotContain("