Registration: sign-up form with proof-of-work and a no-JS time-lock fallback (#56)
This commit is contained in:
parent
b2e0bb2514
commit
028bc2fdf6
16 changed files with 1674 additions and 121 deletions
|
|
@ -7,7 +7,11 @@ public sealed class RegistrationOptions
|
|||
|
||||
public const int MinDifficulty = 1;
|
||||
|
||||
public const int MaxDifficulty = 30;
|
||||
public const int MaxDifficulty = 24;
|
||||
|
||||
public const int MinFallbackWaitSeconds = 5;
|
||||
|
||||
public const int MaxFallbackWaitSeconds = 300;
|
||||
|
||||
public RegistrationCaptchaOptions Captcha { 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;
|
||||
|
||||
/// <summary>Time-lock submissions (no script, no proof of work) per address per <see cref="FallbackWindow"/>; far tighter than <see cref="PerAddressPermits"/> because they cost the client nothing.</summary>
|
||||
public int FallbackPermits { get; init; } = 3;
|
||||
|
||||
public TimeSpan FallbackWindow { get; init; } = TimeSpan.FromHours(1);
|
||||
}
|
||||
|
||||
public sealed class RegistrationCaptchaOptions
|
||||
{
|
||||
/// <summary>Leading zero bits the SHA-256 of <c>challenge:nonce</c> must have. 18 is about 262k hashes, a second or two in a browser.</summary>
|
||||
public int Difficulty { get; init; } = 18;
|
||||
|
||||
/// <summary>Seconds after the challenge was issued before a <c>waited</c> (no proof of work) submission is accepted.</summary>
|
||||
public int FallbackWaitSeconds { get; init; } = 30;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,29 +0,0 @@
|
|||
using Bifrost.Web.Configuration;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Bifrost.Web.Features.ConceptVotes;
|
||||
|
||||
// The one place that decides whether a state-changing request to the vote page came from the site itself. The anonymous
|
||||
// vote flow carries 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 CastRequestGuard
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -12,11 +12,11 @@ public sealed partial class BifrostIdentityService(
|
|||
BifrostDbContext dbContext,
|
||||
TimeProvider timeProvider)
|
||||
{
|
||||
public async Task<UserAccount> RegisterNativeAsync(
|
||||
string identity,
|
||||
string? displayName,
|
||||
int noticeVersion,
|
||||
CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// The one rule set for a new native identity: well formed, not reserved, not taken. Returns the normalized identity or
|
||||
/// throws <see cref="BifrostIdentityException"/>. Spends nothing; the unique index at insert stays the race backstop.
|
||||
/// </summary>
|
||||
public async Task<string> CheckAvailableAsync(string identity, CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedIdentity = NormalizeIdentity(identity);
|
||||
if (IsReserved(normalizedIdentity))
|
||||
|
|
@ -24,14 +24,22 @@ public sealed partial class BifrostIdentityService(
|
|||
throw new BifrostIdentityException("That Bifrost identity is reserved.");
|
||||
}
|
||||
|
||||
var exists = await dbContext.UserAccounts.AnyAsync(
|
||||
x => x.NormalizedBifrostIdentity == normalizedIdentity,
|
||||
cancellationToken);
|
||||
if (exists)
|
||||
if (await dbContext.UserAccounts.AnyAsync(x => x.NormalizedBifrostIdentity == normalizedIdentity, cancellationToken))
|
||||
{
|
||||
throw new BifrostIdentityException("That Bifrost identity is already registered.");
|
||||
}
|
||||
|
||||
return normalizedIdentity;
|
||||
}
|
||||
|
||||
public async Task<UserAccount> RegisterNativeAsync(
|
||||
string identity,
|
||||
string? displayName,
|
||||
int noticeVersion,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedIdentity = await CheckAvailableAsync(identity, cancellationToken);
|
||||
|
||||
var now = timeProvider.GetUtcNow();
|
||||
var publicIdentity = ToPublicIdentity(normalizedIdentity);
|
||||
var resolvedDisplayName = string.IsNullOrWhiteSpace(displayName)
|
||||
|
|
@ -66,10 +74,31 @@ public sealed partial class BifrostIdentityService(
|
|||
NoticeVersion = noticeVersion,
|
||||
AcceptedAtUtc = now
|
||||
});
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
// Only a lost race on the unique index is the caller's mistake; anything else is a fault and propagates.
|
||||
if (!await IdentityTakenAsync(normalizedIdentity))
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
throw new BifrostIdentityException("That Bifrost identity is already registered.");
|
||||
}
|
||||
|
||||
return userAccount;
|
||||
}
|
||||
|
||||
// A lost race on the unique index: the tracked insert is dropped and the identity is read fresh.
|
||||
private async Task<bool> IdentityTakenAsync(string normalizedIdentity)
|
||||
{
|
||||
dbContext.ChangeTracker.Clear();
|
||||
return await dbContext.UserAccounts.AnyAsync(x => x.NormalizedBifrostIdentity == normalizedIdentity);
|
||||
}
|
||||
|
||||
public async Task EnsureIdentityAsync(
|
||||
UserAccount userAccount,
|
||||
string preferredIdentity,
|
||||
|
|
|
|||
123
src/Bifrost.Web/Features/Registration/NativeRegistration.cs
Normal file
123
src/Bifrost.Web/Features/Registration/NativeRegistration.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Membership;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
|
||||
namespace Bifrost.Web.Features.Registration;
|
||||
|
||||
/// <summary>What a client sent to register. <see cref="Waited"/> claims the time-lock path instead of a proof of work.</summary>
|
||||
public sealed record RegistrationAttempt(
|
||||
string? Identity,
|
||||
string? DisplayName,
|
||||
string? Challenge,
|
||||
string? Nonce,
|
||||
bool Waited,
|
||||
int? AcceptedNoticeVersion);
|
||||
|
||||
/// <summary>Which input a refusal is about, so the form can mark it invalid.</summary>
|
||||
public enum RegistrationField { None, Identity, Consent }
|
||||
|
||||
/// <summary>
|
||||
/// Either a signed-in <see cref="Account"/>, or a <see cref="Refusal"/> to return as is (the rate limits), or a rejection
|
||||
/// with a status and message. <see cref="KeepChallenge"/> is set when the challenge was not spent and a retry needs only a correction, so the form should carry it on (the time-lock clock must not restart).
|
||||
/// </summary>
|
||||
public sealed record RegistrationOutcome(
|
||||
UserAccount? Account,
|
||||
IResult? Refusal,
|
||||
int Status,
|
||||
string? Message,
|
||||
RegistrationField Field,
|
||||
bool KeepChallenge)
|
||||
{
|
||||
public static RegistrationOutcome Reject(int status, string message, RegistrationField field = RegistrationField.None, bool keepChallenge = false) =>
|
||||
new(null, null, status, message, field, keepChallenge);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The one registration gate, run by the JSON endpoint and the form alike after each has spent the general address budget.
|
||||
/// Order: consent, one proof only, the identity rules (which spend nothing), 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, and a refusal before the challenge step spends neither the challenge nor a fallback permit.
|
||||
/// </summary>
|
||||
public sealed class NativeRegistration(
|
||||
BifrostIdentityService identities,
|
||||
RegistrationChallengeService challenges,
|
||||
RegistrationRateLimit rateLimit)
|
||||
{
|
||||
public async Task<RegistrationOutcome> RunAsync(HttpContext http, RegistrationAttempt attempt, CancellationToken cancellationToken)
|
||||
{
|
||||
// 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.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await identities.CheckAvailableAsync(attempt.Identity ?? "", cancellationToken);
|
||||
}
|
||||
catch (BifrostIdentityException error)
|
||||
{
|
||||
return RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, error.Message, RegistrationField.Identity, keepChallenge: true);
|
||||
}
|
||||
|
||||
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. Your challenge is still good; submit again then.",
|
||||
keepChallenge: true);
|
||||
}
|
||||
|
||||
if (rateLimit.RefuseFallback(http) is { } fallbackRefused)
|
||||
{
|
||||
return new(null, fallbackRefused, 0, null, RegistrationField.None, false);
|
||||
}
|
||||
|
||||
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, false);
|
||||
}
|
||||
catch (BifrostIdentityException error)
|
||||
{
|
||||
return RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, error.Message, RegistrationField.Identity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -50,58 +50,101 @@ 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);
|
||||
}
|
||||
|
||||
/// <summary>Proof-of-work path: the nonce must meet the difficulty the challenge was issued with. Spends the challenge.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Time-lock path, step one: how long until a <c>waited</c> 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.
|
||||
/// </summary>
|
||||
public TimeSpan? WaitRemaining(string? challenge)
|
||||
{
|
||||
if (Open(challenge) is not { } open)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var remaining = open.IssuedAt + TimeSpan.FromSeconds(options.Value.Captcha.FallbackWaitSeconds) - clock.GetUtcNow();
|
||||
return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero;
|
||||
}
|
||||
|
||||
/// <summary>Time-lock path, step two: spends the challenge if its wait is over. No proof of work is checked.</summary>
|
||||
public bool TryConsumeWaited(string? challenge) =>
|
||||
WaitRemaining(challenge) == TimeSpan.Zero && Open(challenge) is { } open && Spend(open);
|
||||
|
||||
/// <summary>True when the token is ours, unexpired and not yet spent, so a form may carry it into its next attempt.</summary>
|
||||
public bool IsLive(string? challenge)
|
||||
{
|
||||
if (Open(challenge) is not { } open)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (gate)
|
||||
{
|
||||
return !consumed.Contains(open.Id);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record OpenChallenge(string Id, int Difficulty, DateTimeOffset ExpiresAt, DateTimeOffset IssuedAt);
|
||||
|
||||
/// <summary>The payload of a challenge that we protected and that has not expired; null otherwise.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
176
src/Bifrost.Web/Features/Registration/RegistrationPage.cs
Normal file
176
src/Bifrost.Web/Features/Registration/RegistrationPage.cs
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
namespace Bifrost.Web.Features.Registration;
|
||||
|
||||
/// <summary>What the sign-up page shows. Everything user-supplied is HTML-encoded on the way out.</summary>
|
||||
public sealed record RegistrationPageModel(
|
||||
string ReturnPath,
|
||||
string Challenge,
|
||||
int Difficulty,
|
||||
int WaitSeconds,
|
||||
string Identity = "",
|
||||
string DisplayName = "",
|
||||
string? Error = null,
|
||||
RegistrationField ErrorField = RegistrationField.None);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
var skipped = 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; !skipped; 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); });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
form.addEventListener("submit", function (event) {
|
||||
if (event.submitter && event.submitter.id === "skip") {
|
||||
// The way out of a slow solve: stop it and let this submit go on the time-lock path.
|
||||
skipped = true;
|
||||
solved = true;
|
||||
form.elements.nonce.value = "";
|
||||
form.elements.waited.disabled = false;
|
||||
status.textContent = "Skipping the automatic check.";
|
||||
return;
|
||||
}
|
||||
if (solved) { return; }
|
||||
event.preventDefault();
|
||||
if (busy) { return; }
|
||||
busy = true;
|
||||
status.textContent = "Checking. This can take longer on a slow device; press Skip the automatic check to wait " + form.getAttribute("data-wait") + " seconds instead.";
|
||||
solve(form.elements.challenge.value, parseInt(form.getAttribute("data-difficulty"), 10)).then(function (nonce) {
|
||||
if (skipped || nonce === null) { return; }
|
||||
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 automatic check did not run in this browser. Press Skip the automatic check and wait as 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)
|
||||
{
|
||||
var link = model.ErrorField switch
|
||||
{
|
||||
RegistrationField.Identity => """<ul><li><a href="#identity">Identity name</a></li></ul>""",
|
||||
RegistrationField.Consent => """<ul><li><a href="#consent">I have read this notice and consent</a></li></ul>""",
|
||||
_ => ""
|
||||
};
|
||||
summary.Append($"""<div id="errors" role="alert" tabindex="-1"><strong>Registration did not go through.</strong><p>{E(model.Error)}</p>{link}</div>""");
|
||||
}
|
||||
|
||||
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 $$"""
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Create an account - Bifrost</title>
|
||||
<style>
|
||||
body { margin: 0; min-height: 100svh; display: grid; place-items: center; background: #090908; color: #fff8ef; font-family: system-ui, sans-serif; line-height: 1.5; }
|
||||
main { width: min(92vw, 600px); margin: 24px 0; padding: 28px; border: 1px solid rgba(255,248,239,.16); border-radius: 8px; background: #141110; }
|
||||
h1 { margin: 0 0 10px; font-size: 2rem; line-height: 1.1; }
|
||||
p { color: #c7b8ad; }
|
||||
fieldset { margin: 20px 0 0; padding: 14px 16px; border: 1px solid #8a7d73; border-radius: 6px; }
|
||||
legend { padding: 0 6px; color: #d9ad66; font-weight: 750; }
|
||||
label { display: block; margin-top: 12px; font-weight: 650; }
|
||||
.hint { margin: 2px 0 0; font-size: .9rem; }
|
||||
input[type=text] { box-sizing: border-box; width: 100%; min-height: 44px; margin-top: 4px; padding: 0 10px; border: 1px solid #8a7d73; border-radius: 6px; background: #0d0b0a; color: #fff8ef; font: inherit; }
|
||||
input[type=checkbox] { width: 22px; height: 22px; margin: 0 8px 0 0; vertical-align: middle; accent-color: #c43e4f; }
|
||||
label.check { display: flex; align-items: center; margin-top: 14px; }
|
||||
button.secondary { margin-left: 10px; background: #2a2522; border: 1px solid #8a7d73; }
|
||||
button { margin-top: 20px; min-height: 46px; padding: 0 18px; border: 0; border-radius: 6px; background: #c43e4f; color: #fff; font: inherit; font-weight: 750; cursor: pointer; }
|
||||
:focus-visible { outline: 3px solid #ffd27a; outline-offset: 2px; }
|
||||
#errors { margin-top: 18px; padding: 10px 14px; border: 2px solid #ff9aa6; border-radius: 6px; color: #ffc2c9; }
|
||||
#errors p { margin: 4px 0 0; color: #ffc2c9; }
|
||||
[aria-invalid=true] { border-color: #ff9aa6; }
|
||||
#status { min-height: 1.5em; color: #fff8ef; }
|
||||
small { color: #d9ad66; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<small>Public registration</small>
|
||||
<h1>Create a Bifrost account</h1>
|
||||
<p>A new account can chat. It has no vote and opens no member or governance surface.</p>
|
||||
{{summary}}
|
||||
<form id="register" method="post" action="/auth/bifrost/register/form" data-difficulty="{{model.Difficulty}}" data-wait="{{wait}}">
|
||||
<fieldset>
|
||||
<legend>Your account</legend>
|
||||
<label for="identity">Identity name</label>
|
||||
<input type="text" id="identity" name="identity" value="{{E(model.Identity)}}" required autocomplete="username" autocapitalize="none" spellcheck="false"{{Invalid(RegistrationField.Identity)}} />
|
||||
<label for="displayName">Display name (optional)</label>
|
||||
<input type="text" id="displayName" name="displayName" value="{{E(model.DisplayName)}}" autocomplete="nickname" />
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Training notice, version {{notice}}</legend>
|
||||
<p id="notice">{{E(TrainingNotice.Text)}}</p>
|
||||
<label class="check" for="consent"><input type="checkbox" id="consent" name="consent" value="yes" required aria-describedby="notice"{{Invalid(RegistrationField.Consent)}} />I have read this notice and consent</label>
|
||||
<input type="hidden" name="acceptedNoticeVersion" value="{{notice}}" />
|
||||
</fieldset>
|
||||
<input type="hidden" name="challenge" value="{{E(model.Challenge)}}" />
|
||||
<input type="hidden" name="returnUrl" value="{{E(model.ReturnPath)}}" />
|
||||
<input type="hidden" name="nonce" value="" />
|
||||
<input type="hidden" name="waited" value="true" />
|
||||
<p id="status" aria-live="polite"></p>
|
||||
<button type="submit" id="create">Create account</button>
|
||||
<button type="submit" id="skip" class="secondary">Skip the automatic check and wait {{wait}} seconds instead</button>
|
||||
</form>
|
||||
<p class="hint" id="wait-note">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 the box again before you submit. Without the automatic check only a few registrations per hour are accepted from one address.</p>
|
||||
<p><small>After registering, Bifrost returns you to {{E(model.ReturnPath)}}.</small></p>
|
||||
</main>
|
||||
<script>{{Script}}</script>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
}
|
||||
}
|
||||
|
|
@ -17,18 +17,31 @@ public sealed class RegistrationRateLimit(IOptions<RegistrationOptions> 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);
|
||||
|
||||
/// <summary>Null when the request may proceed; otherwise the refusal to return.</summary>
|
||||
public IResult? Refuse(HttpContext http)
|
||||
public IResult? Refuse(HttpContext http) => Refuse(http, addresses, "Too many registration requests from this address.");
|
||||
|
||||
/// <summary>The stricter budget for a submission that passed the time-lock instead of the proof of work.</summary>
|
||||
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)
|
||||
{
|
||||
|
|
|
|||
41
src/Bifrost.Web/Features/Shared/RequestOriginGuard.cs
Normal file
41
src/Bifrost.Web/Features/Shared/RequestOriginGuard.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Allows"/> judges it, and a headerless request
|
||||
/// that does carry a session cookie is refused.
|
||||
/// </summary>
|
||||
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)));
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -135,6 +135,7 @@ builder.Services.AddSingleton<MindIntakeRateLimit>(); // TimeProvider and option
|
|||
builder.Services.AddOptions<RegistrationOptions>().BindConfiguration(RegistrationOptions.SectionName);
|
||||
builder.Services.AddSingleton<RegistrationChallengeService>();
|
||||
builder.Services.AddSingleton<RegistrationRateLimit>();
|
||||
builder.Services.AddScoped<NativeRegistration>();
|
||||
builder.Services.AddHostedService<SealedBallotCloser>();
|
||||
builder.Services.AddScoped<MotionEveSurfaceService>();
|
||||
builder.Services.AddScoped<PatronageService>();
|
||||
|
|
@ -389,8 +390,7 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuth
|
|||
app.MapPost("/auth/bifrost/register", async (
|
||||
NativeBifrostRegistrationRequest request,
|
||||
HttpContext httpContext,
|
||||
BifrostIdentityService bifrostIdentityService,
|
||||
RegistrationChallengeService challenges,
|
||||
NativeRegistration registration,
|
||||
RegistrationRateLimit rateLimit,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
|
|
@ -399,44 +399,142 @@ app.MapPost("/auth/bifrost/register", async (
|
|||
return refused;
|
||||
}
|
||||
|
||||
// Consent first, then the proof of work; a refusal here creates nothing.
|
||||
if (request.AcceptedNoticeVersion != TrainingNotice.Version)
|
||||
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 Results.Text(
|
||||
$"Registration requires accepting the training notice, current version {TrainingNotice.Version}.",
|
||||
statusCode: StatusCodes.Status400BadRequest);
|
||||
return outcome.Refusal;
|
||||
}
|
||||
|
||||
if (!challenges.TryConsume(request.Challenge, request.Nonce))
|
||||
if (outcome.Account is not { } userAccount)
|
||||
{
|
||||
return Results.Text("Registration challenge failed.", statusCode: StatusCodes.Status400BadRequest);
|
||||
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> 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<BifrostHostOptions> hostOptions,
|
||||
IOptions<RegistrationOptions> 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<Microsoft.AspNetCore.Http.Features.IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } limit)
|
||||
{
|
||||
limit.MaxRequestBodySize = MaxFormBytes;
|
||||
}
|
||||
|
||||
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 (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: 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);
|
||||
}
|
||||
|
||||
// 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) =>
|
||||
|
|
@ -814,6 +912,36 @@ static async Task<IFormCollection?> 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 +998,8 @@ public sealed record NativeBifrostRegistrationRequest(
|
|||
string? ReturnUrl,
|
||||
string? Challenge,
|
||||
string? Nonce,
|
||||
int? AcceptedNoticeVersion);
|
||||
int? AcceptedNoticeVersion,
|
||||
bool? Waited = null);
|
||||
|
||||
public sealed record NativeBifrostRegistrationResponse(
|
||||
Guid UserAccountId,
|
||||
|
|
|
|||
Loading…
Reference in a new issue