Path: redb-identity/src/redb.Identity.Core/EmailVerification/RedbEmailVerificationTokenStore.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Core/EmailVerification/RedbEmailVerificationTokenStore.cs ---- using System; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; namespace redb.Identity.Core.EmailVerification; /// /// N-4 (Session C, sub-step N4-6): redb-backed /// . Direct mirror of /// RedbPasswordResetTokenStore with one extra field on the persisted props /// () and one extra field on the verify /// result so the caller can guard against the double-change race. /// public sealed class RedbEmailVerificationTokenStore : IEmailVerificationTokenStore { private readonly IServiceScopeFactory _scopeFactory; private readonly RecoveryCodePepperProvider _pepperProvider; private readonly ILogger _logger; private readonly TimeProvider _timeProvider; public RedbEmailVerificationTokenStore( IServiceScopeFactory scopeFactory, RecoveryCodePepperProvider pepperProvider, ILogger logger, TimeProvider? timeProvider = null) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _pepperProvider = pepperProvider ?? throw new ArgumentNullException(nameof(pepperProvider)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _timeProvider = timeProvider ?? TimeProvider.System; } /// public async Task IssueAsync( long userId, string email, string callerVerifyUrl, TimeSpan ttl, CancellationToken ct = default) { if (userId <= 0) throw new ArgumentOutOfRangeException(nameof(userId)); if (string.IsNullOrWhiteSpace(email)) throw new ArgumentException("email is required", nameof(email)); if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl)); var jti = Guid.NewGuid(); var token = GenerateToken(); var now = _timeProvider.GetUtcNow(); var expires = now + ttl; var hash = RecoveryCodePepperProvider.PepperedSha256Hex(_pepperProvider.Pepper, token); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var obj = new RedbObject(new EmailVerificationTokenProps { Jti = jti.ToString("N"), UserId = userId, Email = email.Trim().ToLowerInvariant(), TokenHash = hash, PepperId = _pepperProvider.PepperId, IssuedAt = now, ExpiresAt = expires, Consumed = false, Attempts = 0, CallerVerifyUrl = callerVerifyUrl ?? string.Empty, }); obj.name = jti.ToString("N"); await redb.SaveAsync(obj).ConfigureAwait(false); return new EmailVerificationIssueResult(jti, token, expires); } /// public async Task VerifyAndConsumeAsync( Guid jti, string token, CancellationToken ct = default) { if (jti == Guid.Empty) return new EmailVerificationVerifyResult(false, 0, string.Empty, "not_found"); if (string.IsNullOrEmpty(token)) return new EmailVerificationVerifyResult(false, 0, string.Empty, "bad_token"); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var key = jti.ToString("N"); await using var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false); var row = await redb.Query() .Where(o => o.Jti == key) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) { await tx.RollbackAsync().ConfigureAwait(false); return new EmailVerificationVerifyResult(false, 0, string.Empty, "not_found"); } if (row.key.HasValue) await redb.LockForUpdateAsync(row.key.Value).ConfigureAwait(false); var p = row.Props; var now = _timeProvider.GetUtcNow(); if (p.Consumed) { await tx.CommitAsync().ConfigureAwait(false); return new EmailVerificationVerifyResult(false, 0, string.Empty, "already_consumed"); } if (p.ExpiresAt < now) { await tx.CommitAsync().ConfigureAwait(false); return new EmailVerificationVerifyResult(false, 0, string.Empty, "expired"); } if (_pepperProvider.PeppersFor(p.PepperId).Count == 0) _logger.LogWarning("The token was hashed with pepper {PepperId}, which is no longer configured.", p.PepperId); var ok = _pepperProvider.MatchesTokenHash(token.Trim(), p.TokenHash, p.PepperId); p.Attempts++; if (ok) { p.Consumed = true; } try { await redb.SaveAsync(row).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } catch { await tx.RollbackAsync().ConfigureAwait(false); throw; } return ok ? new EmailVerificationVerifyResult(true, p.UserId, p.Email, "ok") : new EmailVerificationVerifyResult(false, 0, string.Empty, "bad_token"); } private static string GenerateToken() { Span buf = stackalloc byte[32]; RandomNumberGenerator.Fill(buf); return Base64UrlEncode(buf); } private static string Base64UrlEncode(ReadOnlySpan bytes) { var s = Convert.ToBase64String(bytes); return s.TrimEnd('=').Replace('+', '-').Replace('/', '_'); } }