House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
Build / Build (push) Successful in 30s

- Services, controllers and jobs take their dependencies through primary
  constructors and use them directly; where a method already named a local
  after a dependency, the dependency takes its type's name.
- Every async method takes a CancellationToken last and passes it down to
  MongoDB, HTTP and the job queue. The setup claim is still given back when
  a request is cancelled.
- The federation and media options are read through IOptionsMonitor.
- The Mastodon entities keep sending "" for empty strings, and every model
  field where null means something says so.
- The inbox's 503 with Retry-After, which other servers retry, is the one
  server error left, and says why.
- Arasaka.HouseRules.Analyzers checks all of this in every build, here and in
  PrivaPub.ClientModels as decePubClient builds it.

Checked against GoToSocial in the pasture: 64 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
This commit is contained in:
thepraandClaude Opus 5.5 committed 2026-11-10 01:24:43 +01:00
1 parent f0a14c737f
commit 0f73f69239
176 files changed
+2789 -3974

No files matched your search

+163 -184
View File
@@ -20,53 +20,32 @@ using System.Text.Json;
namespace PrivaPub.Services
{
public class RootUsersService : IRootUsersService
public class RootUsersService(
IJobQueue jobs,
IRootSessions sessions,
IRootRemoval removal,
IStringLocalizer<GenericRes> localizer,
ILogger<RootUsersService> logger,
IPasswordHasher passwordHasher,
DbEntities dbEntities,
AppConfigurationService appConfigurationService) : IRootUsersService
{
readonly DbEntities DbEntities;
readonly IPasswordHasher PasswordHasher;
readonly IStringLocalizer Localizer;
readonly ILogger<RootUsersService> Logger;
readonly AppConfigurationService AppConfigurationService;
readonly IJobQueue Jobs;
readonly IRootSessions Sessions;
readonly IRootRemoval Removal;
public RootUsersService(
IJobQueue jobs,
IRootSessions sessions,
IRootRemoval removal,
IStringLocalizer<GenericRes> localizer,
ILogger<RootUsersService> logger,
IPasswordHasher passwordHasher,
DbEntities dbEntities,
AppConfigurationService appConfigurationService)
{
Jobs = jobs;
Sessions = sessions;
Removal = removal;
DbEntities = dbEntities;
PasswordHasher = passwordHasher;
Localizer = localizer;
Logger = logger;
AppConfigurationService = appConfigurationService;
}
public const string NoMatch = "That username and password do not match.";
static string _decoy;
// a hash nobody's password matches, so an unknown login costs the same hashing as a wrong password
string Decoy => _decoy ??= PasswordHasher.Hash(Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)));
string Decoy => _decoy ??= passwordHasher.Hash(Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)));
public async Task<WebResult> SignUpAsync(LoginForm signUpForm)
public async Task<WebResult> SignUpAsync(LoginForm signUpForm, CancellationToken token = default)
{
var result = new WebResult();
try
{
signUpForm.UserName = signUpForm.UserName.ToLower();
if (await DbEntities.RootUsers.Match(u => u.UserName == signUpForm.UserName).ExecuteAnyAsync())
return result.Invalidate(Localizer["Username '{0}' already taken.", signUpForm.UserName]);
if (await dbEntities.RootUsers.Match(u => u.UserName == signUpForm.UserName).ExecuteAnyAsync(token))
return result.Invalidate(localizer["Username '{0}' already taken.", signUpForm.UserName]);
var signUpPasswordHashed = PasswordHasher.Hash(signUpForm.Password);
var signUpPasswordHashed = passwordHasher.Hash(signUpForm.Password);
var newUser = new RootUser
{
UserName = signUpForm.UserName,
@@ -74,7 +53,7 @@ namespace PrivaPub.Services
};
var cultureLanguage = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
var language = await DbEntities.Languages.Match(l => l.International2Code == cultureLanguage).ExecuteFirstAsync();
var language = await dbEntities.Languages.Match(l => l.International2Code == cultureLanguage).ExecuteFirstAsync(token);
newUser.Settings = new RootUserSettings
{
LanguageCode = language?.International2Code ?? "en",
@@ -86,7 +65,7 @@ namespace PrivaPub.Services
PreferSystemTheming = signUpForm.PreferSystemTheming,
ThemeIsDarkMode = signUpForm.ThemeIsDarkMode
};
await DB.Default.SaveAsync(newUser);
await DB.Default.SaveAsync(newUser, token);
result.Data = (newUser, ToViewSettings(newUser.Settings));
@@ -94,12 +73,12 @@ namespace PrivaPub.Services
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SignUpAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SignUpAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
public async Task<WebResult> LoginAsync(LoginForm loginForm)
public async Task<WebResult> LoginAsync(LoginForm loginForm, CancellationToken token = default)
{
var result = new WebResult();
try
@@ -107,33 +86,33 @@ namespace PrivaPub.Services
// One answer, after the same work, whether the login is unknown, deleted or the password wrong: sign-in must not
// tell anyone which logins exist. Only someone who knows the password learns the login is banned.
loginForm.UserName = loginForm.UserName.ToLower();
var user = await DbEntities.RootUsers.Match(u => u.UserName == loginForm.UserName && u.DeletedAt == null).ExecuteFirstAsync();
var (verified, needsUpgrade) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, loginForm.Password);
var user = await dbEntities.RootUsers.Match(u => u.UserName == loginForm.UserName && u.DeletedAt == null).ExecuteFirstAsync(token);
var (verified, needsUpgrade) = passwordHasher.Check(user?.HashedPassword ?? Decoy, loginForm.Password);
if (user?.HashedPassword == default || !verified)
return result.Invalidate(Localizer[NoMatch]);
return result.Invalidate(localizer[NoMatch]);
if (user.IsBanned)
return result.Invalidate(Localizer["User '{0}' banned.", user.UserName]);
return result.Invalidate(localizer["User '{0}' banned.", user.UserName]);
// only a correct password learns that two-factor is on: it is asked for with a 428
if (user.Totp?.EnabledAt != default)
{
if (string.IsNullOrWhiteSpace(loginForm.OneTimeCode))
return result.Invalidate(Localizer[TwoFactor.CodeNeeded], StatusCodes.Status428PreconditionRequired);
return result.Invalidate(localizer[TwoFactor.CodeNeeded], StatusCodes.Status428PreconditionRequired);
if (!await TwoFactor.Consume(user, loginForm.OneTimeCode, CancellationToken.None))
return result.Invalidate(Localizer[TwoFactor.CodeInvalid]);
return result.Invalidate(localizer[TwoFactor.CodeInvalid]);
}
// hashed again at today's iterations; matched on the old hash, so two sign-ins at once never undo each other
if (needsUpgrade)
{
var oldHash = user.HashedPassword;
user.HashedPassword = PasswordHasher.Hash(loginForm.Password);
user.HashedPassword = passwordHasher.Hash(loginForm.Password);
await DB.Default.Update<RootUser>()
.Match(u => u.ID == user.ID && u.HashedPassword == oldHash)
.Modify(u => u.HashedPassword, user.HashedPassword)
.ExecuteAsync();
.ExecuteAsync(token);
}
var userSettingsResult = await GetUserSettingsAsync(user.ID, loginForm);
var userSettingsResult = await GetUserSettingsAsync(user.ID, loginForm, token);
var userSettings = (ViewUserSettings)userSettingsResult.Data;
result.Data = (user, userSettings);
@@ -142,27 +121,27 @@ namespace PrivaPub.Services
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(LoginAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(LoginAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
public async Task<WebResult> UpdateUserSettingsAsync(ViewUserSettings userSettings, string userId)
public async Task<WebResult> UpdateUserSettingsAsync(ViewUserSettings userSettings, string userId, CancellationToken token = default)
{
var result = new WebResult();
try
{
var isSupportedLanguage = AppConfigurationService.AppConfiguration.SupportedLanguages.Contains(userSettings.LanguageCode);
var isSupportedLanguage = appConfigurationService.AppConfiguration.SupportedLanguages.Contains(userSettings.LanguageCode);
if (!isSupportedLanguage)
return result.Invalidate(Localizer["Language code '{0}' unsupported.", userSettings.LanguageCode]);
return result.Invalidate(localizer["Language code '{0}' unsupported.", userSettings.LanguageCode]);
var languageCodeExists = await DbEntities.Languages
.Match(l => l.International2Code == userSettings.LanguageCode).ExecuteAnyAsync();
var languageCodeExists = await dbEntities.Languages
.Match(l => l.International2Code == userSettings.LanguageCode).ExecuteAnyAsync(token);
if (!languageCodeExists)
return result.Invalidate(Localizer["Language code '{0}' doesn't exist.", userSettings.LanguageCode]);
return result.Invalidate(localizer["Language code '{0}' doesn't exist.", userSettings.LanguageCode]);
var language = await DbEntities.Languages.Match(l => l.International2Code == userSettings.LanguageCode)
.ExecuteFirstAsync();
var language = await dbEntities.Languages.Match(l => l.International2Code == userSettings.LanguageCode)
.ExecuteFirstAsync(token);
_ = await DB.Default.Update<RootUser>()
.MatchID(userId)
.Modify(u => u.Settings.LanguageCode, language.International2Code)
@@ -175,98 +154,98 @@ namespace PrivaPub.Services
.Modify(u => u.Settings.IconsThemeIndexColour, userSettings.IconsThemeIndexColour)
.Modify(u => u.Settings.SavedAt, DateTime.UtcNow)
.Modify(u => u.UpdatedAt, DateTime.UtcNow)
.ExecuteAsync();
.ExecuteAsync(token);
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserSettingsAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserSettingsAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
public async Task<WebResult> UpdateUserPasswordAsync(UserPasswordForm userPasswordForm, string userId)
public async Task<WebResult> UpdateUserPasswordAsync(UserPasswordForm userPasswordForm, string userId, CancellationToken token = default)
{
var result = new WebResult();
try
{
var user = await DbEntities.RootUsers.Match(u => u.ID == userId && u.DeletedAt == null).ExecuteFirstAsync();
var user = await dbEntities.RootUsers.Match(u => u.ID == userId && u.DeletedAt == null).ExecuteFirstAsync(token);
if (user == null)
return result.Invalidate(Localizer["Username '{0}' not found.", userId]);
return result.Invalidate(localizer["Username '{0}' not found.", userId]);
var (verified, needsUpgrade) = PasswordHasher.Check(user.HashedPassword, userPasswordForm.OldPassword);
var (verified, needsUpgrade) = passwordHasher.Check(user.HashedPassword, userPasswordForm.OldPassword);
if (!verified)
return result.Invalidate(Localizer["Wrong password."]);
return result.Invalidate(localizer["Wrong password."]);
await DB.Default.Update<RootUser>().MatchID(user.ID)
.Modify(u => u.HashedPassword, PasswordHasher.Hash(userPasswordForm.NewPassword))
.Modify(u => u.HashedPassword, passwordHasher.Hash(userPasswordForm.NewPassword))
.Modify(u => u.UpdatedAt, DateTime.UtcNow)
.ExecuteAsync();
.ExecuteAsync(token);
// whoever else is signed in may be why the password changed: every session ends, and the caller gets a new one
await Sessions.Revoke(user.ID, CancellationToken.None);
user = await DbEntities.RootUsers.MatchID(user.ID).ExecuteFirstAsync();
await sessions.Revoke(user.ID, CancellationToken.None);
user = await dbEntities.RootUsers.MatchID(user.ID).ExecuteFirstAsync(token);
result.Data = (user, ToViewSettings(user.Settings));
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserPasswordAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UpdateUserPasswordAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
public async Task<WebResult> RemoveUserAsync(UsersIds usersIds)
public async Task<WebResult> RemoveUserAsync(UsersIds usersIds, CancellationToken token = default)
{
var result = new WebResult();
try
{
var removed = 0;
foreach (var id in usersIds.UserIdList.Distinct())
if (await Removal.Remove(id, CancellationToken.None))
if (await removal.Remove(id, CancellationToken.None))
removed++;
if (removed == 0)
return result.Invalidate(Localizer["User already deleted."]);
return result.Invalidate(localizer["User already deleted."]);
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveUserAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveUserAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
// A root deletes itself only with its password, so a stolen session cannot.
public async Task<WebResult> RemoveSelfAsync(string rootId, string password)
public async Task<WebResult> RemoveSelfAsync(string rootId, string password, CancellationToken token = default)
{
var result = new WebResult();
try
{
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
if (user?.HashedPassword == default || !verified)
return result.Invalidate(Localizer[NoMatch], StatusCodes.Status403Forbidden);
await Removal.Remove(user.ID, CancellationToken.None);
return result.Invalidate(localizer[NoMatch], StatusCodes.Status403Forbidden);
await removal.Remove(user.ID, CancellationToken.None);
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveSelfAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveSelfAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
// what can't be undone asks for the password again (a persona's or a group's deletion, by its login or an administrator)
public async Task<bool> PasswordMatches(string rootId, string password)
public async Task<bool> PasswordMatches(string rootId, string password, CancellationToken token = default)
{
var user = string.IsNullOrEmpty(rootId) ? default : await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
var user = string.IsNullOrEmpty(rootId) ? default : await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
return user?.HashedPassword != default && verified;
}
public async Task<WebResult> BanUserAsync(UsersIds usersIds)
public async Task<WebResult> BanUserAsync(UsersIds usersIds, CancellationToken token = default)
{
var result = new WebResult();
try
@@ -274,18 +253,18 @@ namespace PrivaPub.Services
await DB.Default.Update<RootUser>()
.Match(u => usersIds.UserIdList.Contains(u.ID))
.Modify(u => u.IsBanned, true)
.ExecuteAsync();
.ExecuteAsync(token);
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(BanUserAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(BanUserAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
public async Task<WebResult> UnbanUserAsync(UsersIds usersIds)
public async Task<WebResult> UnbanUserAsync(UsersIds usersIds, CancellationToken token = default)
{
var result = new WebResult();
try
@@ -293,25 +272,25 @@ namespace PrivaPub.Services
await DB.Default.Update<RootUser>()
.Match(u => usersIds.UserIdList.Contains(u.ID))
.Modify(u => u.IsBanned, false)
.ExecuteAsync();
.ExecuteAsync(token);
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UnbanUserAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(UnbanUserAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
public async Task<WebResult> GetUserSettingsAsync(string userId, LoginForm loginForm = default)
public async Task<WebResult> GetUserSettingsAsync(string userId, LoginForm loginForm = default, CancellationToken token = default)
{
var result = new WebResult();
try
{
var user = await DbEntities.RootUsers.MatchID(userId).ExecuteFirstAsync();
var user = await dbEntities.RootUsers.MatchID(userId).ExecuteFirstAsync(token);
if (user == default)
return result.Invalidate(Localizer["User not found."], StatusCodes.Status404NotFound);
return result.Invalidate(localizer["User not found."], StatusCodes.Status404NotFound);
if (loginForm != default && loginForm.ThemeIsDarkMode != user.Settings.ThemeIsDarkMode)
{
@@ -319,7 +298,7 @@ namespace PrivaPub.Services
await DB.Default.Update<RootUser>()
.MatchID(userId)
.Modify(u => u.Settings.ThemeIsDarkMode, loginForm.ThemeIsDarkMode)
.ExecuteAsync();
.ExecuteAsync(token);
}
result.Data = ToViewSettings(user.Settings);
@@ -327,8 +306,8 @@ namespace PrivaPub.Services
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(GetUserSettingsAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(GetUserSettingsAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
@@ -336,72 +315,72 @@ namespace PrivaPub.Services
// The same answer, after the same work, whether the account exists, has an email or can be written to: recovery must
// not tell anyone which logins or addresses exist. RecoveryJob does the rest, out of the request.
public async Task<WebResult> SetupAndSendRecoveryEmail(PasswordRecoveryForm passwordRecoveryForm, string host)
public async Task<WebResult> SetupAndSendRecoveryEmail(PasswordRecoveryForm passwordRecoveryForm, string host, CancellationToken token = default)
{
var result = new WebResult();
try
{
var userName = passwordRecoveryForm.UserName?.ToLowerInvariant();
var user = passwordRecoveryForm.IsEmailDisabled
? await DbEntities.RootUsers.Match(u => u.UserName == userName && u.DeletedAt == null).ExecuteFirstAsync()
: await DbEntities.RootUsers.Match(u => u.Email == passwordRecoveryForm.Email && u.IsEmailValidated && u.DeletedAt == null).ExecuteFirstAsync();
await Jobs.Enqueue(JobKind.SendRecovery, JsonSerializer.Serialize(new RecoveryPayload(user?.ID, host)), RecoveryJob.Host,
? await dbEntities.RootUsers.Match(u => u.UserName == userName && u.DeletedAt == null).ExecuteFirstAsync(token)
: await dbEntities.RootUsers.Match(u => u.Email == passwordRecoveryForm.Email && u.IsEmailValidated && u.DeletedAt == null).ExecuteFirstAsync(token);
await jobs.Enqueue(JobKind.SendRecovery, JsonSerializer.Serialize(new RecoveryPayload(user?.ID, host)), RecoveryJob.Host,
dedupeKey: default, CancellationToken.None);
result.Data = Localizer[RecoverySent].Value;
result.Data = (string)localizer[RecoverySent];
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SetupAndSendRecoveryEmail)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(SetupAndSendRecoveryEmail)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
Task<EmailRecovery> LiveRecovery(string recoveryCode)
Task<EmailRecovery> LiveRecovery(string recoveryCode, CancellationToken token = default)
{
var hash = RecoveryJob.Hash(recoveryCode);
var now = DateTime.UtcNow;
return DbEntities.EmailRecoveries.Match(er => er.CodeHash == hash && er.ExpiresAt > now).ExecuteFirstAsync();
return dbEntities.EmailRecoveries.Match(er => er.CodeHash == hash && er.ExpiresAt > now).ExecuteFirstAsync(token);
}
public async Task<WebResult> IsValidRecoveryCode(string recoveryCode)
public async Task<WebResult> IsValidRecoveryCode(string recoveryCode, CancellationToken token = default)
{
var result = new WebResult();
try
{
result.Data = await LiveRecovery(recoveryCode) != default;
result.Data = await LiveRecovery(recoveryCode, token) != default;
return result;
}
catch (Exception ex)
{
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
// A recovered password ends every session the root had: whoever had them may be why it was recovered.
public async Task<WebResult> ChangePassword(NewPasswordForm newPasswordForm)
public async Task<WebResult> ChangePassword(NewPasswordForm newPasswordForm, CancellationToken token = default)
{
var result = new WebResult();
try
{
var recovery = await LiveRecovery(newPasswordForm.RecoveryCode);
var recovery = await LiveRecovery(newPasswordForm.RecoveryCode, token);
var user = recovery == default ? default
: await DbEntities.RootUsers.MatchID(recovery.RootUserId).Match(u => u.DeletedAt == null && !u.IsBanned).ExecuteFirstAsync();
: await dbEntities.RootUsers.MatchID(recovery.RootUserId).Match(u => u.DeletedAt == null && !u.IsBanned).ExecuteFirstAsync(token);
if (user == default)
return result.Invalidate(Localizer["Invalid recovery code."], StatusCodes.Status404NotFound);
return result.Invalidate(localizer["Invalid recovery code."], StatusCodes.Status404NotFound);
await DB.Default.Update<RootUser>().MatchID(user.ID)
.Modify(u => u.HashedPassword, PasswordHasher.Hash(newPasswordForm.NewPassword))
.Modify(u => u.HashedPassword, passwordHasher.Hash(newPasswordForm.NewPassword))
.Modify(u => u.UpdatedAt, DateTime.UtcNow)
.ExecuteAsync();
.ExecuteAsync(token);
await DB.Default.DeleteAsync<EmailRecovery>(er => er.RootUserId == user.ID);
await Sessions.Revoke(user.ID, CancellationToken.None);
await sessions.Revoke(user.ID, CancellationToken.None);
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(ChangePassword)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(ChangePassword)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
@@ -421,16 +400,16 @@ namespace PrivaPub.Services
public const string EmailCodeSent = "If that address can be used, a code is on its way to it. It works for one hour.";
public const string EmailCodeInvalid = "That code is not valid.";
public async Task<WebResult> AccountAsync(string rootId)
public async Task<WebResult> AccountAsync(string rootId, CancellationToken token = default)
{
var result = new WebResult();
try
{
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
if (user == default)
return result.Invalidate(Localizer["User not found."], StatusCodes.Status404NotFound);
return result.Invalidate(localizer["User not found."], StatusCodes.Status404NotFound);
var now = DateTime.UtcNow;
var pending = await DB.Default.Find<EmailVerification>().Match(v => v.RootUserId == rootId && v.ExpiresAt > now).ExecuteFirstAsync();
var pending = await DB.Default.Find<EmailVerification>().Match(v => v.RootUserId == rootId && v.ExpiresAt > now).ExecuteFirstAsync(token);
result.Data = new ViewAccount
{
UserName = user.UserName,
@@ -445,22 +424,22 @@ namespace PrivaPub.Services
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(AccountAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(AccountAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
// Only with the password, so a stolen session can't move recovery to its own inbox. The answer is the same sentence
// whether or not the address is free; EmailVerificationJob sends the code, or nothing when another login holds it.
public async Task<WebResult> RequestEmailChangeAsync(string rootId, EmailChangeForm form)
public async Task<WebResult> RequestEmailChangeAsync(string rootId, EmailChangeForm form, CancellationToken token = default)
{
var result = new WebResult();
try
{
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, form.Password ?? string.Empty);
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, form.Password ?? string.Empty);
if (user?.HashedPassword == default || !verified)
return result.Invalidate(Localizer["Wrong password."], StatusCodes.Status403Forbidden);
return result.Invalidate(localizer["Wrong password."], StatusCodes.Status403Forbidden);
await DB.Default.DeleteAsync<EmailVerification>(v => v.RootUserId == user.ID);
var pending = new EmailVerification
@@ -469,94 +448,94 @@ namespace PrivaPub.Services
Email = form.Email.Trim().ToLowerInvariant(),
ExpiresAt = DateTime.UtcNow + EmailVerification.Lifetime
};
await DB.Default.SaveAsync(pending);
await Jobs.Enqueue(JobKind.SendEmailVerification, JsonSerializer.Serialize(new EmailVerificationPayload(pending.ID)),
await DB.Default.SaveAsync(pending, token);
await jobs.Enqueue(JobKind.SendEmailVerification, JsonSerializer.Serialize(new EmailVerificationPayload(pending.ID)),
EmailVerificationJob.Host, dedupeKey: default, CancellationToken.None);
result.Data = Localizer[EmailCodeSent].Value;
result.Data = (string)localizer[EmailCodeSent];
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RequestEmailChangeAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RequestEmailChangeAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
// One answer for every failure (wrong, expired, five tries spent, or the address verified by another login meanwhile)
public async Task<WebResult> VerifyEmailAsync(string rootId, string code)
public async Task<WebResult> VerifyEmailAsync(string rootId, string code, CancellationToken token = default)
{
var result = new WebResult();
try
{
var now = DateTime.UtcNow;
var pending = await DB.Default.Find<EmailVerification>().Match(v => v.RootUserId == rootId && v.ExpiresAt > now).ExecuteFirstAsync();
var pending = await DB.Default.Find<EmailVerification>().Match(v => v.RootUserId == rootId && v.ExpiresAt > now).ExecuteFirstAsync(token);
if (pending == default || string.IsNullOrEmpty(pending.CodeHash))
return result.Invalidate(Localizer[EmailCodeInvalid]);
return result.Invalidate(localizer[EmailCodeInvalid]);
if (pending.CodeHash != RecoveryJob.Hash(code?.Trim()))
{
if (pending.Attempts + 1 >= EmailVerification.MaxAttempts)
await DB.Default.DeleteAsync<EmailVerification>(pending.ID);
else
await DB.Default.Update<EmailVerification>().MatchID(pending.ID).Modify(b => b.Inc(v => v.Attempts, 1)).ExecuteAsync();
return result.Invalidate(Localizer[EmailCodeInvalid]);
await DB.Default.Update<EmailVerification>().MatchID(pending.ID).Modify(b => b.Inc(v => v.Attempts, 1)).ExecuteAsync(token);
return result.Invalidate(localizer[EmailCodeInvalid]);
}
await DB.Default.DeleteAsync<EmailVerification>(pending.ID);
if (await DbEntities.RootUsers.Match(u => u.Email == pending.Email && u.IsEmailValidated && u.ID != rootId && u.DeletedAt == null).ExecuteAnyAsync())
return result.Invalidate(Localizer[EmailCodeInvalid]);
if (await dbEntities.RootUsers.Match(u => u.Email == pending.Email && u.IsEmailValidated && u.ID != rootId && u.DeletedAt == null).ExecuteAnyAsync(token))
return result.Invalidate(localizer[EmailCodeInvalid]);
await DB.Default.Update<RootUser>().MatchID(rootId)
.Modify(u => u.Email, pending.Email)
.Modify(u => u.IsEmailValidated, true)
.Modify(u => u.UpdatedAt, now)
.ExecuteAsync();
return await AccountAsync(rootId);
.ExecuteAsync(token);
return await AccountAsync(rootId, token);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(VerifyEmailAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(VerifyEmailAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
// Two-factor sign-in (TwoFactor): set up with the password, turned on by the app's first code (which also proves the
// app holds the secret), turned off with the password and a code. Turning it on ends every other session.
public async Task<WebResult> TotpSetupAsync(string rootId, string password)
public async Task<WebResult> TotpSetupAsync(string rootId, string password, CancellationToken token = default)
{
var result = new WebResult();
try
{
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
if (user?.HashedPassword == default || !verified)
return result.Invalidate(Localizer["Wrong password."], StatusCodes.Status403Forbidden);
return result.Invalidate(localizer["Wrong password."], StatusCodes.Status403Forbidden);
if (user.Totp?.EnabledAt != default)
return result.Invalidate(Localizer["Two-factor sign-in is on already: turn it off first."], StatusCodes.Status409Conflict);
return result.Invalidate(localizer["Two-factor sign-in is on already: turn it off first."], StatusCodes.Status409Conflict);
var secret = TwoFactor.NewSecret();
await DB.Default.Update<RootUser>().MatchID(rootId)
.Modify(u => u.Totp, new RootTotp { PendingSecret = secret, PendingSince = DateTime.UtcNow })
.ExecuteAsync();
.ExecuteAsync(token);
var uri = TwoFactor.OtpAuthUri(secret, user.UserName);
result.Data = new ViewTotpSetup { Secret = secret, OtpAuthUri = uri, QrDataUri = TwoFactor.QrDataUri(uri) };
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpSetupAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpSetupAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
public async Task<WebResult> TotpEnableAsync(string rootId, string code)
public async Task<WebResult> TotpEnableAsync(string rootId, string code, CancellationToken token = default)
{
var result = new WebResult();
try
{
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
if (user?.Totp is not { EnabledAt: null, PendingSecret: not null } pending || pending.PendingSince < DateTime.UtcNow.AddHours(-1))
return result.Invalidate(Localizer["Set up two-factor sign-in again: that setup expired."], StatusCodes.Status409Conflict);
return result.Invalidate(localizer["Set up two-factor sign-in again: that setup expired."], StatusCodes.Status409Conflict);
if (TwoFactor.Step(pending.PendingSecret, code) is not { } step)
return result.Invalidate(Localizer[TwoFactor.CodeInvalid]);
return result.Invalidate(localizer[TwoFactor.CodeInvalid]);
var codes = TwoFactor.NewRecoveryCodes();
await DB.Default.Update<RootUser>().MatchID(rootId)
@@ -567,66 +546,66 @@ namespace PrivaPub.Services
LastStep = step,
RecoveryCodeHashes = codes.Select(TwoFactor.HashRecovery).ToList()
})
.ExecuteAsync();
await Sessions.Revoke(rootId, CancellationToken.None);
user = await DbEntities.RootUsers.MatchID(rootId).ExecuteFirstAsync();
.ExecuteAsync(token);
await sessions.Revoke(rootId, CancellationToken.None);
user = await dbEntities.RootUsers.MatchID(rootId).ExecuteFirstAsync(token);
result.Data = (user, ToViewSettings(user.Settings), codes);
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpEnableAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpEnableAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
public async Task<WebResult> TotpDisableAsync(string rootId, string password, string code)
public async Task<WebResult> TotpDisableAsync(string rootId, string password, string code, CancellationToken token = default)
{
var result = new WebResult();
try
{
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
if (user?.HashedPassword == default || !verified)
return result.Invalidate(Localizer["Wrong password."], StatusCodes.Status403Forbidden);
return result.Invalidate(localizer["Wrong password."], StatusCodes.Status403Forbidden);
if (user.Totp?.EnabledAt == default)
return await AccountAsync(rootId);
return await AccountAsync(rootId, token);
if (!await TwoFactor.Consume(user, code, CancellationToken.None))
return result.Invalidate(Localizer[TwoFactor.CodeInvalid]);
return result.Invalidate(localizer[TwoFactor.CodeInvalid]);
await DB.Default.Update<RootUser>().MatchID(rootId).Modify(u => u.Totp, null).ExecuteAsync();
return await AccountAsync(rootId);
await DB.Default.Update<RootUser>().MatchID(rootId).Modify(u => u.Totp, null).ExecuteAsync(token);
return await AccountAsync(rootId, token);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpDisableAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(TotpDisableAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
public async Task<WebResult> RemoveEmailAsync(string rootId, string password)
public async Task<WebResult> RemoveEmailAsync(string rootId, string password, CancellationToken token = default)
{
var result = new WebResult();
try
{
var user = await DbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync();
var (verified, _) = PasswordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
var user = await dbEntities.RootUsers.MatchID(rootId).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
var (verified, _) = passwordHasher.Check(user?.HashedPassword ?? Decoy, password ?? string.Empty);
if (user?.HashedPassword == default || !verified)
return result.Invalidate(Localizer["Wrong password."], StatusCodes.Status403Forbidden);
return result.Invalidate(localizer["Wrong password."], StatusCodes.Status403Forbidden);
await DB.Default.Update<RootUser>().MatchID(rootId)
.Modify(u => u.Email, null)
.Modify(u => u.IsEmailValidated, false)
.Modify(u => u.UpdatedAt, DateTime.UtcNow)
.ExecuteAsync();
.ExecuteAsync(token);
await DB.Default.DeleteAsync<EmailVerification>(v => v.RootUserId == rootId);
await DB.Default.DeleteAsync<EmailRecovery>(r => r.RootUserId == rootId);
return await AccountAsync(rootId);
return await AccountAsync(rootId, token);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveEmailAsync)}()");
return result.Invalidate(Localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(RootUsersService)}.{nameof(RemoveEmailAsync)}()");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
}