Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Integrate invite code into API registration flow and add rate limiting (#2143)

Leendert de Borsta5fc13aba909
diff --git a/apps/server/AliasVault.Api/Config.cs b/apps/server/AliasVault.Api/Config.cs
index ebede6b57..647835737 100644
--- a/apps/server/AliasVault.Api/Config.cs
+++ b/apps/server/AliasVault.Api/Config.cs
@@ -17,7 +17,7 @@ public class Config : SharedConfig
/// <summary>
/// Gets or sets a value indicating whether public registration is enabled.
/// </summary>
- public bool PublicRegistrationEnabled { get; set; }
+ public virtual bool PublicRegistrationEnabled { get; set; }
/// <summary>
/// Gets or sets the list of private email domains that are available.
diff --git a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs
index a9bdca953..91d24a136 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs
@@ -28,6 +28,7 @@ using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.IdentityModel.Tokens;
@@ -487,6 +488,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
/// <param name="model">ValidateUsernameRequest model.</param>
/// <returns>IActionResult.</returns>
[HttpPost("validate-username")]
+ [EnableRateLimiting(RegistrationCheckRateLimit.PolicyName)]
[AllowAnonymous]
public async Task<IActionResult> ValidateUsername([FromBody] ValidateUsernameRequest model)
{
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index e9fd40ba1..1ff109fd0 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -29,6 +29,7 @@ using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.IdentityModel.Tokens;
@@ -48,10 +49,11 @@ using SecureRemotePassword;
/// <param name="registrationRateLimitService">RegistrationRateLimitService instance.</param>
/// <param name="ipBlockListService">IpBlockListService instance.</param>
/// <param name="mobileLoginRateLimitService">MobileLoginRateLimitService instance.</param>
+/// <param name="registrationInviteService">RegistrationInviteService instance.</param>
[Route("v{version:apiVersion}/[controller]")]
[ApiController]
[ApiVersion("2")]
-public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService) : ControllerBase
+public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService, RegistrationInviteService registrationInviteService) : ControllerBase
{
/// <summary>
/// Access token validity in minutes.
@@ -388,8 +390,9 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequest model)
{
- // Check if public registration is disabled in the configuration.
- if (!config.PublicRegistrationEnabled)
+ // Without public registration only an invite code holder may register. The invite use is taken right before the account is created.
+ var requiresInvite = !config.PublicRegistrationEnabled;
+ if (requiresInvite && string.IsNullOrWhiteSpace(model.InviteCode))
{
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
}
@@ -444,6 +447,17 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
PasswordChangedAt = timeProvider.GetUtcNow().UtcDateTime,
};
+ Guid? inviteId = null;
+ if (requiresInvite)
+ {
+ inviteId = await registrationInviteService.TryConsumeAsync(model.InviteCode);
+ if (inviteId is null)
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.InvalidInviteCode);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITE_CODE_INVALID, 400));
+ }
+ }
+
var personalManifestId = Guid.NewGuid();
// Create the personal group before the user row.
@@ -533,12 +547,17 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return Ok(tokenModel);
}
- // Identity creation failed: remove the personal group written ahead of the user row above.
+ // Identity creation failed: remove the personal group written ahead of the user row above and give the invite use back.
await using (var context = await dbContextFactory.CreateDbContextAsync())
{
await context.Groups.Where(g => g.Id == personalGroup.Id).ExecuteDeleteAsync();
}
+ if (inviteId is not null)
+ {
+ await registrationInviteService.ReleaseAsync(inviteId.Value);
+ }
+
var errors = result.Errors.Select(e => e.Description).ToArray();
return BadRequest(ServerValidationErrorResponse.Create(errors, 400));
}
@@ -665,14 +684,22 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
/// <param name="model">ValidateUsernameRequest model.</param>
/// <returns>IActionResult.</returns>
[HttpPost("validate-username")]
+ [EnableRateLimiting(RegistrationCheckRateLimit.PolicyName)]
[AllowAnonymous]
public async Task<IActionResult> ValidateUsername([FromBody] ValidateUsernameRequest model)
{
- // Check if public registration is disabled in the configuration.
- // This prevents username enumeration when registration is disabled.
+ // Without public registration only an invite code holder may check usernames, which prevents username enumeration.
if (!config.PublicRegistrationEnabled)
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
+ if (string.IsNullOrWhiteSpace(model.InviteCode))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
+ }
+
+ if (!await registrationInviteService.IsValidAsync(model.InviteCode))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVITE_CODE_INVALID, 400));
+ }
}
if (string.IsNullOrWhiteSpace(model.Username))
@@ -699,6 +726,24 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return Ok(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_AVAILABLE, 200));
}
+ /// <summary>
+ /// Check whether a registration invite code can be used.
+ /// </summary>
+ /// <param name="model">ValidateInviteCodeRequest model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("validate-invite-code")]
+ [EnableRateLimiting(RegistrationCheckRateLimit.PolicyName)]
+ [AllowAnonymous]
+ public async Task<IActionResult> ValidateInviteCode([FromBody] ValidateInviteCodeRequest model)
+ {
+ if (!await registrationInviteService.IsValidAsync(model.InviteCode))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVITE_CODE_INVALID, 400));
+ }
+
+ return Ok();
+ }
+
/// <summary>
/// Initiates the account deletion process.
/// </summary>
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Tests/TestConfig.cs b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestConfig.cs
new file mode 100644
index 000000000..62daf17e2
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestConfig.cs
@@ -0,0 +1,33 @@
+//-----------------------------------------------------------------------
+// <copyright file="TestConfig.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Api.Controllers.V2.Tests;
+
+#if DEBUG
+
+/// <summary>
+/// Config used in DEBUG builds running in Development, where an E2E test can override values for its own requests via
+/// request headers.
+/// </summary>
+/// <param name="httpContextAccessor">IHttpContextAccessor instance.</param>
+public class TestConfig(IHttpContextAccessor httpContextAccessor) : Config
+{
+ /// <summary>
+ /// Request header that disables public registration for that request.
+ /// </summary>
+ public const string DisablePublicRegistrationHeader = "X-AliasVault-Test-Disable-Public-Registration";
+
+ /// <inheritdoc />
+ public override bool PublicRegistrationEnabled
+ {
+ get => !HasHeader(DisablePublicRegistrationHeader) && base.PublicRegistrationEnabled;
+ set => base.PublicRegistrationEnabled = value;
+ }
+
+ private bool HasHeader(string name) => httpContextAccessor.HttpContext?.Request.Headers.ContainsKey(name) ?? false;
+}
+#endif
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs
index 757ffea14..b7feed2a7 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs
@@ -34,12 +34,14 @@ using Microsoft.EntityFrameworkCore;
/// <param name="environment">IWebHostEnvironment instance.</param>
/// <param name="dbContextFactory">DbContext factory instance.</param>
/// <param name="serverSettingsService">ServerSettingsService instance.</param>
+/// <param name="registrationInviteService">RegistrationInviteService instance.</param>
[ApiVersion("2")]
public class TestController(
UserManager<AliasVaultUser> userManager,
IWebHostEnvironment environment,
IAliasServerDbContextFactory dbContextFactory,
- ServerSettingsService serverSettingsService) : AuthenticatedRequestController(userManager)
+ ServerSettingsService serverSettingsService,
+ RegistrationInviteService registrationInviteService) : AuthenticatedRequestController(userManager)
{
/// <summary>
/// Authenticated test request. Used to verify authentication is working.
@@ -463,6 +465,25 @@ public class TestController(
});
}
+ /// <summary>
+ /// Create a registration invite and return its code, as the admin panel would.
+ /// Only available in DEBUG builds.
+ /// </summary>
+ /// <param name="maxUses">Number of accounts that may register with the invite.</param>
+ /// <returns>OK with the invite code.</returns>
+ [AllowAnonymous]
+ [HttpPost("registration-invites")]
+ public async Task<IActionResult> CreateRegistrationInvite([FromQuery] int maxUses = 1)
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ var code = await registrationInviteService.CreateAsync("E2E test", maxUses, null, "e2e");
+ return Ok(new { code });
+ }
+
/// <summary>
/// Get a server setting by key.
/// Anonymous endpoint for E2E tests that cannot access auth tokens.
diff --git a/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs b/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs
new file mode 100644
index 000000000..96b81cb57
--- /dev/null
+++ b/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs
@@ -0,0 +1,86 @@
+//-----------------------------------------------------------------------
+// <copyright file="RegistrationCheckRateLimit.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Api.Helpers;
+
+using System.Net;
+using System.Net.Sockets;
+using System.Threading.RateLimiting;
+using AliasVault.Auth.IpAddress;
+using AliasVault.Shared.Models.Enums;
+using AliasVault.Shared.Models.WebApi;
+using Microsoft.AspNetCore.RateLimiting;
+
+/// <summary>
+/// Per-IP flood limit for the anonymous registration checks (username availability, invite code).
+/// </summary>
+public static class RegistrationCheckRateLimit
+{
+ /// <summary>
+ /// Name of the rate limiter policy, for <see cref="EnableRateLimitingAttribute"/>.
+ /// </summary>
+ public const string PolicyName = "RegistrationChecks";
+
+ /// <summary>
+ /// Requests a client can make in a burst, shared by all registration check endpoints.
+ /// </summary>
+ private const int BurstLimit = 30;
+
+ /// <summary>
+ /// How often a client gets one more request, which caps the sustained rate at 3 per minute.
+ /// </summary>
+ private static readonly TimeSpan ReplenishmentPeriod = TimeSpan.FromSeconds(20);
+
+ /// <summary>
+ /// Add the policy and the 429 response to the rate limiter options.
+ /// </summary>
+ /// <param name="options">The rate limiter options.</param>
+ /// <param name="isDevelopment">Whether the API runs in Development, where E2E tests register in bulk from one IP and the limit is off.</param>
+ public static void Configure(RateLimiterOptions options, bool isDevelopment)
+ {
+ options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
+ options.OnRejected = async (context, cancellationToken) =>
+ await context.HttpContext.Response.WriteAsJsonAsync(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REGISTRATION_RATE_LIMIT_EXCEEDED, StatusCodes.Status429TooManyRequests), cancellationToken);
+
+ options.AddPolicy(PolicyName, httpContext =>
+ {
+ if (isDevelopment)
+ {
+ return RateLimitPartition.GetNoLimiter(string.Empty);
+ }
+
+ return RateLimitPartition.GetTokenBucketLimiter(GetClientKey(httpContext), _ => new TokenBucketRateLimiterOptions
+ {
+ TokenLimit = BurstLimit,
+ TokensPerPeriod = 1,
+ ReplenishmentPeriod = ReplenishmentPeriod,
+ QueueLimit = 0,
+ });
+ });
+ }
+
+ /// <summary>
+ /// The client IP as partition key, IPv6 reduced to its /64 since a single client usually controls a whole /64.
+ /// </summary>
+ private static string GetClientKey(HttpContext httpContext)
+ {
+ var ip = IpAddressUtility.GetRawIpAddressFromContext(httpContext);
+ if (ip is null)
+ {
+ return "unknown";
+ }
+
+ if (ip.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ var bytes = ip.GetAddressBytes();
+ Array.Clear(bytes, 8, 8);
+ return new IPAddress(bytes).ToString();
+ }
+
+ return ip.ToString();
+ }
+}
diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.cs
index 3728122cd..149f3c3ff 100644
--- a/apps/server/AliasVault.Api/Program.cs
+++ b/apps/server/AliasVault.Api/Program.cs
@@ -12,6 +12,7 @@ using System.Text.Json;
using AliasServerDb;
using AliasServerDb.Configuration;
using AliasVault.Api;
+using AliasVault.Api.Helpers;
using AliasVault.Api.Jwt;
using AliasVault.Api.Services;
using AliasVault.Auth;
@@ -39,7 +40,12 @@ CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
+#if DEBUG
+// E2E tests override config values for their own requests via headers, see TestConfig.
+var config = builder.Environment.IsDevelopment() ? new AliasVault.Api.Controllers.V2.Tests.TestConfig(new HttpContextAccessor()) : new Config();
+#else
var config = new Config();
+#endif
var publicRegistrationEnabled = Environment.GetEnvironmentVariable("PUBLIC_REGISTRATION_ENABLED") ?? "false";
config.PublicRegistrationEnabled = bool.Parse(publicRegistrationEnabled);
@@ -84,12 +90,14 @@ builder.Services.AddScoped<TimeValidationJwtBearerEvents>();
builder.Services.AddScoped<AuthLoggingService>();
builder.Services.AddScoped<ServerSettingsService>();
builder.Services.AddScoped<RegistrationRateLimitService>();
+builder.Services.AddScoped<RegistrationInviteService>();
builder.Services.AddScoped<IpBlockListService>();
builder.Services.AddScoped<MobileLoginRateLimitService>();
builder.Services.AddSingleton<FaviconRateLimitService>();
builder.Services.AddScoped<RateLimitService>();
builder.Services.AddScoped<CapabilityService>();
builder.Services.AddHttpContextAccessor();
+builder.Services.AddRateLimiter(options => RegistrationCheckRateLimit.Configure(options, builder.Environment.IsDevelopment()));
builder.Services.AddLogging(logging =>
{
@@ -214,6 +222,7 @@ if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PATHBAS
app.UseAuthentication();
app.UseAuthorization();
+app.UseRateLimiter();
app.MapControllers();
diff --git a/apps/server/Databases/AliasServerDb/AuthLog.cs b/apps/server/Databases/AliasServerDb/AuthLog.cs
index bc6c18959..adc9b787f 100644
--- a/apps/server/Databases/AliasServerDb/AuthLog.cs
+++ b/apps/server/Databases/AliasServerDb/AuthLog.cs
@@ -77,6 +77,11 @@ public enum AuthFailureReason
/// </summary>
MobileLoginDeclined = 12,
+ /// <summary>
+ /// Indicates that the registration used an invite code that is unknown, expired or used up.
+ /// </summary>
+ InvalidInviteCode = 13,
+
/// <summary>
/// Indicates that the failure reason was unknown.
/// </summary>
diff --git a/apps/server/Shared/AliasVault.Shared.Server/Services/RegistrationInviteService.cs b/apps/server/Shared/AliasVault.Shared.Server/Services/RegistrationInviteService.cs
new file mode 100644
index 000000000..c1d827265
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared.Server/Services/RegistrationInviteService.cs
@@ -0,0 +1,196 @@
+//-----------------------------------------------------------------------
+// <copyright file="RegistrationInviteService.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Server.Services;
+
+using System;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading.Tasks;
+using AliasServerDb;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Creates, checks and consumes registration invites.
+/// </summary>
+/// <param name="dbContextFactory">IDbContextFactory instance.</param>
+/// <param name="timeProvider">TimeProvider instance.</param>
+public class RegistrationInviteService(IAliasServerDbContextFactory dbContextFactory, TimeProvider timeProvider)
+{
+ /// <summary>
+ /// Characters allowed in a code (skip ambiguous characters).
+ /// </summary>
+ private const string CodeAlphabet = "23456789ABCDEFGHJKMNPQRSTVWXYZ";
+
+ /// <summary>
+ /// Number of code characters.
+ /// </summary>
+ private const int CodeLength = 20;
+
+ /// <summary>
+ /// Maximum accepted length of a code as entered by a user, before normalization.
+ /// </summary>
+ private const int MaxInputLength = 64;
+
+ /// <summary>
+ /// Normalize a code as entered by a user: uppercase, separators removed.
+ /// </summary>
+ /// <param name="code">The code as entered.</param>
+ /// <returns>The normalized code.</returns>
+ public static string NormalizeCode(string code)
+ {
+ var sb = new StringBuilder(code.Length);
+ foreach (var c in code.ToUpperInvariant())
+ {
+ switch (c)
+ {
+ case '-' or ' ' or '\t':
+ continue;
+ case 'O':
+ sb.Append('0');
+ break;
+ case 'I' or 'L':
+ sb.Append('1');
+ break;
+ default:
+ sb.Append(c);
+ break;
+ }
+ }
+
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Format a code in groups of four for display.
+ /// </summary>
+ /// <param name="code">The normalized code.</param>
+ /// <returns>The formatted code.</returns>
+ public static string FormatCode(string code)
+ {
+ var sb = new StringBuilder();
+ for (var i = 0; i < code.Length; i += 4)
+ {
+ if (i > 0)
+ {
+ sb.Append('-');
+ }
+
+ sb.Append(code.AsSpan(i, Math.Min(4, code.Length - i)));
+ }
+
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Create an invite and return its code.
+ /// </summary>
+ /// <param name="note">Optional admin note.</param>
+ /// <param name="maxUses">Number of accounts that may register with the invite.</param>
+ /// <param name="expiresAt">Expiry moment in UTC, or null for no expiry.</param>
+ /// <param name="createdBy">The admin username creating the invite.</param>
+ /// <returns>The invite code, formatted in groups of four.</returns>
+ public async Task<string> CreateAsync(string? note, int maxUses, DateTime? expiresAt, string? createdBy)
+ {
+ var code = GenerateCode();
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ context.RegistrationInvites.Add(new RegistrationInvite
+ {
+ Id = Guid.NewGuid(),
+ Code = code,
+ Note = string.IsNullOrWhiteSpace(note) ? null : note.Trim(),
+ MaxUses = Math.Max(1, maxUses),
+ ExpiresAt = expiresAt,
+ CreatedBy = createdBy,
+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,
+ });
+ await context.SaveChangesAsync();
+
+ return FormatCode(code);
+ }
+
+ /// <summary>
+ /// Whether the code belongs to an invite that is not expired and has uses left.
+ /// </summary>
+ /// <param name="code">The code as entered by the user.</param>
+ /// <returns>True if the invite can be used.</returns>
+ public async Task<bool> IsValidAsync(string? code)
+ {
+ var normalized = TryNormalizeInput(code);
+ if (normalized is null)
+ {
+ return false;
+ }
+
+ var now = timeProvider.GetUtcNow().UtcDateTime;
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ return await context.RegistrationInvites.AnyAsync(x => x.Code == normalized && x.UseCount < x.MaxUses && (x.ExpiresAt == null || x.ExpiresAt > now));
+ }
+
+ /// <summary>
+ /// Atomically take one use of the invite.
+ /// </summary>
+ /// <param name="code">The code as entered by the user.</param>
+ /// <returns>The invite id when a use was taken, null when the invite is unknown, expired or used up.</returns>
+ public async Task<Guid?> TryConsumeAsync(string? code)
+ {
+ var normalized = TryNormalizeInput(code);
+ if (normalized is null)
+ {
+ return null;
+ }
+
+ var now = timeProvider.GetUtcNow().UtcDateTime;
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var invite = await context.RegistrationInvites.Where(x => x.Code == normalized).Select(x => new { x.Id }).FirstOrDefaultAsync();
+ if (invite is null)
+ {
+ return null;
+ }
+
+ // The conditional update makes two concurrent registrations unable to both take the last use.
+ var updated = await context.RegistrationInvites
+ .Where(x => x.Id == invite.Id && x.UseCount < x.MaxUses && (x.ExpiresAt == null || x.ExpiresAt > now))
+ .ExecuteUpdateAsync(s => s.SetProperty(x => x.UseCount, x => x.UseCount + 1).SetProperty(x => x.LastUsedAt, now));
+
+ return updated == 1 ? invite.Id : null;
+ }
+
+ /// <summary>
+ /// Give back a use taken by <see cref="TryConsumeAsync"/> when the registration did not complete.
+ /// </summary>
+ /// <param name="inviteId">The invite id.</param>
+ /// <returns>Task.</returns>
+ public async Task ReleaseAsync(Guid inviteId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ await context.RegistrationInvites.Where(x => x.Id == inviteId && x.UseCount > 0).ExecuteUpdateAsync(s => s.SetProperty(x => x.UseCount, x => x.UseCount - 1));
+ }
+
+ private static string? TryNormalizeInput(string? code)
+ {
+ if (string.IsNullOrWhiteSpace(code) || code.Length > MaxInputLength)
+ {
+ return null;
+ }
+
+ return NormalizeCode(code);
+ }
+
+ private static string GenerateCode()
+ {
+ var chars = new char[CodeLength];
+ for (var i = 0; i < CodeLength; i++)
+ {
+ chars[i] = CodeAlphabet[RandomNumberGenerator.GetInt32(CodeAlphabet.Length)];
+ }
+
+ return new string(chars);
+ }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
index cbcefcb87..7e54fe987 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
@@ -267,4 +267,9 @@ public enum ApiErrorCode
/// The supplied KEK derivation parameters are not within expected bounds.
/// </summary>
INVALID_ENCRYPTION_PARAMETERS,
+
+ /// <summary>
+ /// The registration invite code is unknown, expired or used up.
+ /// </summary>
+ INVITE_CODE_INVALID,
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs
index 71c65b833..d288a7234 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs
@@ -91,6 +91,11 @@ public class RegisterRequest
/// </summary>
public string? EncryptedAccountPrivateKey { get; }
+ /// <summary>
+ /// Gets the registration invite code, required when public registration is disabled.
+ /// </summary>
+ public string? InviteCode { get; init; }
+
/// <summary>
/// Gets a value indicating whether the client sent the complete account key hierarchy. A partial one is not usable.
/// </summary>
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateInviteCodeRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateInviteCodeRequest.cs
new file mode 100644
index 000000000..3296a3a50
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateInviteCodeRequest.cs
@@ -0,0 +1,19 @@
+//-----------------------------------------------------------------------
+// <copyright file="ValidateInviteCodeRequest.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Models.WebApi.V2.Auth;
+
+/// <summary>
+/// A request to check a registration invite code.
+/// </summary>
+public class ValidateInviteCodeRequest
+{
+ /// <summary>
+ /// Gets the invite code to check.
+ /// </summary>
+ public required string InviteCode { get; init; } = string.Empty;
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateUsernameRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateUsernameRequest.cs
index 0efa6eecd..d643ff641 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateUsernameRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateUsernameRequest.cs
@@ -16,4 +16,9 @@ public class ValidateUsernameRequest
/// Gets the username to validate.
/// </summary>
public required string Username { get; init; } = string.Empty;
+
+ /// <summary>
+ /// Gets the registration invite code, required when public registration is disabled.
+ /// </summary>
+ public string? InviteCode { get; init; }
}