Files
SocialPub/PrivaPub/Services/EmailVerificationJob.cs
T
thepraandClaude Opus 5.5 0f73f69239
Build / Build (push) Successful in 30s
House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
- 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
2026-11-10 01:24:43 +01:00

68 lines
2.8 KiB
C#

using Microsoft.Extensions.Localization;
using MongoDB.Entities;
using PrivaPub.Infrastructure.Jobs;
using PrivaPub.Models.Jobs;
using PrivaPub.Models.User;
using PrivaPub.Resources;
using System.Security.Cryptography;
using System.Text.Json;
namespace PrivaPub.Services
{
public sealed record EmailVerificationPayload(string VerificationId);
// Sends the code that proves a login owns the address it asked for. The code exists only in the email; the row keeps its
// hash. An address another login has verified meanwhile gets nothing, so the answer to the request never told whether
// the address was taken, and no stranger's inbox receives a code it didn't ask for twice.
public class EmailVerificationJob(
IMailer mailer,
IStringLocalizer<GenericRes> localizer,
ILogger<EmailVerificationJob> logger) : IJobHandler
{
public const string Host = "email";
public JobKind Kind => JobKind.SendEmailVerification;
public int Concurrency => 1;
public int MaxAttempts => 3;
public int PerHostLimit => 1;
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0011", Justification = "A six-digit code with its leading zeros, not a number shown to a reader.")]
public static string NewCode() => RandomNumberGenerator.GetInt32(0, 1_000_000).ToString("D6");
public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{
var payload = JsonSerializer.Deserialize<EmailVerificationPayload>(job.Payload);
var now = DateTime.UtcNow;
var pending = string.IsNullOrEmpty(payload?.VerificationId) ? default
: await DB.Default.Find<EmailVerification>().Match(v => v.ID == payload.VerificationId && v.ExpiresAt > now).ExecuteFirstAsync(token);
if (pending == default)
return JobOutcome.Done;
var user = await DB.Default.Find<RootUser>().MatchID(pending.RootUserId).ExecuteFirstAsync(token);
if (user is not { DeletedAt: null, IsBanned: false })
return JobOutcome.Done;
if (await DB.Default.Find<RootUser>().Match(u => u.Email == pending.Email && u.IsEmailValidated && u.ID != user.ID && u.DeletedAt == null).ExecuteAnyAsync(token))
return JobOutcome.Done;
var code = NewCode();
await DB.Default.Update<EmailVerification>().MatchID(pending.ID).Modify(v => v.CodeHash, RecoveryJob.Hash(code)).ExecuteAsync(token);
try
{
await mailer.Send(pending.Email, localizer["PrivaPub - Confirm your email address"],
string.Format(localizer[
"Hello,\n\nThe PrivaPub login {0} asked to use this address. If it was you, enter this code within an hour:\n\n{1}\n\nIf it was not you, ignore this email: the address is not used."],
user.UserName, code), token);
return JobOutcome.Done;
}
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
{
logger.LogWarning(ex, "The verification email could not be sent");
return JobOutcome.Retry("smtp");
}
}
}
}