Bundle: redb-identity / src/redb.Identity.Core (src.redb.Identity.Core.2.txt), 44 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-identity/_index.txt ==== Path: redb-identity/src/redb.Identity.Core/Services/InMemoryFederationStateNonceStore.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/Services/InMemoryFederationStateNonceStore.cs ---- using System.Collections.Concurrent; namespace redb.Identity.Core.Services; /// /// Single-process implementation of . /// Records consumed jti values with their absolute expiry and prunes /// expired entries on each write. Suitable for single-instance Identity hosts; /// use for multi-node clusters. /// public sealed class InMemoryFederationStateNonceStore : IFederationStateNonceStore { private readonly TimeProvider _timeProvider; private readonly ConcurrentDictionary _seen = new(StringComparer.Ordinal); public InMemoryFederationStateNonceStore(TimeProvider? timeProvider = null) { _timeProvider = timeProvider ?? TimeProvider.System; } public Task TryConsumeAsync(string jti, TimeSpan ttl, CancellationToken ct = default) { if (string.IsNullOrEmpty(jti)) return Task.FromResult(false); var nowTicks = _timeProvider.GetUtcNow().UtcTicks; var expiryTicks = nowTicks + Math.Max(ttl.Ticks, TimeSpan.TicksPerSecond); // Opportunistic GC — small + bounded; runs every consume. Prune(nowTicks); var added = _seen.TryAdd(jti, expiryTicks); if (added) return Task.FromResult(true); // Already seen — only allow re-add if previous entry has expired. if (_seen.TryGetValue(jti, out var existing) && existing <= nowTicks) { if (_seen.TryUpdate(jti, expiryTicks, existing)) return Task.FromResult(true); } return Task.FromResult(false); } private void Prune(long nowTicks) { foreach (var kv in _seen) { if (kv.Value <= nowTicks) _seen.TryRemove(kv.Key, out _); } } } Path: redb-identity/src/redb.Identity.Core/Services/InMemoryRateLimitStore.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/Services/InMemoryRateLimitStore.cs ---- using System.Collections.Concurrent; namespace redb.Identity.Core.Services; /// /// C1 — Per-node sliding-window counter using /// and a per-key lock around a of hit timestamps. /// /// /// /// Default backend for . Counters live in process memory and /// reset on restart. In a multi-node cluster the effective ceiling is N × limit; /// this is acceptable for online brute-force defence (each node still slows attackers and /// correlates per-IP). For a true global limit, switch /// to "redis". /// /// /// Memory bounded by unique-keys × limit × 16 bytes. A background sweep removes /// buckets that have been empty for at least 2 × longestWindow (hard-coded 1 hour /// upper bound) so unbounded distinct-IP traffic eventually gets reaped. /// /// internal sealed class InMemoryRateLimitStore : IRateLimitStore, IDisposable { private readonly ConcurrentDictionary _buckets = new(); private readonly TimeProvider _timeProvider; private readonly Timer? _gcTimer; private static readonly TimeSpan GcInterval = TimeSpan.FromMinutes(5); private static readonly TimeSpan StaleAfter = TimeSpan.FromHours(1); public InMemoryRateLimitStore() : this(TimeProvider.System) { } public InMemoryRateLimitStore(TimeProvider timeProvider) { _timeProvider = timeProvider; // The background sweep is only useful with the real wall-clock; under a test / // fake time provider it would never tick and would also leak Timer instances // across many test fixtures. Tests can call PurgeStale() directly. if (!ReferenceEquals(timeProvider, TimeProvider.System)) { _gcTimer = null; return; } _gcTimer = new Timer(_ => PurgeStale(), null, GcInterval, GcInterval); } public Task TryIncrementAsync(string key, int limit, TimeSpan window, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); var state = _buckets.GetOrAdd(key, _ => new BucketState()); var nowTicks = _timeProvider.GetUtcNow().UtcTicks; var windowStartTicks = nowTicks - window.Ticks; lock (state.SyncRoot) { // Drop hits older than the window. while (state.Hits.Count > 0 && state.Hits.Peek() < windowStartTicks) state.Hits.Dequeue(); if (state.Hits.Count >= limit) { var oldest = state.Hits.Peek(); var retryAfterTicks = window.Ticks - (nowTicks - oldest); if (retryAfterTicks < TimeSpan.TicksPerSecond) retryAfterTicks = TimeSpan.TicksPerSecond; state.LastTouchedTicks = nowTicks; return Task.FromResult(new RateLimitDecision(false, state.Hits.Count, TimeSpan.FromTicks(retryAfterTicks))); } state.Hits.Enqueue(nowTicks); state.LastTouchedTicks = nowTicks; return Task.FromResult(new RateLimitDecision(true, state.Hits.Count, TimeSpan.Zero)); } } public Task ResetAsync(string key, CancellationToken ct = default) { if (_buckets.TryGetValue(key, out var state)) { lock (state.SyncRoot) { state.Hits.Clear(); state.LastTouchedTicks = _timeProvider.GetUtcNow().UtcTicks; } } return Task.CompletedTask; } /// Removes buckets untouched for . Exposed for tests. internal void PurgeStale() { var thresholdTicks = _timeProvider.GetUtcNow().UtcTicks - StaleAfter.Ticks; foreach (var (key, state) in _buckets) { lock (state.SyncRoot) { if (state.LastTouchedTicks < thresholdTicks && state.Hits.Count == 0) _buckets.TryRemove(key, out _); } } } public void Dispose() => _gcTimer?.Dispose(); private sealed class BucketState { public readonly object SyncRoot = new(); public readonly Queue Hits = new(); public long LastTouchedTicks; } } Path: redb-identity/src/redb.Identity.Core/Services/InlineEmailTemplateRegistry.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/Services/InlineEmailTemplateRegistry.cs ---- using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace redb.Identity.Core.Services; /// /// N-4 (Session C): default shipping inline /// English copy for the identity-system transactional e-mails. Variable /// substitution uses a simple {name} placeholder syntax — no Razor / Mustache /// engine is dragged in. Any requested locale falls back to the English template. /// Hosts that need localized or richer rendering replace this registry by /// registering their own singleton before /// AddRedbIdentityServer. /// public sealed class InlineEmailTemplateRegistry : IEmailTemplateRegistry { public ValueTask RenderAsync( string templateId, string? locale, IReadOnlyDictionary vars, CancellationToken ct = default) { if (string.IsNullOrEmpty(templateId)) throw new ArgumentException("templateId is required", nameof(templateId)); var key = (templateId, NormalizeLocale(locale)); if (!_templates.TryGetValue(key, out var template) && !_templates.TryGetValue((templateId, "en"), out template)) { throw new KeyNotFoundException( $"No e-mail template registered for templateId='{templateId}' (also tried fallback locale 'en')."); } return new ValueTask(new RenderedEmailTemplate { Subject = Substitute(template.Subject, vars), HtmlBody = Substitute(template.HtmlBody, vars), TextBody = template.TextBody is null ? null : Substitute(template.TextBody, vars), }); } private static string NormalizeLocale(string? locale) { if (string.IsNullOrWhiteSpace(locale)) return "en"; // Match "ru", "ru-RU", "RU" → "ru"; "en", "en-US" → "en". var dash = locale.IndexOf('-'); var lang = (dash > 0 ? locale[..dash] : locale).ToLowerInvariant(); return lang switch { "ru" => "ru", _ => "en", }; } private static string Substitute(string template, IReadOnlyDictionary vars) { // Simple {name} replacement — no recursion, no formatting. Sufficient for the // transactional e-mails we currently produce. if (vars.Count == 0 || template.IndexOf('{') < 0) return template; var sb = new StringBuilder(template.Length + 64); var i = 0; while (i < template.Length) { var open = template.IndexOf('{', i); if (open < 0) { sb.Append(template, i, template.Length - i); break; } var close = template.IndexOf('}', open + 1); if (close < 0) { sb.Append(template, i, template.Length - i); break; } sb.Append(template, i, open - i); var key = template.Substring(open + 1, close - open - 1); if (vars.TryGetValue(key, out var value)) sb.Append(value); else sb.Append(template, open, close - open + 1); i = close + 1; } return sb.ToString(); } private sealed record Template(string Subject, string HtmlBody, string? TextBody); private static readonly Dictionary<(string templateId, string locale), Template> _templates = new() { // ── password-reset / en ── [(IdentityEmailTemplates.PasswordReset, "en")] = new( Subject: "Reset your password", HtmlBody: "" + "

Hello {userName},

" + "

We received a request to reset the password for your account. " + "Click the link below to set a new password — it expires in {ttlMinutes} minutes " + "and can be used only once.

" + "

Reset password

" + "

If the button does not work, copy this link into your browser:
" + "{resetLink}

" + "

If you did not request a password reset you can safely ignore this e-mail — " + "your password will remain unchanged.

" + "

redb.Identity

" + "", TextBody: "Hello {userName},\r\n\r\n" + "We received a request to reset the password for your account. " + "Open the following link to set a new password (expires in {ttlMinutes} minutes, single-use):\r\n\r\n" + "{resetLink}\r\n\r\n" + "If you did not request a password reset you can safely ignore this e-mail.\r\n\r\n" + "— redb.Identity"), // ── email-verification / en ── [(IdentityEmailTemplates.EmailVerification, "en")] = new( Subject: "Verify your e-mail address", HtmlBody: "" + "

Hello {userName},

" + "

Please confirm that this is your e-mail address by clicking the button below. " + "The link expires in {ttlHours} hours and can be used only once.

" + "

Verify e-mail

" + "

If the button does not work, copy this link into your browser:
" + "{verifyLink}

" + "

If you did not register or change your e-mail you can safely ignore this message.

" + "

redb.Identity

" + "", TextBody: "Hello {userName},\r\n\r\n" + "Please confirm your e-mail address by opening the following link " + "(expires in {ttlHours} hours, single-use):\r\n\r\n" + "{verifyLink}\r\n\r\n" + "If you did not register or change your e-mail you can safely ignore this message.\r\n\r\n" + "— redb.Identity"), // ── change-email / en ── (N4-7: confirmation delivered to the NEW address) [(IdentityEmailTemplates.ChangeEmail, "en")] = new( Subject: "Confirm your new e-mail address", HtmlBody: "" + "

Hello {userName},

" + "

We received a request to switch the e-mail address on your account from " + "{oldEmail} to {newEmail}. " + "Click the button below to confirm the change. The link expires in {ttlHours} hours and can be used only once.

" + "

Confirm new e-mail

" + "

If the button does not work, copy this link into your browser:
" + "{confirmLink}

" + "

If you did not request this change you can safely ignore this message \u2014 your account e-mail will not be changed.

" + "

redb.Identity

" + "", TextBody: "Hello {userName},\r\n\r\n" + "We received a request to switch the e-mail address on your account " + "from {oldEmail} to {newEmail}. Open the link below to confirm " + "(expires in {ttlHours} hours, single-use):\r\n\r\n" + "{confirmLink}\r\n\r\n" + "If you did not request this change you can safely ignore this message.\r\n\r\n" + "— redb.Identity"), // ── mfa-code / en ── (the one-time code of e-mail MFA: enrollment and sign-in) [(IdentityEmailTemplates.MfaCode, "en")] = new( Subject: "Your verification code", HtmlBody: "" + "

Your verification code is:

" + "

{code}

" + "

It expires in {ttlMinutes} minutes and can be used only once.

" + "

If you did not ask for a code you can ignore this message.

" + "

redb.Identity

" + "", TextBody: "Your verification code is: {code}\r\n\r\n" + "It expires in {ttlMinutes} minutes and can be used only once.\r\n\r\n" + "If you did not ask for a code you can ignore this message.\r\n\r\n" + "— redb.Identity"), }; } Path: redb-identity/src/redb.Identity.Core/Services/LoginService.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/Services/LoginService.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Users; using redb.Core.Query; using redb.Core.Security; using redb.Identity.Core.Metrics; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Verifies user credentials via external providers (if any) then falls back /// to the local _users table. Single orchestration point for all /// authentication: Login page, ROPC grant, Device code verification. /// public sealed class LoginService { private readonly IRedbService _redb; private readonly ILogger _logger; private readonly ILogger _securityLogger; private readonly IExternalUserProvider[] _externalProviders; private readonly MfaService? _mfaService; private readonly TimeProvider _timeProvider; private readonly IPasswordHasher? _passwordHasher; private readonly IdentityMetrics? _metrics; private readonly IServiceScopeFactory? _scopeFactory; private readonly Configuration.PasswordPolicyOptions? _passwordPolicy; public LoginService( IRedbService redb, ILogger logger, IEnumerable? externalProviders = null, MfaService? mfaService = null, TimeProvider? timeProvider = null, ILoggerFactory? loggerFactory = null, IPasswordHasher? passwordHasher = null, IdentityMetrics? metrics = null, IServiceScopeFactory? scopeFactory = null, Configuration.PasswordPolicyOptions? passwordPolicy = null) { _redb = redb; _logger = logger; _scopeFactory = scopeFactory; _externalProviders = (externalProviders ?? []) .OrderBy(p => p.Priority) .ToArray(); _mfaService = mfaService; _timeProvider = timeProvider ?? TimeProvider.System; _passwordHasher = passwordHasher; _metrics = metrics; _passwordPolicy = passwordPolicy; // E5: route audit-class signals (denied logins, per-provider deny) to the // RedbIdentity.Security channel so SIEM/audit sinks can subscribe without // also ingesting routine operational logs. Fall back to the regular logger // when no factory is available (tests / non-DI construction). _securityLogger = loggerFactory is not null ? Security.IdentitySecurityLog.CreateLogger(loggerFactory) : logger; } /// /// Validates username/password and returns the user on success. /// Tries external providers in priority order, then falls back to local. /// public async Task AuthenticateAsync( string username, string password, CancellationToken ct = default) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return LoginResult.Failed("Username and password are required."); // Phase 1: Try external providers in priority order foreach (var provider in _externalProviders) { ExternalAuthResult? extResult; try { extResult = await provider.AuthenticateAsync(username, password, ct).ConfigureAwait(false); } catch (Exception ex) { _logger.LogWarning(ex, "External provider '{Provider}' threw for user '{Username}', skipping", provider.ProviderName, username); continue; } if (extResult is null) continue; // provider doesn't handle this user if (!extResult.Succeeded) { // Provider recognized the user but auth failed — do NOT fall through _securityLogger.LogWarning("Login denied by '{Provider}' for user '{Username}': {Error}", provider.ProviderName, username, extResult.ErrorMessage); return LoginResult.Failed(extResult.ErrorMessage ?? "Authentication failed."); } _logger.LogDebug("User '{Username}' authenticated via external provider '{Provider}'", username, provider.ProviderName); return await ResolveExternalUser(provider.ProviderName, extResult, username) .ConfigureAwait(false); } // Phase 2: Fall back to local _users password check return await AuthenticateLocal(username, password).ConfigureAwait(false); } private async Task AuthenticateLocal(string username, string password) { // C12 / F3: measure verify duration across both success and failure branches — // ValidateUserAsync wraps the BCrypt/Argon2id verify plus SELECT latency. The // histogram bucket discriminates `result` success/fail for OTEL tagging. var sw = System.Diagnostics.Stopwatch.StartNew(); var coreUser = await _redb.UserProvider.ValidateUserAsync(username, password) .ConfigureAwait(false); sw.Stop(); _metrics?.PasswordVerifyDuration.Record( sw.Elapsed.TotalMilliseconds, new KeyValuePair("result", coreUser is null ? "fail" : "success")); if (coreUser is null) { // C14 / SEC-A20: timing-equivalence. ValidateUserAsync returns null for // (a) user not found, (b) user disabled, (c) wrong password — but only the // last path actually invokes the BCrypt verify (~100 ms). The first two paths // return early, leaking via timing whether a username exists. Run a fake // BCrypt verify so the wall-clock cost of all three negative branches is // approximately equivalent. The fake hash is precomputed and the result is // intentionally discarded. try { _ = BCrypt.Net.BCrypt.Verify(password ?? "", FakeBcryptHash); } catch { } _securityLogger.LogWarning("Login denied: user '{Username}' — invalid credentials or not found", username); return LoginResult.Failed("Invalid credentials."); } // C12: upgrade-on-login. If the stored hash is in a legacy format (BCrypt, // SHA256+salt) or uses weaker Argon2id parameters than the current configuration, // re-hash the plaintext and persist. Fire-and-forget — a rehash failure must not // block login (the user is already authenticated). if (_passwordHasher is not null && !string.IsNullOrEmpty(coreUser.Password) && NeedsRehash(_passwordHasher, coreUser.Password)) { // AWAITED, deliberately — this used to be Task.Run and that was the bug. A detached // rehash lands about a second after the login that scheduled it (the hash itself costs // ~250 ms before anything reaches the database), and an admin password reset fits into // that window comfortably. When the rehash landed last it put the pre-login password // back over the freshly set one: the account silently reverted to exactly the credential // the operator had just retired, while their reset had long answered success. Measured // on a live worker: nine resets out of nine lost when a login preceded them. A guard // that checks the stored hash before writing does not close this — the expensive hashing // sits between the check and the write, and the reset lands inside it. // // Awaiting removes the detached writer altogether: the login answers only after the // rehash is on disk, so anything that changes the password afterwards writes last and // wins, by construction. The cost is one extra hash on the login path — capped to one // attempt per user per process below, because until the upgrade actually converges // (see the rehash method's remarks) every local login would pay it. // // Through the request-scoped service, not a fresh scope: the fresh scope existed only // because fire-and-forget outlived the request. Awaited, a second scope means a second // connection — and on SQLite that second writer promptly hits 'database is locked' // against the login's own connection. Same connection: no second writer, and inside a // transacted route the rehash simply joins the route's transaction. if (RehashAttempted.TryAdd(coreUser.Id, 0)) { await RehashPasswordIfUnchangedAsync( _redb, coreUser.Id, password, coreUser.Password, _logger) .ConfigureAwait(false); } } // Note: ValidateUserAsync already returns null for disabled users — no separate // branch is needed here, and adding one would re-introduce the enumeration leak // (different error message for "disabled" vs "wrong password"). var oidcObj = await _redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync() .ConfigureAwait(false); _logger.LogDebug("User '{Username}' (id={UserId}) authenticated locally", username, coreUser.Id); // Check MFA (after password validated, before session creation). // B9 / BUG-4: single atomic read of MfaProps via LoadMfaStatusAsync (was two // separate reads — IsMfaEnabledAsync + GetEnabledMethodsAsync — leaving a TOCTOU // window where MFA could be enabled/disabled between the two calls). if (_mfaService is not null) { var (mfaEnabled, methods) = await _mfaService.LoadMfaStatusAsync(coreUser.Id).ConfigureAwait(false); if (mfaEnabled && methods.Length > 0) { _logger.LogDebug("MFA required for user '{Username}' (id={UserId}), methods={Methods}", username, coreUser.Id, string.Join(",", methods)); return LoginResult.MfaChallenge(coreUser, methods); } } // H10 — password expiration. Compare against the configured MaxAge if any. Null // PasswordChangedAt is treated as "not tracked" (legacy users), to avoid forcing // a password change on every account that pre-dates H10. var maxAge = _passwordPolicy?.MaxAge ?? TimeSpan.Zero; if (maxAge > TimeSpan.Zero && oidcObj?.Props.PasswordChangedAt is DateTimeOffset changedAt && _timeProvider.GetUtcNow() - changedAt > maxAge) { _logger.LogDebug( "Password expired for user '{Username}' (id={UserId}); changedAt={ChangedAt}, maxAge={MaxAge}", username, coreUser.Id, changedAt, maxAge); return LoginResult.PasswordExpired(coreUser, oidcObj); } return LoginResult.Success(coreUser, oidcObj); } /// /// Pre-computed BCrypt hash of an arbitrary unguessable string used solely for /// timing-equivalence (see C14 / SEC-A20). Cost factor 12 to mirror the production /// hash work factor used by . /// private static readonly string FakeBcryptHash = BCrypt.Net.BCrypt.HashPassword(Guid.NewGuid().ToString("N"), workFactor: 12); /// /// C12: ask the hasher whether the stored hash should be re-hashed after a successful /// verify. itself has no NeedsRehash contract, so /// we duck-type against the concrete hashers supplied by this module. Unknown /// implementations report "no upgrade needed" (conservative — no spurious rehashes). /// private static bool NeedsRehash(IPasswordHasher hasher, string storedHash) => hasher switch { Security.MultiFormatPasswordHasher mf => mf.NeedsRehash(storedHash), Security.Argon2idPasswordHasher a => a.NeedsRehash(storedHash), _ => false, }; /// /// Users whose rehash was already attempted in this process. The upgrade does not currently /// converge — the write goes through the core provider's own hasher, and when that is BCrypt the /// "upgraded" hash is BCrypt again, so stays true forever. Without this /// cap every local login would pay the extra awaited hash; with it, one per user per process. /// The convergence itself (writing with this module's Argon2id) needs a way to hand the core a /// ready-made hash, which is a redb.Core API question — reported, not worked around. /// private static readonly System.Collections.Concurrent.ConcurrentDictionary RehashAttempted = new(); /// /// C12 upgrade-on-login, second half. Runs on the caller's own — it /// is awaited from the login path (see the call site for why fire-and-forget was a security bug, /// not a latency optimisation), so a separate DI scope would only add a second connection, and /// on SQLite a second writer means 'database is locked' against the login's own. /// Internal and awaitable so both halves are testable. /// /// true when the hash was rewritten; false when skipped or failed. internal static async Task RehashPasswordIfUnchangedAsync( IRedbService rehashRedb, long userId, string password, string hashAtLogin, ILogger? logger) { try { var freshUser = await rehashRedb.UserProvider.GetUserByIdAsync(userId).ConfigureAwait(false); if (freshUser is null) return false; // Guard: rehash only while the stored hash is still the one this login verified. // This task lands roughly a second after the login that scheduled it — Argon2id is slow // by design, Task.Run adds scheduling, the fresh scope adds a connection — and an admin // reset fits into that window comfortably. Writing without the check would put the // pre-login password back over the freshly set one: the account silently reverts to // exactly the credential the operator was trying to retire, while their reset call has // long since answered success. Observed on a live worker, nine times out of nine. // // The check narrows the window to the read-to-write gap below; closing it fully needs a // compare-and-set on the UPDATE itself (WHERE _password = @expected), which is a // redb.Core API question, not this method's. if (!string.Equals(freshUser.Password, hashAtLogin, StringComparison.Ordinal)) { logger?.LogDebug( "Password rehash skipped for user id={UserId}: the stored hash changed since login", userId); return false; } await rehashRedb.UserProvider.SetPasswordAsync(freshUser, password, currentUser: freshUser) .ConfigureAwait(false); logger?.LogDebug("Password hash upgraded to current algorithm for user id={UserId}", userId); return true; } catch (Exception ex) { logger?.LogWarning(ex, "Password hash auto-rehash failed for user id={UserId}", userId); return false; } } /// /// Find-or-create local _users + UserProps for an externally authenticated user. /// On subsequent logins, updates profile from external source. /// private async Task ResolveExternalUser( string providerName, ExternalAuthResult ext, string username) { return await ResolveExternalUserCore(providerName, ext, username).ConfigureAwait(false); } /// /// Resolves a federated user by reverse lookup on the [RedbUnique] LinkKey (one index probe). /// Used by the federation callback flow where there is no username/password — only /// an from the external IdP. /// On first login: auto-provisions a local user (login = email ?? sub). /// On subsequent logins: syncs profile from external source. /// public async Task ResolveFederatedUserAsync( string providerName, ExternalAuthResult ext, CancellationToken ct = default) { if (ext is null || !ext.Succeeded || string.IsNullOrEmpty(ext.ExternalId)) return LoginResult.Failed("Invalid external authentication result."); // H8/V4-UNIQUE: per-link reverse lookup via the [RedbUnique] LinkKey — one probe of // the unique index. O(1) — supports many federated identities per user. var linkKey = FederatedIdentityProps.MakeLinkKey(providerName, ext.ExternalId); var link = await FindLinkAsync(linkKey).ConfigureAwait(false); long? linkedUserId = link?.key; if (linkedUserId.HasValue) { var coreUser = await _redb.UserProvider.GetUserByIdAsync(linkedUserId.Value) .ConfigureAwait(false); if (coreUser is null) { _logger.LogWarning( "Federated link references userId={UserId} but _users row not found (provider={Provider}, sub={Sub})", linkedUserId.Value, providerName, ext.ExternalId); return LoginResult.Failed("User account not found."); } if (!coreUser.Enabled) { _securityLogger.LogWarning("Login denied: federated user '{Username}' is disabled locally", coreUser.Login); return LoginResult.Failed("User account is not active."); } // Authoritative profile sync await SyncCoreProfile(coreUser, ext).ConfigureAwait(false); var oidcObj = await _redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync() .ConfigureAwait(false); if (oidcObj is not null) { await SyncOidcProps(oidcObj, providerName, ext, coreUser.Login ?? ext.Email ?? ext.ExternalId) .ConfigureAwait(false); } // H8: upsert per-link record await UpsertFederatedIdentityLinkAsync(coreUser.Id, providerName, ext, isNewLink: link is null) .ConfigureAwait(false); _logger.LogDebug( "Federated user '{Username}' (id={UserId}) authenticated via '{Provider}'", coreUser.Login, coreUser.Id, providerName); return LoginResult.Success(coreUser, oidcObj); } // H8 (gap (c)): conflict-on-email — if a local user already exists with this email // but no federated link, refuse to silently take over the account. Caller // (FederationCallbackProcessor) translates this into a redirect to the configured // conflict-resolution page so the user can either log in locally then link, or // confirm a takeover with proper credentials. // // Was previously `GetUserByLoginAsync(ext.Email)` — that only triggered when the // local user's login literally equalled the external email, but self-register // forbids '@' in login so the probe was effectively dead code. `GetUserByEmailAsync` // (added to redb.Core in this batch) does a proper case-insensitive lookup on // `_users._email`, so the conflict path now fires for genuine email overlap. if (!string.IsNullOrEmpty(ext.Email)) { var existingByEmail = await _redb.UserProvider.GetUserByEmailAsync(ext.Email) .ConfigureAwait(false); if (existingByEmail is not null) { _securityLogger.LogWarning( "Federated email conflict: provider={Provider} sub={Sub} email={Email} matches existing local user id={UserId}", providerName, ext.ExternalId, ext.Email, existingByEmail.Id); return LoginResult.EmailConflict(ext.Email, providerName, ext.ExternalId); } } // New user — auto-provision var username = ext.Email ?? ext.ExternalId; return await ResolveExternalUserCore(providerName, ext, username).ConfigureAwait(false); } private async Task ResolveExternalUserCore( string providerName, ExternalAuthResult ext, string username) { // Try to find existing user by login (unique in _users) var coreUser = await _redb.UserProvider.GetUserByLoginAsync(username) .ConfigureAwait(false); if (coreUser is null) { // First login ever — create local user with random password (external-only) coreUser = await _redb.UserProvider.CreateUserAsync(new CreateUserRequest { Login = username, Password = Guid.NewGuid().ToString("N") + "Aa1!", // satisfies any complexity rules Name = ext.DisplayName ?? username, Email = ext.Email, Phone = ext.Phone, Enabled = true, CodeString = providerName // quick marker on _users level }).ConfigureAwait(false); _logger.LogDebug("Created local user '{Username}' (id={UserId}) for external provider '{Provider}'", username, coreUser.Id, providerName); } if (!coreUser.Enabled) { _securityLogger.LogWarning("Login denied: external user '{Username}' is disabled locally", username); return LoginResult.Failed("User account is not active."); } // Authoritative sync: always push external profile → _users row var needsUpdate = false; var updateReq = new UpdateUserRequest(); if (ext.DisplayName is not null && ext.DisplayName != coreUser.Name) { updateReq.Name = ext.DisplayName; needsUpdate = true; } if (ext.Email is not null && ext.Email != coreUser.Email) { updateReq.Email = ext.Email; needsUpdate = true; } if (ext.Phone is not null && ext.Phone != coreUser.Phone) { updateReq.Phone = ext.Phone; needsUpdate = true; } if (needsUpdate) { coreUser = await _redb.UserProvider.UpdateUserAsync(coreUser, updateReq) .ConfigureAwait(false); } // Upsert UserProps with external linking + profile sync var oidcObj = await _redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync() .ConfigureAwait(false); if (oidcObj is null) { oidcObj = new RedbObject(new UserProps { UserId = coreUser.Id }); oidcObj.name = username; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); } // Always sync external profile on login oidcObj.Props.ExternalIdentities ??= new Dictionary(); oidcObj.Props.ExternalIdentities[providerName] = new ExternalIdentity { Sub = ext.ExternalId, LinkedAt = _timeProvider.GetUtcNow() }; // H8: do NOT touch oidcObj.value_string here — it would silently overwrite any // earlier federated link's reverse-lookup key. Per-link reverse lookup is // handled by FederatedIdentityProps (UpsertFederatedIdentityLinkAsync below). if (ext.GivenName is not null) oidcObj.Props.GivenName = ext.GivenName; if (ext.FamilyName is not null) oidcObj.Props.FamilyName = ext.FamilyName; if (ext.Email is not null) oidcObj.Props.EmailVerified = true; if (ext.Phone is not null) oidcObj.Props.PhoneNumberVerified = true; // Merge additional claims from external provider if (ext.AdditionalClaims is { Count: > 0 }) { oidcObj.Props.CustomClaims ??= new Dictionary(); foreach (var (key, value) in ext.AdditionalClaims) oidcObj.Props.CustomClaims[key] = value; } await _redb.SaveAsync(oidcObj).ConfigureAwait(false); // H8: per-link PROPS record (enables multi-provider linking + reverse lookup) await UpsertFederatedIdentityLinkAsync(coreUser.Id, providerName, ext, isNewLink: true) .ConfigureAwait(false); return LoginResult.Success(coreUser, oidcObj); } private async Task SyncCoreProfile(IRedbUser coreUser, ExternalAuthResult ext) { var needsUpdate = false; var updateReq = new UpdateUserRequest(); if (ext.DisplayName is not null && ext.DisplayName != coreUser.Name) { updateReq.Name = ext.DisplayName; needsUpdate = true; } if (ext.Email is not null && ext.Email != coreUser.Email) { updateReq.Email = ext.Email; needsUpdate = true; } if (ext.Phone is not null && ext.Phone != coreUser.Phone) { updateReq.Phone = ext.Phone; needsUpdate = true; } if (needsUpdate) await _redb.UserProvider.UpdateUserAsync(coreUser, updateReq).ConfigureAwait(false); } private async Task SyncOidcProps( RedbObject oidcObj, string providerName, ExternalAuthResult ext, string username) { oidcObj.Props.ExternalIdentities ??= new Dictionary(); oidcObj.Props.ExternalIdentities[providerName] = new ExternalIdentity { Sub = ext.ExternalId, LinkedAt = _timeProvider.GetUtcNow() }; // H8: do NOT touch oidcObj.value_string — see ResolveExternalUserCore for rationale. if (ext.GivenName is not null) oidcObj.Props.GivenName = ext.GivenName; if (ext.FamilyName is not null) oidcObj.Props.FamilyName = ext.FamilyName; if (ext.Email is not null) oidcObj.Props.EmailVerified = true; if (ext.Phone is not null) oidcObj.Props.PhoneNumberVerified = true; if (ext.AdditionalClaims is { Count: > 0 }) { oidcObj.Props.CustomClaims ??= new Dictionary(); foreach (var (key, value) in ext.AdditionalClaims) oidcObj.Props.CustomClaims[key] = value; } await _redb.SaveAsync(oidcObj).ConfigureAwait(false); } // ───────────────────────────────────────────────────────────────────────── // H8 (DoD §4): per-link FederatedIdentityProps maintenance + public // self-service link/unlink/list API consumed by MeFederatedIdentitiesProcessor. // ───────────────────────────────────────────────────────────────────────── /// /// Upserts a single (user, provider) federated link in the per-link PROPS scheme. /// Idempotent — safe to call on every successful federated login. The /// [RedbUnique] makes concurrent /// inserts of one external identity collide at the DB level on every provider /// (V4-UNIQUE; before F2 no index actually existed and duplicates were possible); /// the loser re-reads the winner and runs the same integrity check. /// private async Task UpsertFederatedIdentityLinkAsync( long userId, string providerName, ExternalAuthResult ext, bool isNewLink) { var linkKey = FederatedIdentityProps.MakeLinkKey(providerName, ext.ExternalId); var existing = await FindLinkAsync(linkKey).ConfigureAwait(false); var now = _timeProvider.GetUtcNow(); if (existing is null) { var fresh = new RedbObject(new FederatedIdentityProps { ProviderId = providerName, ExternalSub = ext.ExternalId, LinkKey = linkKey, LinkedAt = now, ExternalEmail = ext.Email, ExternalDisplayName = ext.DisplayName, LastLoginAt = now, }); fresh.name = linkKey; fresh.key = userId; try { await _redb.SaveAsync(fresh).ConfigureAwait(false); return; } catch (RedbUniqueViolationException) { // Lost the creation race on the [RedbUnique] LinkKey. Deliberately NOT // SaveByUniqueAsync: its last-writer-wins would silently re-point a link // owned by ANOTHER user. Re-read the winner and fall through to the same // integrity check every non-race path runs. existing = await FindLinkAsync(linkKey).ConfigureAwait(false); if (existing is null) throw; // key vanished between the violation and the re-read; surface it } } if (existing.key != userId) { // Hard data integrity: same external sub linked to a different local user. // Log and refuse rather than silently re-pointing the link. _securityLogger.LogError( "FederatedIdentityProps integrity violation: LinkKey={LinkKey} already links to userId={ExistingUserId}, refused re-link to userId={NewUserId}", linkKey, existing.key, userId); throw new InvalidOperationException( $"External identity '{linkKey}' is already linked to a different user."); } existing.Props.ExternalEmail = ext.Email; existing.Props.ExternalDisplayName = ext.DisplayName; existing.Props.LastLoginAt = now; await _redb.SaveAsync(existing).ConfigureAwait(false); } /// /// The one lookup for a federated link (V4-UNIQUE): a probe of the [RedbUnique] /// LinkKey index, with a transition fallback to the pre-V4 value_string mirror. /// The fallback matters: a legacy row the backfill has not repaired yet MUST still /// resolve — a miss on the login path would auto-provision a SECOND local user for an /// already-linked external identity. A row found through the fallback is repaired in /// place. The fallback goes away at teardown. /// private async Task?> FindLinkAsync(string linkKey) { var link = await _redb.GetByUniqueAsync(p => p.LinkKey, linkKey) .ConfigureAwait(false); if (link is not null) return link; link = await _redb.Query() .WhereRedb(o => o.ValueString == linkKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (link is not null && link.Props.LinkKey is null) { link.Props.LinkKey = linkKey; try { await _redb.SaveAsync(link).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // A concurrent repair of the same legacy row won; harmless — re-read it. return await _redb.GetByUniqueAsync(p => p.LinkKey, linkKey) .ConfigureAwait(false); } } return link; } /// /// H8 (gap (b)): self-service link of a federated identity to an already-authenticated /// local user. Used by MeFederatedIdentitiesProcessor. Throws when the external /// identity is already linked to a different user. /// public async Task LinkFederatedIdentityAsync( long userId, string providerName, ExternalAuthResult ext, CancellationToken ct = default) { await UpsertFederatedIdentityLinkAsync(userId, providerName, ext, isNewLink: true) .ConfigureAwait(false); // Mirror to denormalized cache on UserProps var oidcObj = await _redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (oidcObj is null) { oidcObj = new RedbObject(new UserProps { UserId = userId }); oidcObj.key = userId; oidcObj.value_guid = Guid.NewGuid(); } oidcObj.Props.ExternalIdentities ??= new Dictionary(); oidcObj.Props.ExternalIdentities[providerName] = new ExternalIdentity { Sub = ext.ExternalId, LinkedAt = _timeProvider.GetUtcNow() }; await _redb.SaveAsync(oidcObj).ConfigureAwait(false); } /// /// H8 (gap (b)/(d)): self-service unlink. Returns false when no such link exists. /// Caller is responsible for the "last credential method" guard (it requires reading /// ). /// public async Task UnlinkFederatedIdentityAsync( long userId, string providerName, CancellationToken ct = default) { var links = await _redb.Query() .WhereRedb(o => o.Key == userId) .ToListAsync() .ConfigureAwait(false); var match = links.FirstOrDefault(o => string.Equals(o.Props.ProviderId, providerName, StringComparison.OrdinalIgnoreCase)); if (match is null) return false; await _redb.DeleteAsync(match).ConfigureAwait(false); // Mirror to denormalized cache var oidcObj = await _redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (oidcObj?.Props.ExternalIdentities is { } map && map.Remove(providerName)) await _redb.SaveAsync(oidcObj).ConfigureAwait(false); return true; } /// /// H8 (gap (b)): list all federated links for a user. Returned in stable order /// (provider id ascending) for deterministic UI display. /// public async Task> ListFederatedIdentitiesAsync( long userId, CancellationToken ct = default) { var links = await _redb.Query() .WhereRedb(o => o.Key == userId) .ToListAsync() .ConfigureAwait(false); return links .OrderBy(o => o.Props.ProviderId, StringComparer.OrdinalIgnoreCase) .Select(o => new FederatedIdentityLink( o.Props.ProviderId, o.Props.ExternalSub, o.Props.ExternalEmail, o.Props.ExternalDisplayName, o.Props.LinkedAt, o.Props.LastLoginAt)) .ToList(); } } /// /// H8: read-model record for a single federated identity link, returned to callers of /// . /// public sealed record FederatedIdentityLink( string ProviderId, string ExternalSub, string? ExternalEmail, string? ExternalDisplayName, DateTimeOffset LinkedAt, DateTimeOffset? LastLoginAt); /// /// Result of a login attempt. /// public sealed class LoginResult { public bool Succeeded { get; private init; } public long UserId { get; private init; } public string? Username { get; private init; } /// Core _users row. public IRedbUser? User { get; private init; } /// OIDC extension props (may be null if profile was never saved). public UserProps? OidcProps { get; private init; } /// /// Public-facing GUID identity used for the OIDC sub claim. Pulled from /// RedbObject<UserProps>.value_guid at login time so the same user has /// the same GUID across all sessions and tokens. when the /// login attempt failed (no user resolved) or for legacy data without value_guid. /// public Guid SubjectGuid { get; private init; } public string? ErrorMessage { get; private init; } /// True when password is valid but MFA verification is still required. public bool MfaRequired { get; private init; } /// Available MFA methods when is true. public string[]? MfaMethods { get; private init; } /// /// H10 — password verified, but /// elapsed since /// . Caller (interactive login or password /// grant) must redirect the user to the password-change flow before issuing tokens. /// public bool MustChangePassword { get; private init; } /// /// H8 (gap (c)): set when the federated callback discovered an existing local user /// with the same email but no explicit federated link. Caller must NOT mint tokens — /// it should redirect the user to a "log in locally and link your social account" page. /// public bool IsEmailConflict { get; private init; } /// H8 (gap (c)): conflicting email reported by the external IdP. public string? ConflictEmail { get; private init; } /// H8 (gap (c)): provider id that initiated the conflicting callback. public string? ConflictProviderId { get; private init; } /// H8 (gap (c)): external subject from the IdP for the pending link. public string? ConflictExternalSub { get; private init; } public static LoginResult Success(IRedbUser user, RedbObject? oidcObj) => new() { Succeeded = true, UserId = user.Id, Username = user.Login, User = user, OidcProps = oidcObj?.Props, SubjectGuid = oidcObj?.value_guid ?? Guid.Empty }; public static LoginResult Failed(string message) => new() { Succeeded = false, ErrorMessage = message }; /// Password verified, but MFA is required before session creation. public static LoginResult MfaChallenge(IRedbUser user, string[] methods) => new() { Succeeded = false, MfaRequired = true, UserId = user.Id, Username = user.Login, User = user, MfaMethods = methods }; /// /// H10 — password verified but expired. Caller must steer the user into the /// password-change flow (interactive: redirect; ROPC: reject with /// password_expired). /// public static LoginResult PasswordExpired(IRedbUser user, RedbObject? oidcObj) => new() { Succeeded = false, MustChangePassword = true, UserId = user.Id, Username = user.Login, User = user, OidcProps = oidcObj?.Props, SubjectGuid = oidcObj?.value_guid ?? Guid.Empty, ErrorMessage = "Password expired." }; /// /// H8 (gap (c)): federated callback discovered an existing local user with this /// email but no link from this provider yet. Caller redirects to the conflict /// resolution page so the user can sign in locally and explicitly add the link. /// public static LoginResult EmailConflict(string email, string providerId, string externalSub) => new() { Succeeded = false, IsEmailConflict = true, ConflictEmail = email, ConflictProviderId = providerId, ConflictExternalSub = externalSub, ErrorMessage = "Federated email already registered locally." }; } Path: redb-identity/src/redb.Identity.Core/Services/LogoutConfirmationProtector.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/Services/LogoutConfirmationProtector.cs ---- using System.Security.Cryptography; using System.Text.Json; using Microsoft.AspNetCore.DataProtection; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Services; /// /// The proof that the End-User, not a page they happened to visit, asked to sign out. /// /// /connect/logout is the OIDC end_session_endpoint and works on the browser's own session /// cookie, which a cross-site top-level navigation carries (SameSite=Lax): a link on any page could /// end the visitor's OP session. A relying party proves its intent with a valid id_token_hint whose /// sub is the session's user; a request without one gets a confirmation page instead, and the page's /// form carries a state issued here. The state is bound to the user and the session it was shown for and /// lives five minutes; a foreign page cannot read it (same-origin policy) nor forge it (DataProtection), so /// presenting it is the confirmation. Same shape as Duende's logout prompt and Keycloak's confirmation /// without id_token_hint. /// /// public sealed class LogoutConfirmationProtector { private const string Purpose = "redb.identity.logout-confirmation"; private static readonly TimeSpan MaxAge = TimeSpan.FromMinutes(5); private readonly IDataProtector _protector; private readonly TimeProvider _timeProvider; public LogoutConfirmationProtector(IDataProtectionProvider provider, TimeProvider? timeProvider = null) { ArgumentNullException.ThrowIfNull(provider); _protector = provider.CreateProtector(Purpose); _timeProvider = timeProvider ?? TimeProvider.System; } /// Issues a state for the confirmation page shown to in session . public string Issue(long userId, long sessionId) { var state = new State(userId, sessionId, _timeProvider.GetUtcNow()); return Convert.ToBase64String(_protector.Protect(JsonSerializer.SerializeToUtf8Bytes(state))); } /// /// True when is a state this server issued for exactly this user and /// session, and it is not older than five minutes. Anything else — absent, altered, foreign, another /// session's, expired — is not a confirmation, and the caller shows the page again. /// public bool Accepts(string? protectedState, long userId, long sessionId) { if (string.IsNullOrEmpty(protectedState)) return false; State? state; try { var payload = _protector.Unprotect(Base64Canonical.Decode(protectedState)); state = JsonSerializer.Deserialize(payload); } catch (Exception ex) when (ex is CryptographicException or FormatException or JsonException) { // Not something this server issued: a tampered envelope, foreign bytes or a malformed value. // That is the answer, not a fault. return false; } return state is not null && state.UserId == userId && state.SessionId == sessionId && _timeProvider.GetUtcNow() - state.IssuedAt <= MaxAge; } private sealed record State(long UserId, long SessionId, DateTimeOffset IssuedAt); } Path: redb-identity/src/redb.Identity.Core/Services/LogoutTokenBuilder.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/Services/LogoutTokenBuilder.cs ---- using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using OpenIddict.Server; namespace redb.Identity.Core.Services; /// /// Builds OIDC Back-Channel Logout 1.0 logout_token JWTs (RFC: OIDC Back-Channel /// Logout 1.0 §2.4). Uses the same signing keys as the issuer's id_token, so any RP that /// already validates id_tokens from this issuer can validate the logout_token unchanged. /// public sealed class LogoutTokenBuilder { /// Mandatory event identifier per OIDC Back-Channel Logout 1.0 §2.4. public const string LogoutEventIdentifier = "http://schemas.openid.net/event/backchannel-logout"; private static readonly JwtSecurityTokenHandler _tokenHandler = new() { MapInboundClaims = false }; private readonly IOptionsMonitor _serverOptions; private readonly TimeProvider _timeProvider; private readonly ILogger? _logger; public LogoutTokenBuilder( IOptionsMonitor serverOptions, TimeProvider? timeProvider = null, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(serverOptions); _serverOptions = serverOptions; _timeProvider = timeProvider ?? TimeProvider.System; _logger = logger; } /// /// Returns true when at least one signing credential is configured. Without one /// we cannot produce a logout_token and backchannel logout must be a no-op. /// public bool CanIssue => _serverOptions.CurrentValue.SigningCredentials.Count > 0; /// /// Builds a signed logout_token for a given RP. /// /// RP's client_id (becomes the aud claim). /// End-user identifier (becomes the sub claim). /// /// Optional session id. When not null/empty, an sid claim is added so the RP can /// terminate only the matching session instead of all sessions for the user. /// /// A signed JWS string, or null when no signing key is configured. public string? Build(string audience, string subject, string? sessionId = null) { ArgumentException.ThrowIfNullOrEmpty(audience); ArgumentException.ThrowIfNullOrEmpty(subject); var opts = _serverOptions.CurrentValue; var signing = opts.SigningCredentials.FirstOrDefault(); if (signing is null) { _logger?.LogWarning("No signing credential configured — cannot issue logout_token for {Audience}.", audience); return null; } var issuer = opts.Issuer?.ToString().TrimEnd('/') ?? string.Empty; var now = _timeProvider.GetUtcNow().UtcDateTime; // OIDC Back-Channel Logout 1.0 §2.4: // - MUST contain: iss, aud, iat, jti, events // - MUST contain at least one of: sub, sid // - MUST NOT contain: nonce var claims = new List { new(JwtRegisteredClaimNames.Sub, subject), new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), // events is a JSON object; we serialize it as a literal so JwtPayload doesn't escape it. new("events", $"{{\"{LogoutEventIdentifier}\":{{}}}}", JsonClaimValueTypes.Json), }; if (!string.IsNullOrEmpty(sessionId)) claims.Add(new Claim("sid", sessionId)); var token = new JwtSecurityToken( issuer: string.IsNullOrEmpty(issuer) ? null : issuer, audience: audience, claims: claims, notBefore: null, expires: null, // logout_token has no exp per spec; iat + clock skew is what RP checks signingCredentials: signing); // iat is set automatically by JwtSecurityToken when not in claims; force it to our TimeProvider. token.Payload[JwtRegisteredClaimNames.Iat] = new DateTimeOffset(now).ToUnixTimeSeconds(); return _tokenHandler.WriteToken(token); } } Path: redb-identity/src/redb.Identity.Core/Services/MemoryDpopReplayStore.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/Services/MemoryDpopReplayStore.cs ---- using System.Collections.Concurrent; namespace redb.Identity.Core.Services; /// /// In-process implementation of . Backed by a /// with TTL-based pruning. /// Single-instance only — see . /// public sealed class MemoryDpopReplayStore : IDpopReplayStore, IDisposable { private readonly TimeProvider _timeProvider; private readonly ConcurrentDictionary _seen = new(StringComparer.Ordinal); private readonly Timer? _sweeper; public MemoryDpopReplayStore(TimeProvider? timeProvider = null, TimeSpan? sweepInterval = null) { _timeProvider = timeProvider ?? TimeProvider.System; var interval = sweepInterval ?? TimeSpan.FromMinutes(5); if (interval > TimeSpan.Zero && interval != Timeout.InfiniteTimeSpan) { _sweeper = new Timer(_ => Prune(), null, interval, interval); } } /// public Task TryReserveAsync(string jkt, string jti, TimeSpan ttl, CancellationToken ct = default) { if (string.IsNullOrEmpty(jkt) || string.IsNullOrEmpty(jti)) return Task.FromResult(false); var nowTicks = _timeProvider.GetUtcNow().UtcTicks; var expiryTicks = nowTicks + Math.Max(ttl.Ticks, TimeSpan.TicksPerSecond); var key = jkt + "|" + jti; if (_seen.TryAdd(key, expiryTicks)) return Task.FromResult(true); // Existing entry: only allow re-reservation when it has expired. if (_seen.TryGetValue(key, out var existing) && existing <= nowTicks && _seen.TryUpdate(key, expiryTicks, existing)) { return Task.FromResult(true); } return Task.FromResult(false); } private void Prune() { var nowTicks = _timeProvider.GetUtcNow().UtcTicks; foreach (var kv in _seen) { if (kv.Value <= nowTicks) _seen.TryRemove(kv.Key, out _); } } public void Dispose() => _sweeper?.Dispose(); } Path: redb-identity/src/redb.Identity.Core/Services/MfaSecretProtector.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/Services/MfaSecretProtector.cs ---- using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging; namespace redb.Identity.Core.Services; /// /// Encrypts/decrypts TOTP secrets at rest using ASP.NET DataProtection. /// Unlike , no TTL — secrets live until user disables MFA. /// public sealed class MfaSecretProtector { private const string Purpose = "redb.identity.mfa-secret"; private readonly IDataProtector _protector; private readonly ILogger? _logger; public MfaSecretProtector(IDataProtectionProvider provider, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(provider); _protector = provider.CreateProtector(Purpose); _logger = logger; } /// Encrypts a plaintext secret (e.g. base32-encoded TOTP key). public string Protect(string plainSecret) { ArgumentNullException.ThrowIfNull(plainSecret); var bytes = System.Text.Encoding.UTF8.GetBytes(plainSecret); var encrypted = _protector.Protect(bytes); return Convert.ToBase64String(encrypted); } /// Decrypts a protected secret. Returns null if decryption fails (tampered/rotated keys). public string? Unprotect(string protectedSecret) { if (string.IsNullOrEmpty(protectedSecret)) return null; try { var encrypted = Convert.FromBase64String(protectedSecret); var bytes = _protector.Unprotect(encrypted); return System.Text.Encoding.UTF8.GetString(bytes); } catch (Exception ex) { // Log every decrypt failure: each one is either a security signal (tampered ciphertext) // or an operational alert (DataProtection key rotation/loss). Returning null keeps the // public contract intact for callers (treat as "secret unavailable"). _logger?.LogWarning(ex, "MfaSecretProtector: failed to decrypt protected MFA secret (length={Length}).", protectedSecret.Length); return null; } } } Path: redb-identity/src/redb.Identity.Core/Services/MfaService.WebAuthn.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/Services/MfaService.WebAuthn.cs ---- using System.Text.Json; using Fido2NetLib; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Configuration; using redb.Identity.Core.Exceptions; using redb.Identity.Core.Mfa; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// MFA-3: WebAuthn (FIDO2) orchestration on top of . /// /// Unlike OTP-based methods, WebAuthn does not flow through 's /// InitiateSetupAsync / ConfirmAndApplyAsync / VerifyAsync path /// (the shapes are mismatched: WebAuthn has no shared secret, no destination, no 6-digit /// code). Instead, this partial exposes four bespoke methods (Begin/Complete \u00d7 Register/Assert) /// that the dedicated processors call. The orchestrator integrates the same lockout, /// recovery-code, audit and challenge-replay primitives used by the OTP path. /// /// public sealed partial class MfaService { private static readonly JsonSerializerOptions s_webAuthnJson = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, }; /// /// MFA-3: starts a WebAuthn registration ceremony. Returns /// (forwarded as JSON to the browser) bundled with /// an opaque setupToken that round-trips the challenge + serialized options. /// /// No DB write occurs until succeeds. /// /// public async Task<(CredentialCreateOptions Options, string SetupToken)> BeginWebAuthnRegistrationAsync( long userId, string username, string? displayName, CancellationToken ct = default) { var webAuthn = ResolveWebAuthnMethod(); var existing = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); var creds = existing?.Props?.WebAuthnCredentials; // Per-user UV ratchet: if the user already has a UV credential, force UV on the new // credential too \u2014 we never let a user weaken their own posture by adding a // non-UV authenticator after a UV one. bool enforceUv = creds is { Count: > 0 } && creds.Values.Any(c => c.UserVerified); var options = webAuthn.BeginRegistration( userId, username, string.IsNullOrEmpty(displayName) ? username : displayName, creds, enforceUv); var token = _setupTokenProtector.Protect(new MfaSetupTokenPayload { UserId = userId, MethodId = "webauthn", IssuedAt = _timeProvider.GetUtcNow(), Jti = Guid.NewGuid(), WebAuthnChallenge = options.Challenge, WebAuthnOptionsJson = JsonSerializer.Serialize(options, s_webAuthnJson), }); _logger.LogDebug("WebAuthn registration begin: userId={UserId}", userId); return (options, token); } /// /// MFA-3: completes a WebAuthn registration ceremony. Verifies the attestation, runs the /// AAGUID/UV gates inside , persists the credential, and /// (if this is the user's first MFA method) issues fresh recovery codes returned to the /// caller exactly once. /// /// Caller must hold a transaction with a row-lock on the user's MFA props row when /// calling this method \u2014 the processor wraps it in BeginTransactionAsync + /// LockForUpdateAsync just like . /// /// /// /// Tuple of (success, recoveryCodes-or-null, credentialKey). recoveryCodes is non-null /// only on the very first MFA method enrolled by this user. credentialKey is the /// dictionary key used to look up / rename / delete this credential later. /// public async Task<(bool Success, string[]? RecoveryCodes, string? CredentialKey, string? ErrorCode)> CompleteWebAuthnRegistrationAsync( long userId, AuthenticatorAttestationRawResponse attestationResponse, string setupToken, string? credentialDisplayName, CancellationToken ct = default) { var payload = _setupTokenProtector.Unprotect(setupToken); if (payload is null || payload.UserId != userId || !string.Equals(payload.MethodId, "webauthn", StringComparison.OrdinalIgnoreCase) || payload.WebAuthnChallenge is null || string.IsNullOrEmpty(payload.WebAuthnOptionsJson)) { _logger.LogWarning("WebAuthn register confirm rejected: invalid setup token (userId={UserId})", userId); return (false, null, null, "invalid_setup_token"); } var originalOptions = JsonSerializer.Deserialize( payload.WebAuthnOptionsJson, s_webAuthnJson); if (originalOptions is null) return (false, null, null, "invalid_setup_token"); // Single-use: reject second confirm with the same setup token. var consumeResult = await ResolveChallengeStore().ConsumeAsync( payload.WebAuthnChallenge, userId, "register", TimeSpan.FromMinutes(10), ct).ConfigureAwait(false); if (consumeResult == WebAuthnConsumeResult.Replay) { _securityLogger.LogWarning("WebAuthn register replay detected: userId={UserId}", userId); return (false, null, null, "replay_detected"); } WebAuthnCredential newCred; try { newCred = await ResolveWebAuthnMethod().CompleteRegistrationAsync( attestationResponse, originalOptions, userId, ct).ConfigureAwait(false); } catch (WebAuthnException ex) { _logger.LogWarning("WebAuthn register failed: userId={UserId}, code={Code}", userId, ex.ErrorCode); return (false, null, null, ex.ErrorCode); } if (!string.IsNullOrWhiteSpace(credentialDisplayName)) newCred.DisplayName = credentialDisplayName!.Trim(); var key = EncodeCredentialKey(newCred.CredentialId); var obj = await LoadOrCreateMfaPropsAsync(userId, ct).ConfigureAwait(false); obj.Props.WebAuthnCredentials ??= new Dictionary(StringComparer.Ordinal); // Defence-in-depth: same credential id MUST NOT be added twice. Fido2NetLib's // ExcludeCredentials covers the well-behaved-browser case; this guards against a // malicious/buggy client that strips ExcludeCredentials and submits a duplicate. if (obj.Props.WebAuthnCredentials.ContainsKey(key)) { return (false, null, null, "credential_already_registered"); } obj.Props.WebAuthnCredentials[key] = newCred; var wasAlreadyEnabled = obj.Props.Enabled; obj.Props.Enabled = true; if (string.IsNullOrEmpty(obj.Props.DefaultMethod)) obj.Props.DefaultMethod = "webauthn"; string[]? plainCodes = null; if (!wasAlreadyEnabled || obj.Props.RecoveryCodes is null or { Count: 0 }) { var (codes, hashedCodes) = GenerateRecoveryCodes(); obj.Props.RecoveryCodes = hashedCodes; obj.Props.RecoveryCodesPepperId = _pepperProvider.PepperId; plainCodes = codes; } obj.Props.FailedAttempts = 0; obj.Props.LockedUntil = null; await _redb.SaveAsync(obj).ConfigureAwait(false); _logger.LogDebug("WebAuthn credential registered: userId={UserId}, key={Key}", userId, key); return (true, plainCodes, key, null); } /// /// MFA-3: starts a WebAuthn assertion ceremony for an authenticated user (login flow or /// step-up). Returns + an encrypted mfa_state that /// the caller forwards to the client. /// /// /// (options, mfaStateToken). When the user has zero registered credentials the returned /// options' AllowedCredentials list is empty \u2014 the browser will surface a graceful /// no-credential error, identical to a non-existent userId, preserving username privacy. /// public async Task<(AssertionOptions Options, string MfaStateToken)?> BeginWebAuthnAssertionAsync( long userId, string? username, string? returnUrl, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); var creds = obj?.Props?.WebAuthnCredentials; if (creds is null || creds.Count == 0) return null; var options = ResolveWebAuthnMethod().BeginAssertion(creds); var state = new MfaState { Jti = Guid.NewGuid(), UserId = userId, Username = username, Methods = ["webauthn"], ReturnUrl = returnUrl, IssuedAt = _timeProvider.GetUtcNow(), WebAuthnChallenge = options.Challenge, WebAuthnFlow = "assert", WebAuthnOptionsJson = JsonSerializer.Serialize(options, s_webAuthnJson), }; var token = _stateProtector.Protect(state); return (options, token); } /// /// MFA-3: completes a WebAuthn assertion. Caller must hold a transaction with a row-lock /// on the MFA props (same pattern as ) so concurrent assertions /// cannot lose each other's updates. /// /// /// (success, errorCode). success == true means the credential mutations were /// persisted; errorCode on failure is one of invalid_state / /// flow_mismatch / replay_detected / locked_out / /// uv_downgrade / sign_counter_rollback / credential_not_found / /// verification_failed. /// public async Task<(bool Success, string? ErrorCode)> CompleteWebAuthnAssertionAsync( long userId, AuthenticatorAssertionRawResponse assertionResponse, MfaState state, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(state); if (state.UserId != userId) { _securityLogger.LogWarning("WebAuthn assert rejected (state.UserId mismatch): caller={UserId}", userId); return (false, "invalid_state"); } if (!string.Equals(state.WebAuthnFlow, "assert", StringComparison.Ordinal) || state.WebAuthnChallenge is null || string.IsNullOrEmpty(state.WebAuthnOptionsJson)) { return (false, "flow_mismatch"); } var originalOptions = JsonSerializer.Deserialize( state.WebAuthnOptionsJson, s_webAuthnJson); if (originalOptions is null) return (false, "invalid_state"); // Single-use challenge \u2014 reject replays even within the state token's TTL. var ttl = TimeSpan.FromSeconds(Math.Max(60, ResolveWebAuthnOptions().ChallengeTtlSeconds)); var consumeResult = await ResolveChallengeStore().ConsumeAsync( state.WebAuthnChallenge, userId, "assert", ttl, ct).ConfigureAwait(false); if (consumeResult == WebAuthnConsumeResult.Replay) { _securityLogger.LogWarning("WebAuthn assert replay detected: userId={UserId}", userId); return (false, "replay_detected"); } var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj?.Props is null) return (false, "credential_not_found"); var props = obj.Props; if (IsLockedOut(props)) { _securityLogger.LogWarning("WebAuthn assert rejected (locked out): userId={UserId}", userId); return (false, "locked_out"); } if (props.WebAuthnCredentials is null || props.WebAuthnCredentials.Count == 0) return (false, "credential_not_found"); WebAuthnCredential? mutated; try { mutated = await ResolveWebAuthnMethod().CompleteAssertionAsync( assertionResponse, originalOptions, props.WebAuthnCredentials, userId, ct).ConfigureAwait(false); } catch (WebAuthnException ex) { // Counter rollback / UV downgrade / credential_not_found are *typed* failures; // surface them but still treat as a failed verify for lockout accounting. BumpFailedAttempts(props); await _redb.SaveAsync(obj).ConfigureAwait(false); return (false, ex.ErrorCode); } if (mutated is null) { BumpFailedAttempts(props); await _redb.SaveAsync(obj).ConfigureAwait(false); return (false, "verification_failed"); } props.FailedAttempts = 0; props.LockedUntil = null; props.LastVerifiedAt = _timeProvider.GetUtcNow(); await _redb.SaveAsync(obj).ConfigureAwait(false); return (true, null); } /// /// MFA-3: lists registered WebAuthn credentials for the given user. /// public async Task> ListWebAuthnCredentialsAsync( long userId, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); var creds = obj?.Props?.WebAuthnCredentials; if (creds is null || creds.Count == 0) return Array.Empty(); return creds.Select(kv => new WebAuthnCredentialSummary( kv.Key, kv.Value.DisplayName, kv.Value.Aaguid, kv.Value.RegisteredAt, kv.Value.LastUsedAt, kv.Value.UserVerified, kv.Value.BackupEligible, kv.Value.BackupState )).ToList(); } /// /// MFA-3: renames a single credential (the friendly display label). /// public async Task RenameWebAuthnCredentialAsync( long userId, string credentialKey, string? newDisplayName, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj?.Props?.WebAuthnCredentials is null) return false; if (!obj.Props.WebAuthnCredentials.TryGetValue(credentialKey, out var cred)) return false; cred.DisplayName = string.IsNullOrWhiteSpace(newDisplayName) ? null : newDisplayName!.Trim(); await _redb.SaveAsync(obj).ConfigureAwait(false); return true; } /// /// MFA-3: deletes one credential. If this was the last credential and no other MFA method /// is enabled, the WebAuthn-method subsystem is silently disabled (but Enabled flag is left /// untouched if e.g. TOTP is still configured). /// public async Task DeleteWebAuthnCredentialAsync( long userId, string credentialKey, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj?.Props?.WebAuthnCredentials is null) return false; if (!obj.Props.WebAuthnCredentials.Remove(credentialKey)) return false; if (obj.Props.WebAuthnCredentials.Count == 0) { obj.Props.WebAuthnCredentials = null; // Defer to existing CollectEnabledMethods semantics: Enabled stays true if any other // method is confirmed; otherwise drop it. if (CollectEnabledMethods(obj.Props).Length == 0) { obj.Props.Enabled = false; if (string.Equals(obj.Props.DefaultMethod, "webauthn", StringComparison.OrdinalIgnoreCase)) obj.Props.DefaultMethod = null; } } await _redb.SaveAsync(obj).ConfigureAwait(false); return true; } // ── helpers ── /// /// Encodes a raw credential id as a stable dictionary key (base64url, no padding) suitable /// for use both as the JSON property name and the URL-path segment in REST endpoints. /// internal static string EncodeCredentialKey(byte[] rawId) { return Convert.ToBase64String(rawId) .TrimEnd('=') .Replace('+', '-') .Replace('/', '_'); } private void BumpFailedAttempts(MfaProps props) { props.FailedAttempts++; if (props.FailedAttempts >= _maxFailedAttempts) { props.LockedUntil = _timeProvider.GetUtcNow() + _lockoutDuration; _securityLogger.LogWarning( "MFA lockout activated via WebAuthn: attempts={Attempts}", props.FailedAttempts); } } private IWebAuthnMfaMethod ResolveWebAuthnMethod() { if (_methods.TryGetValue("webauthn", out var m) && m is IWebAuthnMfaMethod web) return web; throw new InvalidOperationException( "WebAuthn is not enabled. Set RedbIdentityOptions.WebAuthn.Enabled = true and ensure IFido2 is registered."); } /// /// MFA-3: lazy-resolved dependency. We deliberately /// avoid making it a constructor parameter so that the OTP-only configuration of the /// service does not have to register a no-op stub when WebAuthn is disabled. /// private IWebAuthnChallengeStore ResolveChallengeStore() => _webAuthnChallengeStore ?? throw new InvalidOperationException( "IWebAuthnChallengeStore is not registered. Enable RedbIdentityOptions.WebAuthn to wire it up."); private IdentityWebAuthnOptions ResolveWebAuthnOptions() => _webAuthnOptions ?? throw new InvalidOperationException( "IdentityWebAuthnOptions is not registered. Enable RedbIdentityOptions.WebAuthn to wire it up."); // Cached-via-DI references injected by the partial constructor extension below. private IWebAuthnChallengeStore? _webAuthnChallengeStore; private IdentityWebAuthnOptions? _webAuthnOptions; /// /// Property setter for DI activation \u2014 called from RedbIdentityServiceExtensions /// when WebAuthn is enabled. Kept off the primary constructor signature so existing /// MfaService construction sites (and hundreds of unit tests) do not need new arguments. /// public void AttachWebAuthn(IWebAuthnChallengeStore challengeStore, IdentityWebAuthnOptions options) { _webAuthnChallengeStore = challengeStore; _webAuthnOptions = options; } } /// MFA-3: client-facing summary of a registered WebAuthn credential. public sealed record WebAuthnCredentialSummary( string Key, string? DisplayName, string? Aaguid, DateTimeOffset RegisteredAt, DateTimeOffset? LastUsedAt, bool UserVerified, bool BackupEligible, bool BackupState); Path: redb-identity/src/redb.Identity.Core/Services/MfaService.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/Services/MfaService.cs ---- using System.Security.Cryptography; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Configuration; using redb.Identity.Core.Exceptions; using redb.Identity.Core.Mfa; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Orchestrates MFA operations: delegates to implementations, /// manages PROPS persistence, lockout, recovery codes, and OTP challenge dispatch. /// public sealed partial class MfaService { private readonly IRedbService _redb; private readonly IReadOnlyDictionary _methods; private readonly IReadOnlyDictionary _channels; private readonly MfaStateProtector _stateProtector; private readonly MfaSetupTokenProtector _setupTokenProtector; private readonly RedbIdentityOptions _options; private readonly ILogger _logger; private readonly ILogger _securityLogger; private readonly RecoveryCodePepperProvider _pepperProvider; private readonly TimeProvider _timeProvider; private readonly IServerSideOtpStore? _otpStore; private readonly int _maxFailedAttempts = 5; private readonly TimeSpan _lockoutDuration = TimeSpan.FromMinutes(15); private readonly int _recoveryCodeCount = 10; /// Cap on RecentOtpTimestamps list size to bound storage (B6 sliding window). private const int RecentOtpTimestampsCap = 50; /// Sliding-window length for OTP rate limiting (B6). private static readonly TimeSpan OtpRateLimitWindow = TimeSpan.FromHours(1); /// How long an e-mail or SMS one-time code stays valid. private static readonly TimeSpan OtpLifetime = TimeSpan.FromMinutes(5); public MfaService( IRedbService redb, IEnumerable methods, IEnumerable channels, MfaStateProtector stateProtector, MfaSetupTokenProtector setupTokenProtector, IOptions options, RecoveryCodePepperProvider pepperProvider, ILogger logger, TimeProvider? timeProvider = null, ILoggerFactory? loggerFactory = null, IServerSideOtpStore? otpStore = null, IEmailNotificationChannel? emailNotificationChannel = null) { _redb = redb; _methods = methods.ToDictionary(m => m.MethodId, StringComparer.OrdinalIgnoreCase); var channelMap = channels.ToDictionary(c => c.ChannelId, StringComparer.OrdinalIgnoreCase); // E-mail OTP goes out through the host's e-mail channel (SMTP when Smtp.Enabled is on), unless the host // registered an IMfaDeliveryChannel of its own for "email". if (emailNotificationChannel is not null && !channelMap.ContainsKey("email")) channelMap["email"] = new EmailMfaDeliveryChannel(emailNotificationChannel, OtpLifetime); _channels = channelMap; _stateProtector = stateProtector; _setupTokenProtector = setupTokenProtector; _options = options.Value; _pepperProvider = pepperProvider; _logger = logger; _timeProvider = timeProvider ?? TimeProvider.System; _otpStore = otpStore; // E5: security-channel for lockouts, rejected-verify, rate-limits. _securityLogger = loggerFactory is not null ? Security.IdentitySecurityLog.CreateLogger(loggerFactory) : logger; } /// Whether the user has at least one confirmed MFA method. public async Task IsMfaEnabledAsync(long userId, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj?.Props is not { Enabled: true } props) return false; return props.TotpConfirmed || props.SmsConfirmed || props.EmailConfirmed; } /// Returns the list of confirmed MFA method IDs for the user. public async Task GetEnabledMethodsAsync(long userId, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj?.Props is not { Enabled: true } props) return []; return CollectEnabledMethods(props); } /// /// Atomic accessor (B9 / BUG-4): returns both the enabled flag and the confirmed /// method list from a single MfaProps read, eliminating the TOCTOU window /// between the prior + /// pair (each of which fetched the props independently). /// public async Task<(bool Enabled, string[] Methods)> LoadMfaStatusAsync(long userId, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj?.Props is not { Enabled: true } props) return (false, Array.Empty()); var methods = CollectEnabledMethods(props); // Enabled is true ONLY if at least one method is confirmed — matches the // semantics of IsMfaEnabledAsync (which checks TotpConfirmed||Sms||Email). return (methods.Length > 0, methods); } private static string[] CollectEnabledMethods(MfaProps props) { var result = new List(3); if (props.TotpConfirmed) result.Add("totp"); if (props.SmsConfirmed && !string.IsNullOrEmpty(props.SmsPhone)) result.Add("sms"); if (props.EmailConfirmed && !string.IsNullOrEmpty(props.OtpEmail)) result.Add("email"); return result.ToArray(); } /// /// Initiates MFA setup for a method. Returns setup data (QR URI, masked destination, etc.) /// AND an opaque, encrypted setup token that the client must present back to /// . Does NOT mutate or save anything /// to the database — the candidate secret/destination lives only in the setup token until /// confirm. This eliminates the "two parallel setups race-overwrite the secret" bug (B5). /// /// E-mail: the one-time code goes to the candidate address now, and the result carries mfa_state, which /// confirm takes together with the code and the setup token. The only database write is the OTP rate-limit /// counter on the user's MFA record (created disabled if the user has none yet) and the server-side OTP. /// SMS is not changed: its setup sends nothing. /// /// /// Phone/email for SMS/Email; ignored by TOTP. public async Task SetupAsync(long userId, string methodId, string username, string? destination = null, CancellationToken ct = default) { var method = GetMethod(methodId); var initiation = await method.InitiateSetupAsync(username, destination, ct).ConfigureAwait(false); // If initiation reported an error (e.g. invalid phone) — return the client payload as-is, // do not issue a setup token and do not touch the database. if (initiation.ClientResult.Extra is not null && initiation.ClientResult.Extra.ContainsKey("error")) { return initiation.ClientResult; } var setupJti = Guid.NewGuid(); var clientResult = initiation.ClientResult; if (string.Equals(method.MethodId, "email", StringComparison.OrdinalIgnoreCase)) { var (protectedState, error) = await SendEnrollmentCodeAsync( userId, username, method.MethodId, initiation.Destination!, setupJti, ct).ConfigureAwait(false); if (error is not null) return new MfaSetupResult { MethodId = method.MethodId, Extra = error }; var extra = new Dictionary(clientResult.Extra ?? new Dictionary()) { ["mfa_state"] = protectedState! }; clientResult = clientResult with { Extra = extra }; } var token = _setupTokenProtector.Protect(new MfaSetupTokenPayload { UserId = userId, MethodId = methodId, EncryptedSecret = initiation.EncryptedSecret, Destination = initiation.Destination, IssuedAt = _timeProvider.GetUtcNow(), Jti = setupJti }); _logger.LogDebug("MFA setup token issued: userId={UserId}, method={Method}", userId, methodId); return clientResult with { SetupToken = token }; } /// /// Sends the one-time code of an e-mail enrollment to the candidate and returns /// the protected bound to , or the error the setup answers with /// (error = description, error_code = OAuth-style code). Rate-limited like a sign-in challenge. /// private async Task<(string? ProtectedState, Dictionary? Error)> SendEnrollmentCodeAsync( long userId, string username, string methodId, string destination, Guid setupJti, CancellationToken ct) { static Dictionary Fail(string code, string description) => new() { ["error"] = description, ["error_code"] = code }; if (!_channels.TryGetValue(methodId, out var channel) || _otpStore is null) return (null, Fail("no_channel", "No delivery channel is configured for this method")); var obj = await LoadOrCreateMfaPropsAsync(userId, ct).ConfigureAwait(false); var retryAfter = CheckOtpRateLimit(obj.Props); if (retryAfter > 0) { _securityLogger.LogWarning("MFA enrollment code rate-limited: userId={UserId}, retryAfter={RetryAfter}s", userId, retryAfter); return (null, Fail("rate_limited", $"Too many codes requested; retry after {retryAfter} seconds")); } // The slot is taken before delivery, success or failure alike (same rule as sign-in challenges). UpdateOtpRateLimitCounters(obj.Props); await _redb.SaveAsync(obj).ConfigureAwait(false); var masked = EmailMfaMethod.MaskEmail(destination); var issued = await _otpStore.IssueAsync(userId, methodId, masked, OtpLifetime, ct).ConfigureAwait(false); try { await channel.SendCodeAsync(destination, issued.PlaintextCode, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogError(ex, "MFA enrollment code delivery failed: userId={UserId}, channel={Channel}", userId, methodId); return (null, Fail("delivery_failed", "The verification code could not be delivered")); } var state = new MfaState { Jti = Guid.NewGuid(), UserId = userId, Username = username, OtpJti = issued.Jti, OtpDestination = masked, OtpMethod = methodId, OtpExpiresAt = issued.ExpiresAt, SetupJti = setupJti, }; _logger.LogDebug("MFA enrollment code sent: userId={UserId}, method={Method}", userId, methodId); return (_stateProtector.Protect(state), null); } /// /// Confirms MFA setup by verifying the first code against the candidate secret/destination /// carried inside . The setup token is the opaque string returned /// by . Returns recovery codes (plain text, shown once) on success or /// null if the token is invalid/expired or the code does not match. /// /// Decrypted MFA state for SMS/Email confirmation; null for TOTP. public async Task ConfirmSetupAsync(long userId, string methodId, string code, string setupToken, MfaState? state = null, CancellationToken ct = default) { var swTotal = System.Diagnostics.Stopwatch.StartNew(); // B7: do NOT throw on unknown methodId — that would distinguish "method exists" from // "token mismatch" to a probing attacker. Treat unknown methods as a generic failure, // identical to invalid token / userId mismatch / wrong code. if (!_methods.TryGetValue(methodId, out var method)) { _logger.LogWarning("MFA setup confirm rejected: unknown method (userId={UserId}, method={Method})", userId, methodId); return null; } var payload = _setupTokenProtector.Unprotect(setupToken); if (payload is null) { _logger.LogWarning("MFA setup confirm rejected: invalid or expired setup token (userId={UserId})", userId); return null; } // Bind: token must match caller userId AND method. if (payload.UserId != userId || !string.Equals(payload.MethodId, methodId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning( "MFA setup confirm rejected: token/caller mismatch (userId={UserId}, tokenUserId={TokenUserId}, method={Method}, tokenMethod={TokenMethod})", userId, payload.UserId, methodId, payload.MethodId); return null; } // E-mail: the code must be the one sent for THIS setup token (to the candidate address), not a sign-in // code sent to the confirmed one. SMS keeps its rule unchanged. if (string.Equals(methodId, "email", StringComparison.OrdinalIgnoreCase) && (state?.SetupJti is not { } stateSetupJti || stateSetupJti != payload.Jti)) { _logger.LogWarning("MFA setup confirm rejected: the code was not sent for this setup token (userId={UserId}, method={Method})", userId, methodId); return null; } var initiation = new MfaSetupInitiation { MethodId = payload.MethodId, EncryptedSecret = payload.EncryptedSecret, Destination = payload.Destination, ClientResult = new MfaSetupResult { MethodId = payload.MethodId } }; var swLoad = System.Diagnostics.Stopwatch.StartNew(); var obj = await LoadOrCreateMfaPropsAsync(userId, ct).ConfigureAwait(false); swLoad.Stop(); var swVerify = System.Diagnostics.Stopwatch.StartNew(); if (!await method.ConfirmAndApplyAsync(obj.Props, initiation, code, state, ct).ConfigureAwait(false)) return null; swVerify.Stop(); var wasAlreadyEnabled = obj.Props.Enabled; obj.Props.Enabled = true; if (string.IsNullOrEmpty(obj.Props.DefaultMethod)) obj.Props.DefaultMethod = methodId; string[] plainCodes; var swHash = System.Diagnostics.Stopwatch.StartNew(); if (!wasAlreadyEnabled || obj.Props.RecoveryCodes is null or { Count: 0 }) { var (codes, hashedCodes) = GenerateRecoveryCodes(); obj.Props.RecoveryCodes = hashedCodes; obj.Props.RecoveryCodesPepperId = _pepperProvider.PepperId; plainCodes = codes; } else { // Adding a 2nd method — keep existing recovery codes; client should call regenerate to get new ones if desired. plainCodes = []; } swHash.Stop(); obj.Props.FailedAttempts = 0; obj.Props.LockedUntil = null; var swSave = System.Diagnostics.Stopwatch.StartNew(); await _redb.SaveAsync(obj).ConfigureAwait(false); swSave.Stop(); swTotal.Stop(); _logger.LogDebug( "MFA_CONFIRM_TIMING load={LoadMs}ms verify={VerifyMs}ms hashCodes={HashMs}ms save={SaveMs}ms total={TotalMs}ms userId={UserId} method={Method} freshCodes={FreshCodes}", swLoad.ElapsedMilliseconds, swVerify.ElapsedMilliseconds, swHash.ElapsedMilliseconds, swSave.ElapsedMilliseconds, swTotal.ElapsedMilliseconds, userId, methodId, plainCodes.Length); _logger.LogDebug("MFA setup confirmed: userId={UserId}, method={Method}", userId, methodId); return plainCodes; } /// /// Verifies an MFA code during login. Enforces lockout after too many failures. /// /// Decrypted MFA state for SMS/Email; null for TOTP. public async Task VerifyAsync(long userId, string methodId, string code, MfaState? state = null, CancellationToken ct = default) { // Cross-check: caller must pass userId that matches the encrypted state. // Defence-in-depth against caller bugs that mix up identities between login and verify. if (state is not null && state.UserId != userId) { _securityLogger.LogWarning("MFA verify rejected (state.UserId != userId): caller={UserId}, state={StateUserId}", userId, state.UserId); return false; } var method = GetMethod(methodId); var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj is null) return false; var props = obj.Props; // Check lockout (with clock skew tolerance — B9 / BUG-5). if (IsLockedOut(props)) { _securityLogger.LogWarning("MFA verify rejected (locked out): userId={UserId}", userId); return false; } if (await method.VerifyAsync(props, code, state, ct).ConfigureAwait(false)) { props.FailedAttempts = 0; props.LockedUntil = null; props.LastVerifiedAt = _timeProvider.GetUtcNow(); await _redb.SaveAsync(obj).ConfigureAwait(false); return true; } // Failed attempt props.FailedAttempts++; if (props.FailedAttempts >= _maxFailedAttempts) { props.LockedUntil = _timeProvider.GetUtcNow() + _lockoutDuration; _securityLogger.LogWarning("MFA lockout activated: userId={UserId}, attempts={Attempts}", userId, props.FailedAttempts); } await _redb.SaveAsync(obj).ConfigureAwait(false); return false; } /// /// Verifies a one-time recovery code. The code is consumed (removed) on success. /// Failed attempts increment and trigger lockout, /// matching the protection given to TOTP/SMS/Email. /// public async Task VerifyRecoveryCodeAsync(long userId, string code, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj is null) return false; var props = obj.Props; // Honour lockout — recovery codes are not a bypass for brute-force protection. if (IsLockedOut(props)) { _securityLogger.LogWarning("MFA recovery rejected (locked out): userId={UserId}", userId); return false; } if (props.RecoveryCodes is { Count: > 0 }) { // Constant-time scan over all unconsumed codes. // Iterate the full list even after a match to avoid leaking match-position via timing. var matchIndex = -1; bool needsRehash = false; var peppers = _pepperProvider.PeppersFor(props.RecoveryCodesPepperId); if (peppers.Count == 0) _securityLogger.LogWarning( "MFA recovery codes were hashed with pepper {PepperId}, which is no longer configured.", props.RecoveryCodesPepperId); for (int i = 0; i < props.RecoveryCodes.Count; i++) { var stored = props.RecoveryCodes[i]; bool isMatch = VerifyRecoveryCodeHash(stored, code, peppers, out var legacy); if (isMatch && matchIndex < 0) { matchIndex = i; needsRehash = legacy; } } if (matchIndex >= 0) { props.RecoveryCodes.RemoveAt(matchIndex); if (needsRehash) { _logger.LogDebug( "MFA recovery code consumed in legacy SHA-256 format (no rehash on used code): userId={UserId}", userId); } props.FailedAttempts = 0; props.LockedUntil = null; props.LastVerifiedAt = _timeProvider.GetUtcNow(); await _redb.SaveAsync(obj).ConfigureAwait(false); _logger.LogDebug("MFA recovery code used: userId={UserId}, remaining={Remaining}", userId, props.RecoveryCodes.Count); return true; } } // Wrong code — count it the same way as a failed TOTP attempt. props.FailedAttempts++; if (props.FailedAttempts >= _maxFailedAttempts) { props.LockedUntil = _timeProvider.GetUtcNow() + _lockoutDuration; _securityLogger.LogWarning("MFA lockout activated via recovery: userId={UserId}, attempts={Attempts}", userId, props.FailedAttempts); } await _redb.SaveAsync(obj).ConfigureAwait(false); return false; } /// Disables a specific MFA method for the user. public async Task DisableAsync(long userId, string methodId, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj is null) return; switch (methodId.ToLowerInvariant()) { case "totp": obj.Props.TotpSecret = null; obj.Props.TotpConfirmed = false; break; case "sms": obj.Props.SmsPhone = null; obj.Props.SmsConfirmed = false; break; case "email": obj.Props.OtpEmail = null; obj.Props.EmailConfirmed = false; break; } // If no methods remain confirmed — disable MFA entirely. var anyConfirmed = obj.Props.TotpConfirmed || obj.Props.SmsConfirmed || obj.Props.EmailConfirmed; if (!anyConfirmed) { obj.Props.Enabled = false; obj.Props.DefaultMethod = null; // B9 / BUG-8: archive the recovery hashes instead of nulling them out, so an // admin can audit «which codes were active when MFA was disabled?». The archived // hashes are NEVER consulted by VerifyRecoveryCodeAsync (see ArchivedRecoveryCodes // doc) so this does not weaken the revocation guarantee. ArchiveRecoveryCodes(obj.Props, reason: "disable"); obj.Props.RecoveryCodes = null; obj.Props.RecoveryCodesPepperId = null; } else if (string.Equals(obj.Props.DefaultMethod, methodId, StringComparison.OrdinalIgnoreCase)) { // Pick a new default — prefer TOTP > SMS > Email obj.Props.DefaultMethod = obj.Props.TotpConfirmed ? "totp" : obj.Props.SmsConfirmed ? "sms" : "email"; } obj.Props.FailedAttempts = 0; obj.Props.LockedUntil = null; await _redb.SaveAsync(obj).ConfigureAwait(false); _logger.LogDebug("MFA disabled: userId={UserId}, method={Method}", userId, methodId); } /// Returns MFA status for the user: enabled, methods, recovery codes remaining. public async Task GetStatusAsync(long userId, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj?.Props is not { } props) return new MfaStatusResult { Enabled = false, Methods = [], RecoveryCodesRemaining = 0 }; var methods = new List(); if (props.TotpConfirmed) methods.Add("totp"); if (props.SmsConfirmed && !string.IsNullOrEmpty(props.SmsPhone)) methods.Add("sms"); if (props.EmailConfirmed && !string.IsNullOrEmpty(props.OtpEmail)) methods.Add("email"); return new MfaStatusResult { Enabled = props.Enabled, Methods = methods.ToArray(), RecoveryCodesRemaining = props.RecoveryCodes?.Count ?? 0 }; } /// Regenerates recovery codes. Old codes are invalidated. public async Task RegenerateRecoveryCodesAsync(long userId, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj?.Props is not { Enabled: true }) return null; var (plainCodes, hashedCodes) = GenerateRecoveryCodes(); // B9 / BUG-8: archive the previous batch before overwriting. ArchiveRecoveryCodes(obj.Props, reason: "regenerate"); obj.Props.RecoveryCodes = hashedCodes; obj.Props.RecoveryCodesPepperId = _pepperProvider.PepperId; await _redb.SaveAsync(obj).ConfigureAwait(false); _logger.LogDebug("MFA recovery codes regenerated: userId={UserId}", userId); return plainCodes; } /// Encrypts MFA state for the challenge flow (password verified → awaiting MFA code). public string ProtectState(MfaState state) => _stateProtector.Protect(state); /// Decrypts and validates MFA state. Returns null if invalid/expired. public MfaState? UnprotectState(string protectedState) => _stateProtector.Unprotect(protectedState); /// /// Generates a fresh OTP code for SMS/Email, dispatches it via the matching delivery channel, /// updates rate-limit counters, and returns a new encrypted MFA state with the code embedded. /// public async Task CreateChallengeAsync( long userId, string username, string methodId, string? returnUrl, CancellationToken ct = default) => await CreateChallengeAsync(userId, username, methodId, returnUrl, knownMethods: null, ct).ConfigureAwait(false); /// /// Overload that lets callers reuse the methods array from the original MFA state, avoiding /// an extra DB roundtrip when the list has not changed. /// public async Task CreateChallengeAsync( long userId, string username, string methodId, string? returnUrl, string[]? knownMethods, CancellationToken ct = default) { if (methodId != "sms" && methodId != "email") return MfaChallengeResult.Failed("method_not_challengeable"); var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj?.Props is not { Enabled: true } props) return MfaChallengeResult.Failed("mfa_not_enabled"); // Determine destination string? destination = methodId == "sms" ? props.SmsPhone : props.OtpEmail; var confirmed = methodId == "sms" ? props.SmsConfirmed : props.EmailConfirmed; if (string.IsNullOrEmpty(destination) || !confirmed) return MfaChallengeResult.Failed("method_not_configured"); // Channel must be registered (host app must wire up SMS/Email senders) if (!_channels.TryGetValue(methodId, out var channel)) return MfaChallengeResult.Failed("no_channel"); // Rate limit check var rateLimit = CheckOtpRateLimit(props); if (rateLimit > 0) { _securityLogger.LogWarning("MFA challenge rate-limited: userId={UserId}, retryAfter={RetryAfter}s", userId, rateLimit); return MfaChallengeResult.Failed("rate_limited", rateLimit); } // Reserve the rate-limit slot BEFORE attempting delivery — otherwise an attacker could // spam SMS/email indefinitely as long as the upstream provider keeps returning errors. // The slot is consumed on delivery attempt, success or failure alike. UpdateOtpRateLimitCounters(props); await _redb.SaveAsync(obj).ConfigureAwait(false); var masked = methodId == "sms" ? SmsMfaMethod.MaskPhone(destination) : EmailMfaMethod.MaskEmail(destination); // B3: server-side OTP store. The plaintext code lives only between issue & delivery; // the state blob carries just a `jti` reference, so the code never appears in URLs, // Referer headers, HTTP access logs or the encrypted state cookie content. Guid jti; string code; DateTimeOffset expiresAt; if (_otpStore is not null) { var ttl = TimeSpan.FromMinutes(5); var issued = await _otpStore.IssueAsync(userId, methodId, masked, ttl, ct).ConfigureAwait(false); jti = issued.Jti; code = issued.PlaintextCode; expiresAt = issued.ExpiresAt; } else { // Fallback for legacy tests that don't register IServerSideOtpStore — still OK because // the per-method verify path checks state.OtpMethod+state.OtpJti first; legacy path // uses Jti as a dummy handle and VerifyAndConsume is bypassed. jti = Guid.NewGuid(); code = GenerateOtpCode(); expiresAt = _timeProvider.GetUtcNow() + TimeSpan.FromMinutes(5); } try { await channel.SendCodeAsync(destination, code, ct).ConfigureAwait(false); } catch (MfaDeliveryException ex) { _logger.LogError(ex, "MFA delivery failed: userId={UserId}, channel={Channel}", userId, methodId); return MfaChallengeResult.Failed("delivery_failed"); } catch (Exception ex) { _logger.LogError(ex, "MFA delivery exception: userId={UserId}, channel={Channel}", userId, methodId); return MfaChallengeResult.Failed("delivery_failed"); } // Reuse knownMethods if provided (saves a DB roundtrip when called from MfaChallengeProcessor // where the original state already carries the method list). var methods = knownMethods ?? CollectEnabledMethods(props); var newState = new MfaState { Jti = Guid.NewGuid(), UserId = userId, Username = username, Methods = methods, ReturnUrl = returnUrl, OtpJti = jti, OtpDestination = masked, OtpMethod = methodId, OtpExpiresAt = expiresAt, }; var protectedState = _stateProtector.Protect(newState); _logger.LogDebug("MFA challenge sent: userId={UserId}, method={Method}", userId, methodId); return MfaChallengeResult.Ok(methodId, protectedState, masked); } /// Returns the registered by id (public for processors). public IMfaMethod GetRegisteredMethod(string methodId) => GetMethod(methodId); /// Loads MFA props for a user (public so processors can read state for verify). public async Task LoadPropsAsync(long userId, CancellationToken ct = default) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); return obj?.Props; } // --- Private helpers --- private IMfaMethod GetMethod(string methodId) { if (_methods.TryGetValue(methodId, out var method)) return method; throw new ArgumentException($"Unknown MFA method: {methodId}", nameof(methodId)); } private async Task?> LoadMfaPropsAsync(long userId, CancellationToken _) { return await _redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync().ConfigureAwait(false); } /// /// Returns the redb-object id of the MFA props row for , or 0 if none. /// Used by callers (e.g. ) to acquire a row-level /// SELECT ... FOR UPDATE lock via before invoking /// — serializes concurrent verify attempts and prevents lost-update on /// / . /// internal async Task GetMfaObjectIdAsync(long userId, CancellationToken _) { return await _redb.Query() .WhereRedb(o => o.Key == userId) .Select(o => o.id) .FirstOrDefaultAsync().ConfigureAwait(false); } private async Task> LoadOrCreateMfaPropsAsync(long userId, CancellationToken ct) { var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false); if (obj is not null) return obj; obj = new RedbObject(new MfaProps { UserId = userId }); obj.key = userId; return obj; } private (string[] plain, List hashed) GenerateRecoveryCodes() { // Alphabet without ambiguous chars (0/O, 1/I/l) const string alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; var plain = new string[_recoveryCodeCount]; var hashed = new string[_recoveryCodeCount]; // Generate plaintext codes serially — UnbiasedRandom uses RandomNumberGenerator.Fill // on a stackalloc'd byte, which is cheap; the dominant cost is PBKDF2 below. for (int i = 0; i < _recoveryCodeCount; i++) plain[i] = GenerateSingleCode(alphabet); // PBKDF2 is CPU-bound per code (~80–100ms each at production iteration counts). // 10 codes × 90ms ≈ 900ms serially. Parallel.For distributes across cores; each // HashCode invocation is independent (its own salt + buffers), so no synchronisation // is required. Plain[] / hashed[] are written to disjoint indices. Parallel.For(0, _recoveryCodeCount, i => { hashed[i] = HashCode(plain[i]); }); return (plain, hashed.ToList()); } /// /// B9 / BUG-5 helper. Returns whether the user is currently inside the lockout window, /// applying to bias the comparison /// toward «still locked» when clocks may be slightly out of sync. /// private bool IsLockedOut(MfaProps props) { if (!props.LockedUntil.HasValue) return false; var now = _timeProvider.GetUtcNow(); return now < props.LockedUntil.Value + _options.MfaLockoutClockSkew; } /// /// B9 / BUG-8 helper. Moves the current into /// with a timestamp + reason. Caller is /// responsible for clearing RecoveryCodes afterwards. /// private void ArchiveRecoveryCodes(MfaProps props, string reason) { if (props.RecoveryCodes is not { Count: > 0 } codes) return; props.ArchivedRecoveryCodes ??= new List(); props.ArchivedRecoveryCodes.Add(new MfaArchivedRecoveryCodeBatch { ArchivedAt = _timeProvider.GetUtcNow(), Reason = reason, HashedCodes = new List(codes) }); } private static string GenerateSingleCode(string alphabet) { // Format: XXXX-XXXX (8 chars + dash) // Use rejection sampling to avoid modulo bias (alphabet.Length=31, 256%31≠0) var sb = new StringBuilder(9); for (int i = 0; i < 8; i++) { if (i == 4) sb.Append('-'); sb.Append(alphabet[UnbiasedRandom(alphabet.Length)]); } return sb.ToString(); } private static int UnbiasedRandom(int range) { // Rejection sampling: discard values >= largest multiple of range that fits in a byte int limit = 256 - (256 % range); Span buf = stackalloc byte[1]; int value; do { RandomNumberGenerator.Fill(buf); value = buf[0]; } while (value >= limit); return value % range; } private string HashCode(string code) { // PBKDF2-HMAC-SHA256(password = normalized_code || pepper, salt = per-code random 16B, // iterations = configured work-factor, length = 32B). Format string embeds iteration count // so future work-factor increases verify side-by-side. var normalized = NormalizeRecoveryCode(code); var salt = RandomNumberGenerator.GetBytes(16); var iterations = _options.RecoveryCodePbkdf2Iterations; var hash = Pbkdf2Hash(normalized, salt, iterations, _pepperProvider.Pepper); return string.Concat( "pbkdf2$", iterations.ToString(System.Globalization.CultureInfo.InvariantCulture), "$", Convert.ToBase64String(salt), "$", Convert.ToBase64String(hash)); } /// /// Returns true if matches the stored hash. /// Sets = true when the stored hash is the pre-B4 SHA-256 hex /// representation (so the caller can log a migration event). Always uses constant-time /// comparison on the byte representation. A PBKDF2 hash is checked with each of /// (the set's own pepper, or for a set without a pepper id the current /// one and then the previous ones); none matches when the list is empty. /// private bool VerifyRecoveryCodeHash(string stored, string presentedCode, IReadOnlyList peppers, out bool legacyFormat) { legacyFormat = false; var normalized = NormalizeRecoveryCode(presentedCode); if (stored.StartsWith("pbkdf2$", StringComparison.Ordinal)) { var parts = stored.Split('$'); if (parts.Length != 4) return false; if (!int.TryParse(parts[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var iterations) || iterations <= 0) return false; byte[] salt, expected; try { salt = Convert.FromBase64String(parts[2]); expected = Convert.FromBase64String(parts[3]); } catch (FormatException) { return false; } var match = false; foreach (var pepper in peppers) match |= CryptographicOperations.FixedTimeEquals(Pbkdf2Hash(normalized, salt, iterations, pepper, expected.Length), expected); return match; } // Legacy format: hex-encoded SHA-256 of the normalized code (no salt, no pepper). legacyFormat = true; var legacyExpected = SHA256.HashData(Encoding.UTF8.GetBytes(normalized)); // Compare to the stored hex string after decoding back to bytes (constant-time on bytes). if (stored.Length != legacyExpected.Length * 2) return false; byte[] storedBytes; try { storedBytes = Convert.FromHexString(stored); } catch (FormatException) { return false; } return CryptographicOperations.FixedTimeEquals(storedBytes, legacyExpected); } private static byte[] Pbkdf2Hash(string normalizedCode, byte[] salt, int iterations, byte[] pepper, int outputLength = 32) { var codeBytes = Encoding.UTF8.GetBytes(normalizedCode); var pwd = new byte[codeBytes.Length + pepper.Length]; Buffer.BlockCopy(codeBytes, 0, pwd, 0, codeBytes.Length); Buffer.BlockCopy(pepper, 0, pwd, codeBytes.Length, pepper.Length); try { return Rfc2898DeriveBytes.Pbkdf2(pwd, salt, iterations, HashAlgorithmName.SHA256, outputLength); } finally { CryptographicOperations.ZeroMemory(pwd); } } private static string NormalizeRecoveryCode(string code) => code.Replace("-", "", StringComparison.Ordinal).ToUpperInvariant(); /// /// Returns the number of seconds until the next OTP can be sent, or 0 if allowed now. /// Combines per-send cooldown and a sliding-window per-hour quota (B6). /// private int CheckOtpRateLimit(MfaProps props) { var now = _timeProvider.GetUtcNow(); // Cooldown if (props.LastOtpSentAt is { } last) { var elapsed = now - last; if (elapsed < _options.OtpCooldown) { var remaining = (int)Math.Ceiling((_options.OtpCooldown - elapsed).TotalSeconds); return Math.Max(remaining, 1); } } // Sliding-window hourly quota var timestamps = props.RecentOtpTimestamps; if (timestamps is null || timestamps.Count == 0) return 0; var cutoff = now.ToUnixTimeSeconds() - (long)OtpRateLimitWindow.TotalSeconds; // Count entries still within the window (do not mutate here — mutation happens in // UpdateOtpRateLimitCounters under the same row lock). var insideWindow = 0; var oldestInside = long.MaxValue; foreach (var ts in timestamps) { if (ts > cutoff) { insideWindow++; if (ts < oldestInside) oldestInside = ts; } } if (insideWindow < _options.OtpMaxPerHour) return 0; // Quota reached — caller must wait until the oldest in-window entry leaves the window. var nextSlotUnix = oldestInside + (long)OtpRateLimitWindow.TotalSeconds; var waitSeconds = (int)(nextSlotUnix - now.ToUnixTimeSeconds()); return Math.Max(waitSeconds, 1); } private void UpdateOtpRateLimitCounters(MfaProps props) { var now = _timeProvider.GetUtcNow(); var nowUnix = now.ToUnixTimeSeconds(); var cutoff = nowUnix - (long)OtpRateLimitWindow.TotalSeconds; // Prune expired timestamps in-place; allocate a fresh list if none yet. var timestamps = props.RecentOtpTimestamps; if (timestamps is null) { timestamps = new List(4); props.RecentOtpTimestamps = timestamps; } else { timestamps.RemoveAll(ts => ts <= cutoff); } timestamps.Add(nowUnix); // Cap list size to bound storage. Drop oldest entries first. if (timestamps.Count > RecentOtpTimestampsCap) { timestamps.RemoveRange(0, timestamps.Count - RecentOtpTimestampsCap); } props.LastOtpSentAt = now; } /// Generates a 6-digit OTP code using cryptographic RNG. internal static string GenerateOtpCode() { Span buf = stackalloc byte[4]; RandomNumberGenerator.Fill(buf); var n = BitConverter.ToUInt32(buf) % 1_000_000u; return n.ToString("D6", System.Globalization.CultureInfo.InvariantCulture); } } Path: redb-identity/src/redb.Identity.Core/Services/MfaSetupInitiation.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/Services/MfaSetupInitiation.cs ---- using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Pure setup data returned by . /// Captures everything the orchestrator needs to (a) hand a setup_token back to the /// client and (b) reconstruct + apply the secret on confirm — without mutating /// first. This is the B5 fix for the "two parallel setups /// race-overwrite the secret" bug. /// public sealed record MfaSetupInitiation { public required string MethodId { get; init; } /// /// Method-private secret to be persisted on confirm. For TOTP this is the encrypted /// (DataProtection-protected) base32 shared secret; for WebAuthn it would be the /// credential id payload. Null for methods that don't carry a secret (SMS/Email). /// public string? EncryptedSecret { get; init; } /// Destination such as phone or email. Null for TOTP. public string? Destination { get; init; } /// Client-facing setup data (QR URI, masked destination, errors, etc.). public required MfaSetupResult ClientResult { get; init; } } Path: redb-identity/src/redb.Identity.Core/Services/MfaSetupTokenProtector.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/Services/MfaSetupTokenProtector.cs ---- using System.Text.Json; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging; using redb.Identity.Core.Models; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Services; /// /// Encrypts/decrypts an MFA setup token (B5). The setup token carries the candidate /// secret/destination for an in-progress MFA setup so that the secret is NEVER persisted /// to until the user proves possession by submitting a valid code /// during confirm. /// /// Uses ASP.NET DataProtection with a dedicated purpose so leaks across MFA-state / /// MFA-secret protectors are impossible. Default TTL is 10 minutes. /// public sealed class MfaSetupTokenProtector { private const string Purpose = "redb.identity.mfa-setup.v1"; private static readonly TimeSpan DefaultMaxAge = TimeSpan.FromMinutes(10); private readonly IDataProtector _protector; private readonly TimeProvider _timeProvider; private readonly ILogger? _logger; public MfaSetupTokenProtector(IDataProtectionProvider provider) : this(provider, TimeProvider.System, null) { } public MfaSetupTokenProtector(IDataProtectionProvider provider, TimeProvider? timeProvider) : this(provider, timeProvider, null) { } public MfaSetupTokenProtector( IDataProtectionProvider provider, TimeProvider? timeProvider, ILogger? logger) { ArgumentNullException.ThrowIfNull(provider); _protector = provider.CreateProtector(Purpose); _timeProvider = timeProvider ?? TimeProvider.System; _logger = logger; } public string Protect(MfaSetupTokenPayload payload) { ArgumentNullException.ThrowIfNull(payload); if (payload.IssuedAt == default) payload.IssuedAt = _timeProvider.GetUtcNow(); if (payload.Jti == Guid.Empty) payload.Jti = Guid.NewGuid(); var json = JsonSerializer.SerializeToUtf8Bytes(payload); var encrypted = _protector.Protect(json); return Convert.ToBase64String(encrypted); } /// /// Returns the decrypted payload or null if tampered, malformed, expired, or older than /// (defaults to 10 minutes). /// public MfaSetupTokenPayload? Unprotect(string token, TimeSpan? maxAge = null) { if (string.IsNullOrEmpty(token)) return null; try { var bytes = Base64Canonical.Decode(token); var json = _protector.Unprotect(bytes); var payload = JsonSerializer.Deserialize(json); if (payload is null || payload.UserId <= 0 || string.IsNullOrEmpty(payload.MethodId)) { _logger?.LogWarning( "MfaSetupTokenProtector: decrypted payload was null or had invalid UserId/MethodId."); return null; } var age = _timeProvider.GetUtcNow() - payload.IssuedAt; if (age > (maxAge ?? DefaultMaxAge)) { _logger?.LogDebug( "MfaSetupTokenProtector: setup token expired (age={AgeSeconds}s, max={MaxSeconds}s).", age.TotalSeconds, (maxAge ?? DefaultMaxAge).TotalSeconds); return null; } return payload; } catch (Exception ex) { // Tampering or DataProtection key rotation. Public contract preserved (null). _logger?.LogWarning(ex, "MfaSetupTokenProtector: failed to decrypt setup token (length={Length}).", token.Length); return null; } } } Path: redb-identity/src/redb.Identity.Core/Services/MfaStateProtector.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/Services/MfaStateProtector.cs ---- using System.Text.Json; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging; using redb.Identity.Contracts.Mfa; using redb.Identity.Core.Models; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Services; /// /// Encrypts/decrypts temporary MFA state using ASP.NET DataProtection with TTL enforcement. /// Same pattern as but for the MFA challenge flow. /// /// Also implements — a minimal read-only surface in /// redb.Identity.Contracts that transport facades (HTTP, gRPC, …) consume to render /// MFA-method selectors without taking a project-reference on Core. /// /// public sealed class MfaStateProtector : IMfaStateInspector { private const string Purpose = "redb.identity.mfa-state"; private static readonly TimeSpan DefaultMaxAge = TimeSpan.FromMinutes(5); private readonly IDataProtector _protector; private readonly TimeProvider _timeProvider; private readonly ILogger? _logger; public MfaStateProtector(IDataProtectionProvider provider) : this(provider, TimeProvider.System, null) { } public MfaStateProtector(IDataProtectionProvider provider, TimeProvider? timeProvider) : this(provider, timeProvider, null) { } public MfaStateProtector( IDataProtectionProvider provider, TimeProvider? timeProvider, ILogger? logger) { ArgumentNullException.ThrowIfNull(provider); _protector = provider.CreateProtector(Purpose); _timeProvider = timeProvider ?? TimeProvider.System; _logger = logger; } /// Encrypts MFA state into a base64 string for use as a hidden form field or query parameter. public string Protect(MfaState state) { ArgumentNullException.ThrowIfNull(state); state.IssuedAt ??= _timeProvider.GetUtcNow(); var json = JsonSerializer.SerializeToUtf8Bytes(state); var encrypted = _protector.Protect(json); return Convert.ToBase64String(encrypted); } /// /// Decrypts and validates MFA state. Returns null if invalid, tampered, or expired. /// public MfaState? Unprotect(string protectedState, TimeSpan? maxAge = null) { if (string.IsNullOrEmpty(protectedState)) return null; try { var encrypted = Base64Canonical.Decode(protectedState); var json = _protector.Unprotect(encrypted); var state = JsonSerializer.Deserialize(json); if (state is null || state.UserId <= 0) { _logger?.LogWarning( "MfaStateProtector: decrypted state was null or had invalid UserId."); return null; } var age = _timeProvider.GetUtcNow() - (state.IssuedAt ?? DateTimeOffset.MinValue); if (age > (maxAge ?? DefaultMaxAge)) { _logger?.LogDebug( "MfaStateProtector: state expired (age={AgeSeconds}s, max={MaxSeconds}s).", age.TotalSeconds, (maxAge ?? DefaultMaxAge).TotalSeconds); return null; } return state; } catch (Exception ex) { // Tampering or DataProtection key rotation. Public contract preserved (null). _logger?.LogWarning(ex, "MfaStateProtector: failed to decrypt MFA state (length={Length}).", protectedState.Length); return null; } } /// string[]? IMfaStateInspector.TryGetMethods(string? protectedState) { if (string.IsNullOrEmpty(protectedState)) return null; var state = Unprotect(protectedState); return state?.Methods; } } Path: redb-identity/src/redb.Identity.Core/Services/OidcFederatedAuthProvider.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/Services/OidcFederatedAuthProvider.cs ---- using System.Net.Http.Json; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; using redb.Identity.Core.Configuration; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Core.Services; /// /// Generic OIDC Relying Party — works with any IdP that exposes /// .well-known/openid-configuration (Google, Azure AD, Keycloak, etc.). /// Uses PKCE (S256), validates id_token signature + claims. /// public sealed class OidcFederatedAuthProvider : IFederatedAuthProvider { private readonly FederationProviderConfig _config; private readonly IHttpClientFactory _httpClientFactory; private readonly ConfigurationManager _configManager; private static readonly JsonWebTokenHandler _tokenHandler = new(); public OidcFederatedAuthProvider( FederationProviderConfig config, IHttpClientFactory httpClientFactory) { _config = config ?? throw new ArgumentNullException(nameof(config)); _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); var metadataAddress = config.Authority.TrimEnd('/') + "/.well-known/openid-configuration"; _configManager = new ConfigurationManager( metadataAddress, new OpenIdConnectConfigurationRetriever(), new HttpDocumentRetriever(_httpClientFactory.CreateClient("redb-identity-federation")) { RequireHttps = config.Authority.StartsWith("https://", StringComparison.OrdinalIgnoreCase) }); } public string ProviderId => _config.ProviderId; public string DisplayName => _config.DisplayName; public int Priority => _config.Priority; public async Task CreateChallengeAsync( string callbackUrl, string returnUrl, CancellationToken ct = default) { var disco = await _configManager.GetConfigurationAsync(ct).ConfigureAwait(false); // PKCE S256 var codeVerifier = GenerateCodeVerifier(); var codeChallenge = ComputeCodeChallenge(codeVerifier); var nonce = GenerateNonce(); var state = GenerateNonce(); // opaque, the caller wraps it with DataProtection var authUrl = disco.AuthorizationEndpoint + "?response_type=code" + "&client_id=" + Uri.EscapeDataString(_config.ClientId) + "&redirect_uri=" + Uri.EscapeDataString(callbackUrl) + "&scope=" + Uri.EscapeDataString(string.Join(" ", _config.Scopes)) + "&state=" + Uri.EscapeDataString(state) + "&nonce=" + Uri.EscapeDataString(nonce) + "&code_challenge=" + Uri.EscapeDataString(codeChallenge) + "&code_challenge_method=S256"; return new FederationChallenge { RedirectUri = authUrl, State = state, Nonce = nonce, CodeVerifier = codeVerifier }; } public async Task HandleCallbackAsync( string code, string callbackUrl, string? codeVerifier = null, string? nonce = null, CancellationToken ct = default) { var disco = await _configManager.GetConfigurationAsync(ct).ConfigureAwait(false); // Exchange authorization code for tokens var tokenResponse = await ExchangeCodeAsync(disco.TokenEndpoint, code, callbackUrl, codeVerifier, ct) .ConfigureAwait(false); if (tokenResponse is null || string.IsNullOrEmpty(tokenResponse.id_token)) return ExternalAuthResult.Failed("Token exchange failed or no id_token received."); // Validate id_token var validationResult = await ValidateIdTokenAsync(tokenResponse.id_token, disco, nonce, ct) .ConfigureAwait(false); if (!validationResult.IsValid) return ExternalAuthResult.Failed($"id_token validation failed: {validationResult.Exception?.Message}"); var claims = validationResult.ClaimsIdentity; var sub = claims.FindFirst("sub")?.Value; if (string.IsNullOrEmpty(sub)) return ExternalAuthResult.Failed("id_token missing 'sub' claim."); return ExternalAuthResult.Success( externalId: sub, displayName: claims.FindFirst("name")?.Value, email: claims.FindFirst("email")?.Value, givenName: claims.FindFirst("given_name")?.Value, familyName: claims.FindFirst("family_name")?.Value); } private async Task ExchangeCodeAsync( string tokenEndpoint, string code, string callbackUrl, string? codeVerifier, CancellationToken ct) { using var client = _httpClientFactory.CreateClient("redb-identity-federation"); var parameters = new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = callbackUrl, ["client_id"] = _config.ClientId, ["client_secret"] = _config.ClientSecret }; if (!string.IsNullOrEmpty(codeVerifier)) parameters["code_verifier"] = codeVerifier; using var content = new FormUrlEncodedContent(parameters); using var response = await client.PostAsync(tokenEndpoint, content, ct).ConfigureAwait(false); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(ct).ConfigureAwait(false); } private async Task ValidateIdTokenAsync( string idToken, OpenIdConnectConfiguration disco, string? expectedNonce, CancellationToken ct) { var validationParams = new TokenValidationParameters { ValidIssuer = _config.Authority.TrimEnd('/'), ValidAudience = _config.ClientId, IssuerSigningKeys = disco.SigningKeys, ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(5) }; var result = await _tokenHandler.ValidateTokenAsync(idToken, validationParams).ConfigureAwait(false); // Validate nonce if provided if (result.IsValid && !string.IsNullOrEmpty(expectedNonce)) { var tokenNonce = result.ClaimsIdentity.FindFirst("nonce")?.Value; if (tokenNonce != expectedNonce) { return new TokenValidationResult { IsValid = false, Exception = new SecurityTokenValidationException("Nonce mismatch in id_token.") }; } } return result; } // PKCE helpers private static string GenerateCodeVerifier() { var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); return Base64UrlEncoder.Encode(bytes); } private static string ComputeCodeChallenge(string codeVerifier) { var bytes = SHA256.HashData(Encoding.ASCII.GetBytes(codeVerifier)); return Base64UrlEncoder.Encode(bytes); } private static string GenerateNonce() { var bytes = new byte[16]; RandomNumberGenerator.Fill(bytes); return Base64UrlEncoder.Encode(bytes); } private sealed class TokenResponse { public string? access_token { get; set; } public string? id_token { get; set; } public string? token_type { get; set; } public int expires_in { get; set; } } } Path: redb-identity/src/redb.Identity.Core/Services/OutboundUrlGuard.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/Services/OutboundUrlGuard.cs ---- using System.Net; using System.Net.Sockets; namespace redb.Identity.Core.Services; /// /// Decides whether the server may make an outbound HTTP request to a URL that came from /// outside — a client's jwks_uri, a JAR request_uri, a webhook target. /// /// Such a URL is attacker-influenced input. Fetching it unchecked turns the server into a proxy /// into its own network (SSRF): http://127.0.0.1:9090/admin, http://10.0.0.5/, or /// the cloud metadata service at 169.254.169.254, which hands out instance credentials to /// whoever can reach it. The server is inside the perimeter; the caller is not. /// /// internal static class OutboundUrlGuard { /// Why a URL was rejected. means it passed. internal enum Rejection { None, NotAbsolute, SchemeNotAllowed, HttpsRequired, HostUnresolvable, PrivateNetworkTarget, } /// /// Validates the URL's shape (absolute, allowed scheme) without touching the network. /// internal static Rejection ValidateShape(string? url, bool requireHttps, out Uri? uri) { uri = null; if (string.IsNullOrWhiteSpace(url)) return Rejection.NotAbsolute; if (!Uri.TryCreate(url, UriKind.Absolute, out var parsed)) return Rejection.NotAbsolute; if (parsed.Scheme != Uri.UriSchemeHttps && parsed.Scheme != Uri.UriSchemeHttp) return Rejection.SchemeNotAllowed; if (requireHttps && parsed.Scheme != Uri.UriSchemeHttps) return Rejection.HttpsRequired; uri = parsed; return Rejection.None; } /// /// Full check: shape, then DNS resolution, then every resolved address against the /// non-public ranges. Rejects when any resolved address is non-public — a name that /// answers with both a public and a private address must not slip through on the public one. /// /// /// This cannot close DNS rebinding on its own: the name is resolved here and again by the /// HTTP stack, and the answer may differ between the two. Closing that hole means pinning the /// validated address for the actual connection. The check still removes the whole class of /// trivially-internal targets, which is what an operator pasting an internal URL — or an /// attacker with write access to a client record — would reach for first. /// internal static async ValueTask ValidateAsync( string? url, bool requireHttps, bool allowPrivateNetworkTargets, CancellationToken cancellationToken = default) { var shape = ValidateShape(url, requireHttps, out var uri); if (shape != Rejection.None || uri is null) return shape; if (allowPrivateNetworkTargets) return Rejection.None; IPAddress[] addresses; if (IPAddress.TryParse(uri.Host, out var literal)) { addresses = [literal]; } else { try { addresses = await Dns.GetHostAddressesAsync(uri.Host, cancellationToken) .ConfigureAwait(false); } catch (Exception e) when (e is SocketException or ArgumentException) { return Rejection.HostUnresolvable; } } if (addresses.Length == 0) return Rejection.HostUnresolvable; foreach (var address in addresses) { if (!IsPublic(address)) return Rejection.PrivateNetworkTarget; } return Rejection.None; } /// /// True when the address is routable on the public internet. Everything else — loopback, /// RFC 1918, link-local (incl. the 169.254.169.254 metadata address), CGNAT, /// unique-local IPv6, and IPv4-mapped IPv6 forms of all of those — is treated as internal. /// internal static bool IsPublic(IPAddress address) { // ::ffff:10.0.0.1 must be judged as 10.0.0.1, not as an opaque IPv6 address. if (address.IsIPv4MappedToIPv6) address = address.MapToIPv4(); if (IPAddress.IsLoopback(address)) return false; if (address.AddressFamily == AddressFamily.InterNetwork) { var b = address.GetAddressBytes(); return b[0] switch { 0 => false, // 0.0.0.0/8 "this network" 10 => false, // RFC 1918 127 => false, // loopback (belt and braces) 169 when b[1] == 254 => false, // link-local incl. cloud metadata 172 when b[1] >= 16 && b[1] <= 31 => false, // RFC 1918 192 when b[1] == 168 => false, // RFC 1918 100 when b[1] >= 64 && b[1] <= 127 => false, // RFC 6598 CGNAT >= 224 => false, // multicast + reserved _ => true, }; } if (address.AddressFamily == AddressFamily.InterNetworkV6) { if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal || address.IsIPv6Multicast) return false; // fc00::/7 unique local var b = address.GetAddressBytes(); if ((b[0] & 0xFE) == 0xFC) return false; // :: and ::1 if (address.Equals(IPAddress.IPv6Any) || address.Equals(IPAddress.IPv6Loopback)) return false; return true; } return false; } /// Human-readable reason, for logs and invalid_request_object descriptions. internal static string Describe(Rejection rejection) => rejection switch { Rejection.NotAbsolute => "not an absolute URL", Rejection.SchemeNotAllowed => "scheme must be http or https", Rejection.HttpsRequired => "must use https", Rejection.HostUnresolvable => "host could not be resolved", Rejection.PrivateNetworkTarget => "resolves to a non-public address", _ => "ok", }; } Path: redb-identity/src/redb.Identity.Core/Services/RecoveryCodePepperProvider.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/Services/RecoveryCodePepperProvider.cs ---- using System.Security.Cryptography; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Identity.Core.Configuration; namespace redb.Identity.Core.Services; /// /// Provides the server-wide pepper applied during MFA recovery-code hashing /// (B4 — defence-in-depth on top of per-user salt + PBKDF2) and to the hashes of the /// password-reset, e-mail-verification and change-e-mail tokens. /// /// The current pepper () hashes everything new; the previous ones /// () are only tried on verification, so a rotation keeps /// what was issued under them. Every pepper has an id () that stored hashes record, so a /// record is checked against exactly its pepper. /// /// Singleton lifetime: pepper bytes are decoded once at construction so every /// instance shares the same value. /// public sealed class RecoveryCodePepperProvider { private static readonly byte[] IdLabel = Encoding.ASCII.GetBytes("redb.identity.pepper-id"); private readonly IReadOnlyList<(string Id, byte[] Pepper)> _previous; /// Raw pepper bytes (configured or ephemeral). Never empty. public byte[] Pepper { get; } /// Id of the current pepper, recorded with every hash made from it. public string PepperId { get; } /// True if the pepper was generated at startup (development fallback). public bool IsEphemeral { get; } /// Ids of the previous peppers, in configured order. public IReadOnlyList PreviousPepperIds { get; } public RecoveryCodePepperProvider( IOptions options, ILogger logger) { var configured = options.Value.RecoveryCodePepper; if (!string.IsNullOrEmpty(configured)) { Pepper = Decode(configured, "RedbIdentityOptions.RecoveryCodePepper"); IsEphemeral = false; } else if (!options.Value.AllowEphemeralKeys) { throw new InvalidOperationException( "RedbIdentityOptions.RecoveryCodePepper is not configured. " + "Set AllowEphemeralKeys=true in development, or provide a stable base64-encoded " + "pepper (16+ bytes) loaded from a secret store in production."); } else { Pepper = RandomNumberGenerator.GetBytes(32); IsEphemeral = true; logger.LogWarning( "MFA recovery-code pepper is ephemeral: codes generated in this process cannot be " + "verified after restart. Set RedbIdentityOptions.RecoveryCodePepper for production."); } PepperId = ComputeId(Pepper); var previous = new List<(string, byte[])>(); var values = options.Value.RecoveryCodePreviousPeppers ?? []; for (var i = 0; i < values.Length; i++) { var name = $"RedbIdentityOptions.RecoveryCodePreviousPeppers[{i}]"; if (string.IsNullOrEmpty(values[i])) throw new InvalidOperationException($"{name} is empty."); var bytes = Decode(values[i], name); var id = ComputeId(bytes); if (id == PepperId) throw new InvalidOperationException($"{name} is the current RecoveryCodePepper."); if (previous.Any(p => p.Item1 == id)) throw new InvalidOperationException($"{name} repeats an earlier entry."); previous.Add((id, bytes)); } _previous = previous; PreviousPepperIds = previous.Select(p => p.Item1).ToArray(); } private RecoveryCodePepperProvider(byte[] pepper, bool isEphemeral, IEnumerable previous) { Pepper = pepper; IsEphemeral = isEphemeral; PepperId = ComputeId(pepper); _previous = previous.Select(p => (ComputeId(p), p)).ToArray(); PreviousPepperIds = _previous.Select(p => p.Id).ToArray(); } /// /// The peppers a stored hash is checked against. A hash with an id gets exactly its pepper, or none when that /// pepper is no longer configured; a hash without an id (written before 4.8.0) gets the current pepper, then the /// previous ones in order. /// public IReadOnlyList PeppersFor(string? pepperId) { if (string.IsNullOrEmpty(pepperId)) return [Pepper, .. _previous.Select(p => p.Pepper)]; if (pepperId == PepperId) return [Pepper]; foreach (var (id, pepper) in _previous) if (id == pepperId) return [pepper]; return []; } /// /// The id of a pepper: the first 8 bytes of HMAC-SHA256(pepper, "redb.identity.pepper-id"), lowercase hex. It /// tells peppers apart and reveals nothing usable about the value. /// public static string ComputeId(byte[] pepper) => Convert.ToHexStringLower(HMACSHA256.HashData(pepper, IdLabel).AsSpan(0, 8)); /// sha256(pepper || token), lowercase hex: the stored form of the one-time link tokens. public static string PepperedSha256Hex(byte[] pepper, string token) { var tokenBytes = Encoding.UTF8.GetBytes(token); var input = new byte[pepper.Length + tokenBytes.Length]; Buffer.BlockCopy(pepper, 0, input, 0, pepper.Length); Buffer.BlockCopy(tokenBytes, 0, input, pepper.Length, tokenBytes.Length); return Convert.ToHexStringLower(SHA256.HashData(input)); } /// /// Checks a one-time link token against its stored hash with the peppers gives for the /// stored pepper id. Every candidate is compared, in constant time. /// public bool MatchesTokenHash(string token, string storedHash, string? pepperId) { var stored = Encoding.ASCII.GetBytes(storedHash); var match = false; foreach (var pepper in PeppersFor(pepperId)) match |= CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(PepperedSha256Hex(pepper, token)), stored); return match; } private static byte[] Decode(string value, string name) { byte[] bytes; try { bytes = Convert.FromBase64String(value); } catch (FormatException ex) { throw new InvalidOperationException($"{name} must be a valid base64 string.", ex); } if (bytes.Length < 16) throw new InvalidOperationException($"{name} must decode to at least 16 bytes; got {bytes.Length}."); return bytes; } /// /// Test-only factory: builds a provider with a fixed (or random 32-byte) pepper, and optional previous peppers, /// without going through configuration validation. Use exclusively in unit / integration tests. /// public static RecoveryCodePepperProvider ForTesting(byte[]? pepper = null, params byte[][] previous) => new(pepper ?? RandomNumberGenerator.GetBytes(32), isEphemeral: pepper is null, previous); } Path: redb-identity/src/redb.Identity.Core/Services/RedbDpopReplayStore.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/Services/RedbDpopReplayStore.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; namespace redb.Identity.Core.Services; /// /// PROPS-backed mirroring /// . Singleton; resolves /// through a fresh DI scope per operation to avoid /// captive-scope-in-singleton. /// /// Atomicity (RFC 9449 §11.1, at most once): the reservation row carries /// ValueUnique = SHA-256 of jkt|jti, so the database index decides who wins, not /// the lookup. Two presentations of one proof racing past FirstOrDefaultAsync both try /// to insert; the index lets exactly one through and the other gets /// , reported as a replay. The lookup stays as the /// fast path — an already-consumed proof is refused without a failing statement — and an /// expired reservation is refreshed in place rather than inserted a second time. /// /// /// The key is hashed for the reason the idempotency record's is: /// jti is chosen by the client and unbounded, while ValueUnique is capped at 440 /// characters. Rows written before the key existed carry none; the lookup still finds them, /// and the cleanup timer removes them within one TTL. /// /// public sealed class RedbDpopReplayStore : IDpopReplayStore { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private readonly TimeProvider _timeProvider; public RedbDpopReplayStore( IServiceScopeFactory scopeFactory, ILogger logger, TimeProvider? timeProvider = null) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _timeProvider = timeProvider ?? TimeProvider.System; } public async Task TryReserveAsync(string jkt, string jti, TimeSpan ttl, CancellationToken ct = default) { if (string.IsNullOrEmpty(jkt) || string.IsNullOrEmpty(jti)) return false; var now = _timeProvider.GetUtcNow(); var expiresAt = now + (ttl <= TimeSpan.Zero ? TimeSpan.FromMinutes(5) : ttl); var name = jkt + "|" + jti; var uniqueKey = IdempotencyKeyHash.Sha256Hex(name); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // ExecuteAtomicAsync rather than an explicit transaction: it joins the ambient one when // the route is transacted (the token route is) and opens its own when it is not. An // explicit BeginTransactionAsync can do neither — the core rejects it under an ambient // scope — and a mid-logic rollback would discard the whole route: a replayed proof must // fail the request, not undo everything before it. return await redb.Context.ExecuteAtomicAsync(async () => { var existing = await redb.Query() .Where(o => o.Jkt == jkt && o.Jti == jti) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) { // A live reservation is a replay. if (existing.Props.ExpiresAt > now) { _logger.LogWarning("DPoP proof replay detected: jkt={Jkt} jti={Jti}", jkt, jti); return false; } // Expired — cleanup has not run yet. Refresh the row in place: a second insert // would hit the unique key and misreport a stale row as a replay. A proof this // old is refused by the iat window long before it reaches the store, so this // branch is housekeeping, not the guard. existing.Props.ConsumedAt = now; existing.Props.ExpiresAt = expiresAt; existing.ValueUnique = uniqueKey; await redb.SaveAsync(existing).ConfigureAwait(false); return true; } var row = new RedbObject(new DpopConsumedJtiProps { Jkt = jkt, Jti = jti, ConsumedAt = now, ExpiresAt = expiresAt, }); row.name = name; row.ValueUnique = uniqueKey; try { await redb.SaveAsync(row).ConfigureAwait(false); return true; } catch (RedbUniqueViolationException) { // The other presenter of this jti inserted between our lookup and our insert. // The core ran the insert under a savepoint, so the surrounding transaction (the // token route's, when ambient) is intact and the request is refused cleanly. _logger.LogWarning("DPoP proof replay detected (concurrent): jkt={Jkt} jti={Jti}", jkt, jti); return false; } }, ct).ConfigureAwait(false); } } Path: redb-identity/src/redb.Identity.Core/Services/RedisDpopReplayStore.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/Services/RedisDpopReplayStore.cs ---- using redb.Route.Redis; using StackExchange.Redis; namespace redb.Identity.Core.Services; /// /// Redis-backed . Uses atomic SET key NX EX ttl /// so the first writer wins; concurrent replays observe the existing key. /// internal sealed class RedisDpopReplayStore : IDpopReplayStore, IAsyncDisposable, IDisposable { private readonly RedisConnectionFactory _factory; private readonly string _prefix; private readonly SemaphoreSlim _connectionLock = new(1, 1); private IConnectionMultiplexer? _connection; public RedisDpopReplayStore(RedisConnectionFactory factory, string keyPrefix) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _prefix = keyPrefix ?? string.Empty; } public async Task TryReserveAsync(string jkt, string jti, TimeSpan ttl, CancellationToken ct = default) { if (string.IsNullOrEmpty(jkt) || string.IsNullOrEmpty(jti)) return false; ct.ThrowIfCancellationRequested(); var db = await GetDatabaseAsync(ct).ConfigureAwait(false); var fullKey = _prefix + jkt + ":" + jti; var ttlSpan = ttl <= TimeSpan.Zero ? TimeSpan.FromMinutes(5) : ttl; return await db.StringSetAsync( fullKey, "1", expiry: ttlSpan, when: When.NotExists).ConfigureAwait(false); } private async Task GetDatabaseAsync(CancellationToken ct) { if (_connection is { IsConnected: true }) return _connection.GetDatabase(_factory.Database); await _connectionLock.WaitAsync(ct).ConfigureAwait(false); try { if (_connection is { IsConnected: true }) return _connection.GetDatabase(_factory.Database); var config = _factory.Build(); _connection = await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false); return _connection.GetDatabase(_factory.Database); } finally { _connectionLock.Release(); } } public async ValueTask DisposeAsync() { if (_connection is not null) await _connection.DisposeAsync().ConfigureAwait(false); _connectionLock.Dispose(); } public void Dispose() { _connection?.Dispose(); _connectionLock.Dispose(); } } Path: redb-identity/src/redb.Identity.Core/Services/RedisFederationStateNonceStore.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/Services/RedisFederationStateNonceStore.cs ---- using redb.Route.Redis; using StackExchange.Redis; namespace redb.Identity.Core.Services; /// /// Redis-backed implementation of . /// Uses a per-jti string key with NX semantics so the first call wins atomically; /// the key is set with the requested TTL so expired jti values can be replayed /// only after the original state would itself have expired (consistent with /// ). /// internal sealed class RedisFederationStateNonceStore : IFederationStateNonceStore, IAsyncDisposable, IDisposable { private readonly RedisConnectionFactory _factory; private readonly string _prefix; private readonly SemaphoreSlim _connectionLock = new(1, 1); private IConnectionMultiplexer? _connection; public RedisFederationStateNonceStore(RedisConnectionFactory factory, string keyPrefix) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _prefix = keyPrefix ?? string.Empty; } public async Task TryConsumeAsync(string jti, TimeSpan ttl, CancellationToken ct = default) { if (string.IsNullOrEmpty(jti)) return false; ct.ThrowIfCancellationRequested(); var db = await GetDatabaseAsync(ct).ConfigureAwait(false); var fullKey = _prefix + jti; var ttlSpan = ttl <= TimeSpan.Zero ? TimeSpan.FromMinutes(5) : ttl; // Atomic SETNX with TTL — first writer wins; everyone else gets false. return await db.StringSetAsync( fullKey, "1", expiry: ttlSpan, when: When.NotExists).ConfigureAwait(false); } private async Task GetDatabaseAsync(CancellationToken ct) { if (_connection is { IsConnected: true }) return _connection.GetDatabase(_factory.Database); await _connectionLock.WaitAsync(ct).ConfigureAwait(false); try { if (_connection is { IsConnected: true }) return _connection.GetDatabase(_factory.Database); var config = _factory.Build(); _connection = await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false); return _connection.GetDatabase(_factory.Database); } finally { _connectionLock.Release(); } } public async ValueTask DisposeAsync() { if (_connection is not null) await _connection.DisposeAsync().ConfigureAwait(false); _connectionLock.Dispose(); } public void Dispose() { _connection?.Dispose(); _connectionLock.Dispose(); } } Path: redb-identity/src/redb.Identity.Core/Services/RedisRateLimitStore.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/Services/RedisRateLimitStore.cs ---- using redb.Identity.Core.Configuration; using redb.Route.Redis; using StackExchange.Redis; namespace redb.Identity.Core.Services; /// /// C1 — Cluster-global sliding-window counter backed by a Redis sorted set. /// Activated when is "redis". /// Uses the same abstraction as /// . /// internal sealed class RedisRateLimitStore : IRateLimitStore, IAsyncDisposable, IDisposable { private readonly RedisConnectionFactory _factory; private readonly string _prefix; private readonly TimeProvider _timeProvider; private readonly SemaphoreSlim _connectionLock = new(1, 1); private IConnectionMultiplexer? _connection; // Sliding-window counter. Mirrors InMemoryRateLimitStore semantics: // a request is denied iff the bucket already holds >= limit non-expired hits, and the // current hit is NOT inserted in that case. Returns { allowed (1/0), countAfter, oldestScore }. private const string IncrLuaScript = """ local key = KEYS[1] local nowTicks = tonumber(ARGV[1]) local windowTicks = tonumber(ARGV[2]) local limit = tonumber(ARGV[3]) local ttl = math.floor(windowTicks / 10000000) + 10 redis.call('ZREMRANGEBYSCORE', key, 0, nowTicks - windowTicks) local existing = redis.call('ZCARD', key) if existing >= limit then local oldest = '' local oldestEntries = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES') if #oldestEntries == 2 then oldest = oldestEntries[2] end redis.call('EXPIRE', key, ttl) return { 0, existing, oldest } end local member = nowTicks .. '-' .. redis.call('INCR', key .. ':seq') redis.call('ZADD', key, nowTicks, member) local count = redis.call('ZCARD', key) redis.call('EXPIRE', key, ttl) redis.call('EXPIRE', key .. ':seq', ttl) return { 1, count, '' } """; public RedisRateLimitStore(RedisConnectionFactory factory, string keyPrefix, TimeProvider timeProvider) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _prefix = keyPrefix; _timeProvider = timeProvider; } public async Task TryIncrementAsync(string key, int limit, TimeSpan window, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); var db = await GetDatabaseAsync(ct).ConfigureAwait(false); var nowTicks = _timeProvider.GetUtcNow().UtcTicks; var fullKey = _prefix + key; var raw = await db.ScriptEvaluateAsync( IncrLuaScript, new RedisKey[] { fullKey }, new RedisValue[] { nowTicks, window.Ticks, limit }).ConfigureAwait(false); var arr = (RedisResult[]?)raw; if (arr is null || arr.Length < 2) return new RateLimitDecision(true, 0, TimeSpan.Zero); var allowed = (long)arr[0]! == 1L; var count = (int)(long)arr[1]!; var retryAfter = TimeSpan.Zero; if (!allowed && arr.Length >= 3) { var oldestStr = (string?)arr[2]; if (!string.IsNullOrEmpty(oldestStr) && long.TryParse(oldestStr, out var oldestTicks)) { var elapsed = nowTicks - oldestTicks; retryAfter = TimeSpan.FromTicks(Math.Max(window.Ticks - elapsed, TimeSpan.TicksPerSecond)); } } return new RateLimitDecision(allowed, count, retryAfter); } public async Task ResetAsync(string key, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); var db = await GetDatabaseAsync(ct).ConfigureAwait(false); var fullKey = _prefix + key; await db.KeyDeleteAsync(new RedisKey[] { fullKey, fullKey + ":seq" }).ConfigureAwait(false); } private async Task GetDatabaseAsync(CancellationToken ct) { if (_connection is { IsConnected: true }) return _connection.GetDatabase(_factory.Database); await _connectionLock.WaitAsync(ct).ConfigureAwait(false); try { if (_connection is { IsConnected: true }) return _connection.GetDatabase(_factory.Database); var config = _factory.Build(); _connection = await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false); return _connection.GetDatabase(_factory.Database); } finally { _connectionLock.Release(); } } public async ValueTask DisposeAsync() { if (_connection is not null) await _connection.DisposeAsync().ConfigureAwait(false); _connectionLock.Dispose(); } public void Dispose() { _connection?.Dispose(); _connectionLock.Dispose(); } } Path: redb-identity/src/redb.Identity.Core/Services/RoleService.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/Services/RoleService.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// B.3 — backing implementation for the Roles registry. All shapes go /// through redb's native LINQ provider so cross-dialect (PG / MSSQL / /// SQLite) works without per-driver SQL. /// public sealed class RoleService { private readonly IRedbService _redb; public RoleService(IRedbService redb) => _redb = redb; // ── Role CRUD ────────────────────────────────────────────── public async Task> CreateRoleAsync( string name, string audience, long? applicationId, string? displayName, string? description, bool isSystem = false, CancellationToken ct = default) { // Uniqueness check — (Name, Audience, ApplicationId) var dupe = await _redb.Query() .Where(p => p.Name == name) .Where(p => p.Audience == audience) .Where(p => p.ApplicationId == applicationId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (dupe is not null) throw new InvalidOperationException( $"Role '{name}' with audience '{audience}' (app={applicationId?.ToString() ?? "none"}) already exists."); var obj = new RedbObject { name = name, Props = new RoleProps { Name = name, DisplayName = displayName, Description = description, Audience = audience, ApplicationId = applicationId, IsSystem = isSystem } }; obj.id = await _redb.SaveAsync(obj).ConfigureAwait(false); return obj; } public async Task?> GetRoleAsync(long roleId, CancellationToken ct = default) => await _redb.LoadAsync(roleId).ConfigureAwait(false); public async Task UpdateRoleAsync( long roleId, string? displayName, string? description, CancellationToken ct = default) { var role = await _redb.LoadAsync(roleId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Role {roleId} not found."); if (displayName is not null) role.Props.DisplayName = displayName; if (description is not null) role.Props.Description = description; await _redb.SaveAsync(role).ConfigureAwait(false); } public async Task DeleteRoleAsync(long roleId, CancellationToken ct = default) { var role = await _redb.LoadAsync(roleId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Role {roleId} not found."); if (role.Props.IsSystem) throw new InvalidOperationException("System roles cannot be deleted."); // Cascade-clean assignments first so we don't leave orphaned rows // hanging around (foreign-key contract is parent_id → role id). await CleanAssignmentsAsync(roleId).ConfigureAwait(false); await _redb.DeleteAsync(role).ConfigureAwait(false); } /// /// Paged search across all roles, with optional name pattern + audience /// filter + application filter. Audience='application' + applicationId /// supplied narrows to one app's roles. /// public async Task<(List> Items, int Total)> SearchRolesAsync( string? namePattern, string? audience, long? applicationId, int offset, int count, CancellationToken ct = default) { var query = _redb.Query(); if (!string.IsNullOrEmpty(namePattern)) { var pat = namePattern; query = query.WhereRedb(o => o.Name.Contains(pat)); } if (!string.IsNullOrEmpty(audience)) query = query.Where(p => p.Audience == audience); if (applicationId is not null) query = query.Where(p => p.ApplicationId == applicationId); var total = (int)await query.CountAsync().ConfigureAwait(false); var items = await query .OrderByRedb(o => o.Name) .Skip(offset) .Take(count) .ToListAsync() .ConfigureAwait(false); return (items, total); } // ── Assignments ──────────────────────────────────────────── public async Task AssignUserAsync(long roleId, long userId, long? actingUserId, CancellationToken ct = default) { // Idempotent — skip if row already exists with same role+user. var existing = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) return; var obj = new RedbObject(new UserRoleAssignmentProps { AssignedAt = DateTimeOffset.UtcNow, AssignedByUserId = actingUserId }) { name = $"user:{userId}", key = userId, parent_id = roleId, value_long = userId }; await _redb.SaveAsync(obj).ConfigureAwait(false); } public async Task UnassignUserAsync(long roleId, long userId, CancellationToken ct = default) { var existing = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is null) return; await _redb.DeleteAsync(existing).ConfigureAwait(false); } public async Task AssignGroupAsync(long roleId, long groupId, long? actingUserId, CancellationToken ct = default) { var existing = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .WhereRedb(o => o.Key == groupId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) return; var obj = new RedbObject(new GroupRoleAssignmentProps { AssignedAt = DateTimeOffset.UtcNow, AssignedByUserId = actingUserId }) { name = $"group:{groupId}", key = groupId, parent_id = roleId, value_long = groupId }; await _redb.SaveAsync(obj).ConfigureAwait(false); } public async Task UnassignGroupAsync(long roleId, long groupId, CancellationToken ct = default) { var existing = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .WhereRedb(o => o.Key == groupId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is null) return; await _redb.DeleteAsync(existing).ConfigureAwait(false); } private async Task CleanAssignmentsAsync(long roleId) { var users = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .ToListAsync() .ConfigureAwait(false); foreach (var u in users) await _redb.DeleteAsync(u).ConfigureAwait(false); var groups = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .ToListAsync() .ConfigureAwait(false); foreach (var g in groups) await _redb.DeleteAsync(g).ConfigureAwait(false); } // ── Queries (assignees + per-user role set) ──────────────── /// /// Returns (userIds, groupIds) currently assigned to . /// public async Task<(List UserIds, List GroupIds)> ListAssigneesAsync(long roleId, CancellationToken ct = default) { var users = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .ToListAsync() .ConfigureAwait(false); var groups = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .ToListAsync() .ConfigureAwait(false); return ( users.Where(u => u.value_long.HasValue).Select(u => u.value_long!.Value).Distinct().ToList(), groups.Where(g => g.value_long.HasValue).Select(g => g.value_long!.Value).Distinct().ToList()); } /// /// Bulk per-role assignment count for the list page badge. /// public async Task> CountAssignmentsByRoleAsync( IEnumerable roleIds, CancellationToken ct = default) { var ids = roleIds.Distinct().ToList(); if (ids.Count == 0) return new(); var users = await _redb.Query() .WhereInRedb(o => o.ParentId, ids.Cast()) .ToListAsync() .ConfigureAwait(false); var groups = await _redb.Query() .WhereInRedb(o => o.ParentId, ids.Cast()) .ToListAsync() .ConfigureAwait(false); var counts = new Dictionary(); foreach (var u in users) { if (u.parent_id is { } pid) counts[pid] = counts.GetValueOrDefault(pid) + 1; } foreach (var g in groups) { if (g.parent_id is { } pid) counts[pid] = counts.GetValueOrDefault(pid) + 1; } return counts; } // ── Scope attachments ────────────────────────────────────── public async Task AttachScopeAsync(long roleId, long scopeId, long? actingUserId, CancellationToken ct = default) { var existing = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .WhereRedb(o => o.Key == scopeId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) return; var obj = new RedbObject(new RoleScopeAssignmentProps { AttachedAt = DateTimeOffset.UtcNow, AttachedByUserId = actingUserId }) { name = $"scope:{scopeId}", key = scopeId, parent_id = roleId, value_long = scopeId }; await _redb.SaveAsync(obj).ConfigureAwait(false); } public async Task DetachScopeAsync(long roleId, long scopeId, CancellationToken ct = default) { var existing = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .WhereRedb(o => o.Key == scopeId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is null) return; await _redb.DeleteAsync(existing).ConfigureAwait(false); } /// /// List scope IDs currently attached to . /// public async Task> ListScopeIdsForRoleAsync(long roleId, CancellationToken ct = default) { var rows = await _redb.Query() .WhereRedb(o => o.ParentId == roleId) .ToListAsync() .ConfigureAwait(false); return rows .Where(r => r.value_long.HasValue) .Select(r => r.value_long!.Value) .Distinct() .ToList(); } /// /// Effective scope set for a set of roles — union of every role's /// attached scopes. Returns the SCOPE NAMES (string), ready to merge /// into the principal's scope list at token issuance. /// public async Task> GetEffectiveScopeNamesAsync( IEnumerable roleIds, CancellationToken ct = default) { var ids = roleIds.Distinct().ToList(); if (ids.Count == 0) return new(StringComparer.Ordinal); var rows = await _redb.Query() .WhereInRedb(o => o.ParentId, ids.Cast()) .ToListAsync() .ConfigureAwait(false); var scopeIds = rows .Where(r => r.value_long.HasValue) .Select(r => r.value_long!.Value) .Distinct() .ToList(); if (scopeIds.Count == 0) return new(StringComparer.Ordinal); var scopes = await _redb.Query() .WhereInRedb(o => o.Id, scopeIds.Cast()) .ToListAsync() .ConfigureAwait(false); // V4-UNIQUE: ScopeName is a stored [RedbUnique] prop; value_string covers legacy rows. return scopes .Select(s => s.Props.ScopeName ?? s.value_string) .Where(n => !string.IsNullOrEmpty(n)) .Select(n => n!) .ToHashSet(StringComparer.Ordinal); } /// /// Effective role set for a user at token issuance time: /// direct user assignments ∪ assignments inherited from every group /// the user belongs to. Filtered by audience and applicationId so an /// audience='application' role bound to app A doesn't leak into a /// token issued for app B. /// public async Task>> GetEffectiveRolesAsync( long userId, IEnumerable groupIds, long? applicationId, CancellationToken ct = default) { var groupIdList = groupIds.Distinct().ToList(); // Direct user assignments → role ids var userAssignments = await _redb.Query() .WhereRedb(o => o.Key == userId) .ToListAsync() .ConfigureAwait(false); var roleIds = userAssignments .Where(u => u.parent_id.HasValue) .Select(u => u.parent_id!.Value) .ToHashSet(); // Group → role ids if (groupIdList.Count > 0) { var groupAssignments = await _redb.Query() .WhereInRedb(o => o.Key, groupIdList.Cast()) .ToListAsync() .ConfigureAwait(false); foreach (var g in groupAssignments) { if (g.parent_id.HasValue) roleIds.Add(g.parent_id.Value); } } if (roleIds.Count == 0) return new(); // Bulk-load the roles in one round trip, filter on audience. var roles = await _redb.Query() .WhereInRedb(o => o.Id, roleIds.Cast()) .ToListAsync() .ConfigureAwait(false); return roles.Where(r => { if (r.Props.Audience == "organization") return true; // audience='application' → only emit when applicationId matches. return applicationId.HasValue && r.Props.ApplicationId == applicationId.Value; }).ToList(); } } Path: redb-identity/src/redb.Identity.Core/Services/SeedAdminPasswordHostedService.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/Services/SeedAdminPasswordHostedService.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Identity.Core.Configuration; using redb.Route.Abstractions; namespace redb.Identity.Core.Services; /// /// Startup seeder that ensures the well-known admin user from the base /// redb SQL seed (_users.id = 1, login = "admin", empty password) /// has a usable password on a fresh install. Behaviour: /// /// Resolves through a transient scope. /// Looks up user by . /// If the user is missing → no-op. /// If the user has a stored password other than the documented default /// admin → no-op with one log line: that password belongs to the operator /// (set via the Tsak dashboard, bootstrap-admin or the management API). /// If the stored password is empty, or is still the default admin /// (a Tsak dashboard sharing the database writes admin/admin before this /// listener runs), hashes via the /// configured chain and /// persists it via . /// /// Always logs a loud WARNING on startup when the configured password is /// the documented default admin, regardless of whether a write was needed. /// /// Implemented as an hooked into /// rather than an /// IHostedService because Tsak hosts modules without a generic IHost; /// route-context lifecycle hooks are the canonical startup extension point and /// fire on every cold-start AND on every hot-reload of the .tpkg module. /// /// public sealed class SeedAdminPasswordHostedService : IRouteLifecycleListener { private readonly IServiceProvider _serviceProvider; private readonly IOptions _options; private readonly ILogger _logger; public SeedAdminPasswordHostedService( IServiceProvider serviceProvider, IOptions options, ILogger logger) { _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _options = options ?? throw new ArgumentNullException(nameof(options)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task OnContextStarting(IRouteContext context, CancellationToken cancellationToken) { var seed = _options.Value.SeedAdmin; if (!seed.Enabled) { _logger.LogDebug("SeedAdmin disabled — skipping default-password seeding"); return; } if (string.IsNullOrWhiteSpace(seed.Login) || string.IsNullOrEmpty(seed.Password)) { _logger.LogWarning( "SeedAdmin enabled but Login/Password is empty — skipping (login='{Login}')", seed.Login); return; } WarnIfDefaultPassword(seed); try { using var scope = _serviceProvider.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var user = await redb.UserProvider.GetUserByLoginAsync(seed.Login).ConfigureAwait(false); if (user is null) { _logger.LogInformation( "SeedAdmin: user '{Login}' not found in _users — nothing to seed", seed.Login); return; } if (!string.IsNullOrEmpty(user.Password)) { // A password is already stored. Replace it only while it is still the documented // default: a host that shares the database with the Tsak dashboard sees the dashboard // write admin/admin before this listener runs. Any other password belongs to the // operator and stays. if (string.Equals(seed.Password, SeedAdminOptions.DefaultPassword, StringComparison.Ordinal)) { _logger.LogDebug( "SeedAdmin: user '{Login}' (id={Id}) already has a stored password and no other is configured", seed.Login, user.Id); return; } var storedIsDefault = await redb.UserProvider .ValidateUserAsync(seed.Login, SeedAdminOptions.DefaultPassword) .ConfigureAwait(false) is not null; if (!storedIsDefault) { _logger.LogInformation( "SeedAdmin: user '{Login}' (id={Id}) already has a changed password, seed skipped", seed.Login, user.Id); return; } } var ok = await redb.UserProvider .SetPasswordAsync(user, seed.Password, currentUser: user) .ConfigureAwait(false); if (ok) { _logger.LogInformation( "SeedAdmin: hashed and stored default password for user '{Login}' (id={Id})", seed.Login, user.Id); } else { _logger.LogWarning( "SeedAdmin: SetPasswordAsync returned false for user '{Login}' (id={Id})", seed.Login, user.Id); } } catch (Exception ex) { // Never fail host startup over the convenience seeder. Worst case: the // operator hits the bootstrap-admin endpoint or sets the password manually. _logger.LogError(ex, "SeedAdmin: unexpected failure while seeding password for user '{Login}'", seed.Login); } } private void WarnIfDefaultPassword(SeedAdminOptions seed) { if (!string.Equals(seed.Password, SeedAdminOptions.DefaultPassword, StringComparison.Ordinal)) return; _logger.LogWarning( "============================================================"); _logger.LogWarning( " SECURITY WARNING: SeedAdmin password for '{Login}' is the"); _logger.LogWarning( " documented default ('admin'). This is intended for FRESH"); _logger.LogWarning( " development installs only. Rotate it via the management API"); _logger.LogWarning( " or set Identity:SeedAdmin:Password before exposing this"); _logger.LogWarning( " host to untrusted networks."); _logger.LogWarning( "============================================================"); } } Path: redb-identity/src/redb.Identity.Core/Services/SeedBackchannelClientHostedService.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/Services/SeedBackchannelClientHostedService.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Identity.Core.Configuration; using redb.Route.Abstractions; namespace redb.Identity.Core.Services; /// /// W6-0 — sister of . Ensures the /// client_credentials backchannel service-account OpenIddict application /// exists on host startup. The Web BFF uses this account to publish /// (POST /api/v1/identity/revoked-sids) and poll /// (GET /api/v1/identity/revoked-sids/since) the cluster-wide revoked-sids /// list for backchannel logout. /// /// Behaviour: /// /// No-op when is false. /// No-op when the application already exists (idempotent across restarts). /// Logs and skips when is empty — /// client_credentials requires a confidential client (RFC 6749 §4.4). /// Never throws — operators can always provision the client manually via the /// management API. /// /// /// public sealed class SeedBackchannelClientHostedService : IRouteLifecycleListener { private readonly IServiceProvider _serviceProvider; private readonly IOptions _options; private readonly ILogger _logger; public SeedBackchannelClientHostedService( IServiceProvider serviceProvider, IOptions options, ILogger logger) { _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _options = options ?? throw new ArgumentNullException(nameof(options)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task OnContextStarting(IRouteContext context, CancellationToken cancellationToken) { var seed = _options.Value.SeedBackchannelClient; if (!seed.Enabled) { _logger.LogDebug("SeedBackchannelClient disabled — skipping"); return; } if (string.IsNullOrWhiteSpace(seed.ClientId)) { _logger.LogWarning("SeedBackchannelClient enabled but ClientId is empty — skipping"); return; } if (string.IsNullOrEmpty(seed.ClientSecret)) { _logger.LogWarning( "SeedBackchannelClient enabled but ClientSecret is empty — client_credentials requires a confidential client. Skipping."); return; } try { using var scope = _serviceProvider.CreateScope(); var manager = scope.ServiceProvider.GetRequiredService(); var existing = await manager.FindByClientIdAsync(seed.ClientId, cancellationToken).ConfigureAwait(false); if (existing is not null) { _logger.LogDebug( "SeedBackchannelClient: client '{ClientId}' already exists — leaving untouched", seed.ClientId); return; } var descriptor = new OpenIddictApplicationDescriptor { ClientId = seed.ClientId, ClientSecret = seed.ClientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = seed.DisplayName, ApplicationType = OpenIddictConstants.ApplicationTypes.Web, }; descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Token); descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials); foreach (var s in seed.Scopes) descriptor.Permissions.Add(OpenIddictConstants.Permissions.Prefixes.Scope + s); await manager.CreateAsync(descriptor, cancellationToken).ConfigureAwait(false); _logger.LogInformation( "SeedBackchannelClient: registered backchannel service account '{ClientId}' with scopes [{Scopes}]", seed.ClientId, string.Join(", ", seed.Scopes)); } catch (Exception ex) { _logger.LogError(ex, "SeedBackchannelClient: unexpected failure while seeding client '{ClientId}'", _options.Value.SeedBackchannelClient.ClientId); } } } Path: redb-identity/src/redb.Identity.Core/Services/SeedWebClientHostedService.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/Services/SeedWebClientHostedService.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Identity.Core.Configuration; using redb.Route.Abstractions; namespace redb.Identity.Core.Services; /// /// Startup seeder that ensures the canonical Web Console OIDC client (default /// identity-web) exists in the OpenIddict application store. Sister to /// — together they make a fresh /// install runnable end-to-end with no manual bootstrap step: /// /// hashes the default /// password for the seeded admin user. /// This service registers the OIDC client so the Web BFF can complete /// /connect/authorize. /// /// Behaviour: /// /// Resolves via a transient scope. /// Looks up the client by . /// If found → no-op (idempotent across restarts; respects clients /// created by bootstrap-admin / dynamic registration / management API). /// Otherwise creates a Public client (or Confidential when a /// is supplied) with /// authorization_code + refresh_token + PKCE-required. /// /// Convenience for fresh dev/demo deployments only — production should disable /// this and provision clients explicitly via the management API. /// /// Implemented as an hooked into /// — Tsak modules have /// no generic IHost, so route-context lifecycle is the canonical startup /// extension point. /// /// public sealed class SeedWebClientHostedService : IRouteLifecycleListener { private readonly IServiceProvider _serviceProvider; private readonly IOptions _options; private readonly ILogger _logger; public SeedWebClientHostedService( IServiceProvider serviceProvider, IOptions options, ILogger logger) { _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _options = options ?? throw new ArgumentNullException(nameof(options)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task OnContextStarting(IRouteContext context, CancellationToken cancellationToken) { var seed = _options.Value.SeedWebClient; if (!seed.Enabled) { _logger.LogDebug("SeedWebClient disabled — skipping default OIDC client seeding"); return; } if (string.IsNullOrWhiteSpace(seed.ClientId)) { _logger.LogWarning("SeedWebClient enabled but ClientId is empty — skipping"); return; } try { using var scope = _serviceProvider.CreateScope(); var manager = scope.ServiceProvider.GetRequiredService(); var existing = await manager .FindByClientIdAsync(seed.ClientId, cancellationToken) .ConfigureAwait(false); if (existing is not null) { _logger.LogDebug( "SeedWebClient: OIDC client '{ClientId}' already exists — leaving untouched", seed.ClientId); return; } var isPublic = string.IsNullOrEmpty(seed.ClientSecret); var descriptor = new OpenIddictApplicationDescriptor { ClientId = seed.ClientId, ClientSecret = isPublic ? null : seed.ClientSecret, ClientType = isPublic ? OpenIddictConstants.ClientTypes.Public : OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = seed.DisplayName, ApplicationType = OpenIddictConstants.ApplicationTypes.Web, }; foreach (var uri in seed.RedirectUris) { if (Uri.TryCreate(uri, UriKind.Absolute, out var parsed)) descriptor.RedirectUris.Add(parsed); else _logger.LogWarning("SeedWebClient: skipping invalid RedirectUri '{Uri}'", uri); } foreach (var uri in seed.PostLogoutRedirectUris) { if (Uri.TryCreate(uri, UriKind.Absolute, out var parsed)) descriptor.PostLogoutRedirectUris.Add(parsed); else _logger.LogWarning("SeedWebClient: skipping invalid PostLogoutRedirectUri '{Uri}'", uri); } // Endpoint + grant + response permissions required for code+PKCE+refresh. var permissions = new List { OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.EndSession, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.ResponseTypes.Code, }; // Map scope names to the appropriate OpenIddict permission constants. // Standard OIDC scopes have dedicated permission constants; everything // else goes through the generic Scope: prefix. foreach (var s in seed.Scopes) { var perm = s switch { "openid" => OpenIddictConstants.Permissions.Prefixes.Scope + "openid", "profile" => OpenIddictConstants.Permissions.Scopes.Profile, "email" => OpenIddictConstants.Permissions.Scopes.Email, "roles" => OpenIddictConstants.Permissions.Scopes.Roles, "phone" => OpenIddictConstants.Permissions.Scopes.Phone, "address" => OpenIddictConstants.Permissions.Scopes.Address, "offline_access" => OpenIddictConstants.Permissions.Prefixes.Scope + "offline_access", _ => OpenIddictConstants.Permissions.Prefixes.Scope + s, }; permissions.Add(perm); } foreach (var p in permissions) descriptor.Permissions.Add(p); // PKCE is mandatory for public clients (and best-practice for confidential). descriptor.Requirements.Add( OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange); await manager.CreateAsync(descriptor, cancellationToken).ConfigureAwait(false); _logger.LogInformation( "SeedWebClient: registered OIDC client '{ClientId}' ({ClientType}) with {RedirectCount} redirect uri(s) and scopes [{Scopes}]", seed.ClientId, isPublic ? "public" : "confidential", seed.RedirectUris.Count, string.Join(", ", seed.Scopes)); } catch (Exception ex) { // Never fail host startup over the convenience seeder. Operators can // always provision the client manually via the management API or the // bootstrap-admin endpoint. _logger.LogError(ex, "SeedWebClient: unexpected failure while seeding OIDC client '{ClientId}'", _options.Value.SeedWebClient.ClientId); } } } Path: redb-identity/src/redb.Identity.Core/Services/SessionService.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/Services/SessionService.cs ---- using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Manages user login sessions. Sessions track when a user logged into an application. /// Revoking sessions cascades to revoking all authorizations (which invalidates tokens). /// public sealed class SessionService { private readonly IRedbService _redb; private readonly TimeProvider _timeProvider; private readonly TimeSpan _idleTimeout; private readonly TimeSpan _absoluteTimeout; public SessionService(IRedbService redb) : this(redb, TimeProvider.System, null) { } public SessionService(IRedbService redb, TimeProvider? timeProvider) : this(redb, timeProvider, null) { } public SessionService(IRedbService redb, TimeProvider? timeProvider, IOptions? options) { _redb = redb; _timeProvider = timeProvider ?? TimeProvider.System; // No DI source → fall back to industry-default 24 h idle / 30 d absolute. // Same defaults as RedbIdentityOptions; declared twice so a SessionService // built without options (legacy call sites) doesn't fail-open with // TimeSpan.Zero. _idleTimeout = options?.Value.SessionIdleTimeout ?? TimeSpan.FromHours(24); _absoluteTimeout = options?.Value.SessionAbsoluteTimeout ?? TimeSpan.FromDays(30); } /// /// S-track: is this session beyond either timeout? Mirrors the check done /// at (lazy) and /// (eager). /// public bool IsExpired(SessionProps props, DateTimeOffset? createdAt, DateTimeOffset now) { if (createdAt is { } c && now - c > _absoluteTimeout) return true; if (props.LastAccessedAt is { } la && now - la > _idleTimeout) return true; return false; } /// /// Creates a new active session record. , /// and are optional device-identification fields populated by /// the HTTP authentication processors from the calling request's headers. /// public async Task> CreateAsync( long userId, long applicationObjectId, bool mfaVerified = false, string? mfaMethod = null, string? ipAddress = null, string? userAgent = null, string? deviceLabel = null, CancellationToken ct = default) { var now = _timeProvider.GetUtcNow(); var session = new RedbObject { key = userId, Props = new SessionProps { ApplicationObjectId = applicationObjectId, Status = "active", MfaVerified = mfaVerified, MfaMethod = mfaMethod, IpAddress = ipAddress, UserAgent = userAgent, DeviceLabel = deviceLabel, LastAccessedAt = now, LastAccessedBy = "create", } }; session.id = await _redb.SaveAsync(session).ConfigureAwait(false); return session; } /// /// S-track: bump LastAccessedAt on the given session. Called by /// on /// refresh_token grant, by the cookie OnValidatePrincipal handler, and /// by /connect/userinfo. is a short label /// stored for diagnostics ("refresh_token", "cookie", "userinfo"). /// No-op (returns false) when the session doesn't exist or is revoked. /// public async Task TouchAsync(long sessionId, string activity, CancellationToken ct = default) { if (sessionId <= 0) return false; var session = await _redb.LoadAsync(sessionId).ConfigureAwait(false); if (session is null || session.Props.Status != "active") return false; session.Props.LastAccessedAt = _timeProvider.GetUtcNow(); session.Props.LastAccessedBy = activity; await _redb.SaveAsync(session).ConfigureAwait(false); return true; } /// /// Records that obtained tokens through session /// (). Idempotent. The /// append runs under a row lock: two authorization requests from the same browser (two tabs, two /// relying parties) must not lose each other's entry, because a lost entry is a relying party that is /// never told about the logout. Returns false for an unknown or revoked session. /// public async Task BindClientAsync(long sessionId, long applicationObjectId, CancellationToken ct = default) { if (sessionId <= 0 || applicationObjectId <= 0) return false; return await _redb.Context.ExecuteAtomicAsync(async () => { await _redb.LockForUpdateAsync([sessionId], ct).ConfigureAwait(false); var session = await _redb.LoadAsync(sessionId).ConfigureAwait(false); if (session is null || session.Props.Status != "active") return false; var bound = session.Props.ClientApplicationIds ?? []; if (bound.Contains(applicationObjectId)) return true; session.Props.ClientApplicationIds = [.. bound, applicationObjectId]; await _redb.SaveAsync(session).ConfigureAwait(false); return true; }, ct).ConfigureAwait(false); } /// /// Checks whether a specific session (by its object ID) has been revoked. /// Returns true if the session exists and is revoked, false otherwise. /// public async Task IsSessionRevokedAsync(long sessionObjectId, CancellationToken ct = default) { if (sessionObjectId <= 0) return false; var session = await _redb.LoadAsync(sessionObjectId) .ConfigureAwait(false); return session?.Props.Status == "revoked"; } /// /// Checks whether the user's sessions have been revoked (indicating explicit logout). /// Returns true only if revoked sessions exist AND there are zero active ones. /// If no sessions exist at all (first authorize), returns false (not revoked). /// public async Task IsFullyRevokedAsync( long userId, TimeSpan? lookbackWindow = null, CancellationToken ct = default) { var sessions = await _redb.Query() .WhereRedb(o => o.Key == userId) .ToListAsync() .ConfigureAwait(false); // Only consider sessions within the lookback window (default: all). // Sessions older than the cookie lifetime are irrelevant — any cookie from that era // has already expired, so revoked sessions from previous login generations don't matter. if (lookbackWindow.HasValue) { var cutoff = _timeProvider.GetUtcNow() - lookbackWindow.Value; sessions = sessions .Where(s => s.date_create >= cutoff) .ToList(); } // No sessions at all — user hasn't authorized yet, not revoked if (sessions.Count == 0) return false; // If any session is active, not fully revoked return sessions.All(s => s.Props.Status == "revoked"); } /// /// Lists all active sessions for a user. Includes application info. /// /// Application metadata is fetched in a single batched WhereInRedb(o => o.Id, ids) /// query rather than per-row — a user with many /// active sessions across multiple clients would otherwise turn this admin endpoint /// into an O(N) round-trip storm. /// /// public async Task> ListAsync(long userId, CancellationToken ct = default) { var sessions = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(s => s.Status == "active") .ToListAsync() .ConfigureAwait(false); // S-track: lazy-expire any active rows that have crossed either // timeout. Mark + persist + drop from the result so the caller sees // only sessions actually still alive. Eager cleanup also runs in // SessionCleanupProcessor for tenants where the user never lists. var now = _timeProvider.GetUtcNow(); var stillAlive = new List>(sessions.Count); foreach (var s in sessions) { if (IsExpired(s.Props, s.date_create, now)) { s.Props.Status = "revoked"; await _redb.SaveAsync(s).ConfigureAwait(false); } else { stillAlive.Add(s); } } sessions = stillAlive; // Batch-fetch every distinct ApplicationProps in ONE query to avoid N+1. var appIds = sessions .Where(s => s.Props.ApplicationObjectId > 0) .Select(s => s.Props.ApplicationObjectId) .Distinct() .ToArray(); var appsById = new Dictionary>(appIds.Length); if (appIds.Length > 0) { var apps = await _redb.Query() .WhereInRedb(o => o.Id, appIds) .ToListAsync() .ConfigureAwait(false); foreach (var app in apps) appsById[app.id] = app; } var result = new List(sessions.Count); foreach (var session in sessions) { string? clientId = null; string? appName = null; if (session.Props.ApplicationObjectId > 0 && appsById.TryGetValue(session.Props.ApplicationObjectId, out var app)) { clientId = app.Props.ClientId; appName = app.Name; } result.Add(new SessionInfo { SessionId = session.id, UserId = session.key ?? 0, ApplicationObjectId = session.Props.ApplicationObjectId, ClientId = clientId, ApplicationName = appName, Status = session.Props.Status ?? "active", CreatedAt = session.date_create, IpAddress = session.Props.IpAddress, UserAgent = session.Props.UserAgent, DeviceLabel = session.Props.DeviceLabel, LastAccessedAt = session.Props.LastAccessedAt, LastAccessedBy = session.Props.LastAccessedBy }); } return result; } /// /// Admin-wide list of recent active sessions across ALL users, paginated. /// Powers the /admin/sessions browse-by-default page (WSO2-style). The /// per-user stays the targeted path; this one is /// the operator's first-look "what's alive right now" view. /// public async Task<(List Items, int Total)> ListAllActiveAsync( int offset, int count, CancellationToken ct = default) { offset = Math.Max(0, offset); count = Math.Clamp(count, 1, 200); var total = (int)await _redb.Query() .Where(s => s.Status == "active") .CountAsync() .ConfigureAwait(false); var sessions = await _redb.Query() .Where(s => s.Status == "active") .OrderByDescendingRedb(o => o.Id) .Skip(offset) .Take(count) .ToListAsync() .ConfigureAwait(false); var appIds = sessions .Where(s => s.Props.ApplicationObjectId > 0) .Select(s => s.Props.ApplicationObjectId) .Distinct() .ToArray(); var appsById = new Dictionary>(appIds.Length); if (appIds.Length > 0) { var apps = await _redb.Query() .WhereInRedb(o => o.Id, appIds) .ToListAsync() .ConfigureAwait(false); foreach (var app in apps) appsById[app.id] = app; } var items = new List(sessions.Count); foreach (var s in sessions) { string? clientId = null; string? appName = null; if (s.Props.ApplicationObjectId > 0 && appsById.TryGetValue(s.Props.ApplicationObjectId, out var app)) { clientId = app.Props.ClientId ?? app.value_string; appName = app.name; } items.Add(new SessionInfo { SessionId = s.id, UserId = s.key ?? 0, ApplicationObjectId = s.Props.ApplicationObjectId, ClientId = clientId, ApplicationName = appName, Status = s.Props.Status, CreatedAt = s.date_create, IpAddress = s.Props.IpAddress, UserAgent = s.Props.UserAgent, DeviceLabel = s.Props.DeviceLabel, LastAccessedAt = s.Props.LastAccessedAt, LastAccessedBy = s.Props.LastAccessedBy }); } return (items, total); } /// /// Revokes a single session by its object ID. /// public async Task RevokeAsync(long sessionObjectId, CancellationToken ct = default) { var session = await _redb.LoadAsync(sessionObjectId) .ConfigureAwait(false); if (session is null || session.Props.Status == "revoked") return 0; session.Props.Status = "revoked"; await _redb.SaveAsync(session).ConfigureAwait(false); return 1; } /// /// Revokes all active sessions for a user. /// /// Mutated rows are persisted in a single batched SaveAsync(IEnumerable<...>) /// call rather than per-row inside the loop \u2014 a power user with many open device /// sessions otherwise turned this admin / logout step into an O(N) round-trip storm. /// /// public async Task RevokeAllAsync(long userId, CancellationToken ct = default) { var sessions = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(s => s.Status == "active") .ToListAsync() .ConfigureAwait(false); if (sessions.Count == 0) return 0; foreach (var session in sessions) session.Props.Status = "revoked"; await _redb.SaveAsync(sessions).ConfigureAwait(false); return sessions.Count; } /// /// N7-4 dry-run: returns how many active sessions would /// revoke plus a small sample of their ids, WITHOUT mutating any rows. Intended as the /// preview backing for admin destructive-operation confirmation flows. /// public async Task<(int Count, IReadOnlyList SampleSessionIds)> PreviewRevokeAllAsync( long userId, CancellationToken ct = default) { const int sampleSize = 10; var ids = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(s => s.Status == "active") .Select(o => o.Id) .ToListAsync() .ConfigureAwait(false); return (ids.Count, ids.Take(sampleSize).ToList()); } /// /// Signs the user out everywhere: every active session, every authorization and every valid token of /// theirs is revoked, so nothing issued to the user keeps working. This is what a password change or /// reset, an operator's logout, a SCIM deactivation and a user disable rely on. /// /// Authorizations and tokens are written by the OpenIddict stores and keyed by the user's public /// subject (value_guid), not by the internal user id the sessions carry in Key. Tokens /// are revoked on their own, not only through their authorization: the password grant issues refresh /// tokens with no authorization row, and a revoked authorization leaves an already issued access token /// valid until it expires, while a revoked token entry is refused at introspection and on refresh. /// /// /// Every revocation is flushed via batched SaveAsync(IEnumerable<...>) rather than per /// row: a user with many consents and rotated refresh tokens would otherwise turn this into hundreds /// of round-trips. /// /// /// Number of sessions revoked. public async Task LogoutAsync(long userId, CancellationToken ct = default) { // 1. Revoke all active sessions var sessionCount = await RevokeAllAsync(userId, ct).ConfigureAwait(false); // 2. Every grant of the user, by public subject. var subject = await ResolveSubjectAsync(userId).ConfigureAwait(false); if (subject == Guid.Empty) return sessionCount; var auths = await _redb.Query() .WhereRedb(o => o.ValueGuid == subject) .Where(a => a.Status != "revoked") .ToListAsync() .ConfigureAwait(false); if (auths.Count > 0) { foreach (var auth in auths) auth.Props.Status = "revoked"; await _redb.SaveAsync(auths).ConfigureAwait(false); } var tokens = await _redb.Query() .WhereRedb(o => o.ValueGuid == subject) .Where(t => t.Status == "valid") .ToListAsync() .ConfigureAwait(false); if (tokens.Count > 0) { foreach (var token in tokens) Stores.TokenStatus.Set(token, global::OpenIddict.Abstractions.OpenIddictConstants.Statuses.Revoked); await _redb.SaveAsync(tokens).ConfigureAwait(false); } return sessionCount; } /// /// The user's public subject GUID \u2014 the sub of every token and the value_guid the /// OpenIddict stores key authorizations and tokens by. It lives on the UserProps object whose /// Key is the core user id. when the user has no such object, and /// then there are no grants to revoke either. /// private async Task ResolveSubjectAsync(long userId) { var userProps = await _redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); return userProps?.value_guid ?? Guid.Empty; } /// Session info DTO for API responses. public sealed class SessionInfo { public long SessionId { get; set; } public long UserId { get; set; } public long ApplicationObjectId { get; set; } public string? ClientId { get; set; } public string? ApplicationName { get; set; } public string Status { get; set; } = "active"; public DateTimeOffset? CreatedAt { get; set; } /// Client IP captured at session creation. null for non-HTTP transports. public string? IpAddress { get; set; } /// Raw User-Agent header at session creation. Truncated to 512 chars by extractor. public string? UserAgent { get; set; } /// Human-friendly device label (e.g. "Chrome 135 on Windows 10") parsed from . public string? DeviceLabel { get; set; } /// S-track: last activity timestamp (refresh_token / cookie / userinfo). Null on legacy rows. public DateTimeOffset? LastAccessedAt { get; set; } /// S-track: label of the most recent activity that bumped . public string? LastAccessedBy { get; set; } } } Path: redb-identity/src/redb.Identity.Core/Services/SmsMfaMethod.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/Services/SmsMfaMethod.cs ---- using redb.Identity.Core.Mfa; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// SMS OTP MFA method. /// Stores the user's phone in . The OTP code itself /// is persisted server-side in (SHA-256 hashed, single-use /// under LockForUpdate) via — the encrypted /// only carries a jti reference (B3). /// internal sealed class SmsMfaMethod : IMfaMethod { private readonly IServerSideOtpStore? _otpStore; public SmsMfaMethod(IServerSideOtpStore? otpStore = null) { _otpStore = otpStore; } public string MethodId => "sms"; public Task InitiateSetupAsync(string username, string? destination = null, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(destination)) { return Task.FromResult(new MfaSetupInitiation { MethodId = MethodId, ClientResult = new MfaSetupResult { MethodId = MethodId, Extra = new Dictionary { ["error"] = "Phone number is required" } } }); } var phone = NormalizePhone(destination); if (phone is null) { return Task.FromResult(new MfaSetupInitiation { MethodId = MethodId, ClientResult = new MfaSetupResult { MethodId = MethodId, Extra = new Dictionary { ["error"] = "Invalid phone number format" } } }); } return Task.FromResult(new MfaSetupInitiation { MethodId = MethodId, Destination = phone, ClientResult = new MfaSetupResult { MethodId = MethodId, Extra = new Dictionary { ["masked_phone"] = MaskPhone(phone) } } }); } public async Task ConfirmAndApplyAsync(MfaProps props, MfaSetupInitiation initiation, string code, MfaState? state = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(props); ArgumentNullException.ThrowIfNull(initiation); if (string.IsNullOrEmpty(initiation.Destination)) return false; if (!await VerifyAgainstStateAsync(state, code, ct).ConfigureAwait(false)) return false; // Atomic apply. props.SmsPhone = initiation.Destination; props.SmsConfirmed = true; return true; } public Task VerifyAsync(MfaProps props, string code, MfaState? state = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(props); return VerifyAgainstStateAsync(state, code, ct); } private async Task VerifyAgainstStateAsync(MfaState? state, string code, CancellationToken ct) { if (state is null) return false; if (state.OtpMethod != MethodId) return false; if (string.IsNullOrEmpty(code)) return false; // B3: server-side OTP store is the authoritative source; jti must be present. if (_otpStore is null || !state.OtpJti.HasValue) return false; var res = await _otpStore.VerifyAndConsumeAsync(state.OtpJti.Value, state.UserId, code, ct).ConfigureAwait(false); return res.Success; } internal static string? NormalizePhone(string input) { if (string.IsNullOrWhiteSpace(input)) return null; var digits = new string(input.Where(c => char.IsDigit(c) || c == '+').ToArray()); var hasPlus = digits.StartsWith('+'); if (hasPlus) digits = digits[1..]; if (digits.Length < 10 || digits.Length > 15) return null; if (!digits.All(char.IsDigit)) return null; return "+" + digits; } internal static string MaskPhone(string phone) { if (string.IsNullOrEmpty(phone) || phone.Length <= 4) return "****"; // Keep leading "+" + first digit, mask middle, keep last 4 var prefix = phone.StartsWith('+') ? phone[..2] : phone[..1]; return prefix + "***" + phone[^4..]; } } Path: redb-identity/src/redb.Identity.Core/Services/SmtpEmailNotificationChannel.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/Services/SmtpEmailNotificationChannel.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Configuration; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Services; /// /// N-4 (Session C): production backed by the /// redb.Route.Mail SMTP DSL. Renders the requested template through /// and forwards the resulting message to /// , which the host route builder wires to a /// Smtp.Send(...) producer when is true. /// /// The channel only knows about route URIs and exchange headers — concrete SMTP details /// (host / port / credentials / TLS) live entirely on the route definition, exactly as /// the rest of the redb.Route ecosystem expects. This keeps the abstraction transport- /// agnostic: swapping SMTP for SendGrid is a route change, not a channel change. /// /// public sealed class SmtpEmailNotificationChannel : IEmailNotificationChannel, IDisposable { private readonly IRouteContext _routeContext; private readonly IEmailTemplateRegistry _registry; private readonly SmtpOptions _smtp; private readonly ILogger _logger; private readonly object _producerLock = new(); private IProducerTemplate? _producer; private bool _disposed; public SmtpEmailNotificationChannel( IRouteContext routeContext, IEmailTemplateRegistry registry, IOptions options, ILoggerFactory? loggerFactory = null) { _routeContext = routeContext ?? throw new ArgumentNullException(nameof(routeContext)); _registry = registry ?? throw new ArgumentNullException(nameof(registry)); _smtp = options.Value.Smtp; _logger = loggerFactory?.CreateLogger() ?? (ILogger)NullLogger.Instance; } /// public async Task SendTemplateAsync( string to, string templateId, IReadOnlyDictionary vars, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(to); ArgumentException.ThrowIfNullOrWhiteSpace(templateId); ArgumentNullException.ThrowIfNull(vars); // Render the template using the host-supplied registry. Locale negotiation lives // there; this channel only forwards the rendered output to the SMTP route. var rendered = await _registry.RenderAsync(templateId, locale: null, vars, ct).ConfigureAwait(false); var message = new Message { Body = rendered.HtmlBody ?? rendered.TextBody ?? string.Empty }; message.Headers["redbMail.To"] = to; message.Headers["redbMail.Subject"] = rendered.Subject ?? string.Empty; if (!string.IsNullOrWhiteSpace(_smtp.FromAddress)) message.Headers["redbMail.From"] = _smtp.FromAddress; // Force the SMTP component to treat the body as HTML and use TextBody as the // plain-text alternative — see redb.Route.Mail.SmtpComponent.BuildMimeMessage. message.Headers["redbMail.ContentType"] = "text/html"; if (!string.IsNullOrWhiteSpace(rendered.TextBody)) message.Headers["redbMail.TextBody"] = rendered.TextBody!; var producer = EnsureProducer(); try { await producer.SendAsync(IdentityEndpoints.EmailSend, message).ConfigureAwait(false); } catch (Exception ex) { // Mirrors PasswordForgotProcessor's expectation that channel implementations // surface fatal issues but absorb transient ones. We log + rethrow so the // processor can keep the anti-enumeration contract (it catches and degrades). // The recipient address is left out: it is personal data, and the template and the // endpoint are what an operator needs to find a failing mail route. _logger.LogError(ex, "SmtpEmailNotificationChannel: send via {Endpoint} failed for template {TemplateId}", IdentityEndpoints.EmailSend, templateId); throw; } } private IProducerTemplate EnsureProducer() { if (_producer is { IsStarted: true }) return _producer; lock (_producerLock) { if (_disposed) throw new ObjectDisposedException(nameof(SmtpEmailNotificationChannel)); if (_producer is { IsStarted: true }) return _producer; var p = new ProducerTemplate(_routeContext); p.Start(); _producer = p; return _producer; } } public void Dispose() { if (_disposed) return; lock (_producerLock) { if (_disposed) return; _disposed = true; (_producer as IDisposable)?.Dispose(); _producer = null; } } } Path: redb-identity/src/redb.Identity.Core/Services/TotpMfaMethod.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/Services/TotpMfaMethod.cs ---- using System.Security.Cryptography; using OtpNet; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// TOTP (RFC 6238) MFA method using Otp.NET. /// Stateless: receives and operates on its TOTP fields. /// internal sealed class TotpMfaMethod : IMfaMethod { public string MethodId => "totp"; private readonly MfaSecretProtector _secretProtector; private readonly string _issuerName; private readonly int _secretLength = 20; // 160 bit per RFC 4226 private readonly int _codeDigits = 6; private readonly int _periodSeconds = 30; private readonly int _skewSteps = 1; // ±30s tolerance public TotpMfaMethod(MfaSecretProtector secretProtector, string issuerName = "redb.Identity") { _secretProtector = secretProtector; _issuerName = issuerName; } public Task InitiateSetupAsync(string username, string? destination = null, CancellationToken ct = default) { // destination is ignored for TOTP — the secret is generated server-side. var key = RandomNumberGenerator.GetBytes(_secretLength); var base32Secret = Base32Encoding.ToString(key); var encryptedSecret = _secretProtector.Protect(base32Secret); var qrUri = $"otpauth://totp/{Uri.EscapeDataString(_issuerName)}:{Uri.EscapeDataString(username)}" + $"?secret={base32Secret}&issuer={Uri.EscapeDataString(_issuerName)}" + $"&digits={_codeDigits}&period={_periodSeconds}"; var clientResult = new MfaSetupResult { MethodId = MethodId, SecretBase32 = base32Secret, QrUri = qrUri }; return Task.FromResult(new MfaSetupInitiation { MethodId = MethodId, EncryptedSecret = encryptedSecret, ClientResult = clientResult }); } public Task ConfirmAndApplyAsync(MfaProps props, MfaSetupInitiation initiation, string code, MfaState? state = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(props); ArgumentNullException.ThrowIfNull(initiation); if (string.IsNullOrEmpty(initiation.EncryptedSecret)) return Task.FromResult(false); // Verify the supplied code against the candidate secret WITHOUT touching props yet. if (!TryVerifyCodeWithSecret(initiation.EncryptedSecret, code, out var step)) return Task.FromResult(false); // Atomic apply: secret + confirmation flag + replay-protection seed. props.TotpSecret = initiation.EncryptedSecret; props.TotpConfirmed = true; props.LastTotpStep = step; return Task.FromResult(true); } public Task VerifyAsync(MfaProps props, string code, MfaState? state = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(props); // state is ignored for TOTP. if (!TryVerifyCode(props, code, out var step)) return Task.FromResult(false); // RFC 6238 §5.2: reject codes from a previously accepted (or earlier) time-step // to prevent replay within the verification window. // Caller (B1) must hold a row-lock + transaction so two concurrent verifies for the // same user serialize on the read-then-write of LastTotpStep. if (props.LastTotpStep.HasValue && step <= props.LastTotpStep.Value) return Task.FromResult(false); props.LastTotpStep = step; return Task.FromResult(true); } private bool TryVerifyCode(MfaProps props, string code, out long step) { if (string.IsNullOrEmpty(props.TotpSecret)) { step = 0; return false; } return TryVerifyCodeWithSecret(props.TotpSecret, code, out step); } private bool TryVerifyCodeWithSecret(string encryptedSecret, string code, out long step) { step = 0; if (string.IsNullOrEmpty(encryptedSecret) || string.IsNullOrEmpty(code)) return false; var base32Secret = _secretProtector.Unprotect(encryptedSecret); if (base32Secret is null) return false; var key = Base32Encoding.ToBytes(base32Secret); var totp = new Totp(key, step: _periodSeconds, totpSize: _codeDigits); var window = new VerificationWindow(previous: _skewSteps, future: _skewSteps); return totp.VerifyTotp(code, out step, window); } } Path: redb-identity/src/redb.Identity.Core/Services/UserProfileService.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/Services/UserProfileService.cs ---- using System.Security.Claims; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Core.OpenIddict; namespace redb.Identity.Core.Services; /// /// Default implementation of . /// Loads Core user + OIDC extension + group memberships in a single call, /// then builds the ClaimsPrincipal via /// and enriches with group/role claims via . /// internal sealed class UserProfileService : IUserProfileService { private readonly IRedbService _redb; private readonly ILogger _logger; public UserProfileService(IRedbService redb, ILogger logger) { _redb = redb; _logger = logger; } public async Task BuildPrincipalAsync( long userId, IEnumerable scopes, bool mfaVerified = false, string? mfaMethod = null, OidcClaimsRequest? claimsRequest = null, CancellationToken ct = default) { var coreUser = await _redb.UserProvider.GetUserByIdAsync(userId).ConfigureAwait(false); if (coreUser is null) { _logger.LogWarning("UserProfileService: user {UserId} not found", userId); return null; } if (!coreUser.Enabled) { _logger.LogWarning("UserProfileService: user {UserId} is disabled", userId); return null; } // Load OIDC profile extension (may not exist for users without profile data) var oidcObj = await _redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync() .ConfigureAwait(false); // The public sub claim is the value_guid on the user's UserProps envelope. If // the legacy record has none, lazy-create one and persist so subsequent logins // get the same GUID. Guid subjectGuid; if (oidcObj is null) { oidcObj = new RedbObject(new UserProps()) { name = coreUser.Login, key = coreUser.Id, value_guid = Guid.NewGuid() }; await _redb.SaveAsync(oidcObj).ConfigureAwait(false); subjectGuid = oidcObj.value_guid!.Value; } else if (oidcObj.value_guid is null || oidcObj.value_guid == Guid.Empty) { oidcObj.value_guid = Guid.NewGuid(); await _redb.SaveAsync(oidcObj).ConfigureAwait(false); subjectGuid = oidcObj.value_guid.Value; } else { subjectGuid = oidcObj.value_guid.Value; } var scopeList = scopes as IReadOnlyList ?? scopes.ToList(); // Build base principal with standard OIDC claims (incl. amr if MFA verified) var principal = IdentityPrincipalBuilder.Build( coreUser, subjectGuid, oidcObj.Props, scopeList, mfaVerified, mfaMethod, claimsRequest); // Enrich with group/role claims var resolver = new GroupClaimsResolver(_redb); await resolver.EnrichPrincipalAsync(principal, userId, scopeList, ct).ConfigureAwait(false); return principal; } /// /// Fast-path overload: caller (e.g. LoginService.AuthenticateAsync) has already /// loaded the Core user, OIDC props, and resolved the subject GUID — skip the redundant /// _users + UserProps round-trips. Group memberships are still loaded on /// demand when groups / roles scopes are requested. /// public async Task BuildPrincipalAsync( IRedbUser user, UserProps? oidcProps, Guid subjectGuid, IEnumerable scopes, bool mfaVerified = false, string? mfaMethod = null, CancellationToken ct = default) { if (!user.Enabled) { _logger.LogWarning("UserProfileService: user {UserId} is disabled", user.Id); return null; } var scopeList = scopes as IReadOnlyList ?? scopes.ToList(); var principal = IdentityPrincipalBuilder.Build(user, subjectGuid, oidcProps, scopeList, mfaVerified, mfaMethod); var resolver = new GroupClaimsResolver(_redb); await resolver.EnrichPrincipalAsync(principal, user.Id, scopeList, ct).ConfigureAwait(false); return principal; } } Path: redb-identity/src/redb.Identity.Core/Services/WebAuthnMfaMethod.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/Services/WebAuthnMfaMethod.cs ---- using System.Globalization; using System.Security.Cryptography; using Fido2NetLib; using Fido2NetLib.Objects; using Microsoft.Extensions.Options; using redb.Identity.Core.Configuration; using redb.Identity.Core.Exceptions; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// MFA-3: WebAuthn (FIDO2 / Passkey) MFA method backed by Fido2NetLib v4. /// /// Wraps with redb-Identity-specific concerns: /// /// /// UV-downgrade ratchet — registration parses authenticatorData /// flags (bit 0x04 = UV) and persists per-credential ; /// assertion BeginAssertion sets UserVerification = Required when ANY credential of the /// user has UV-on, and CompleteAssertion re-verifies authenticatorData UV bit per-credential /// and rejects with uv_downgrade if a UV-registered credential asserted without UV. /// AAGUID blocklist — the AAGUID parsed from /// is checked against /// at registration time; matched /// requests fail with aaguid_blocked. /// Sign-counter rollback — Fido2NetLib enforces /// StoredSignatureCounter ≥ stored value at MakeAssertionAsync; redb additionally /// double-checks here so the surface error is sign_counter_rollback rather than /// the library's internal exception type. /// /// /// All cryptographic verification (attestation parsing, signature verification, certificate /// chain validation against MDS3 if enabled) is delegated to Fido2NetLib — this class /// encapsulates only redb-specific glue. /// /// internal sealed class WebAuthnMfaMethod : IMfaMethod, IWebAuthnMfaMethod { public string MethodId => "webauthn"; private readonly IFido2 _fido2; private readonly IdentityWebAuthnOptions _options; private readonly HashSet _aaguidBlocklist; private readonly TimeProvider _timeProvider; public WebAuthnMfaMethod( IFido2 fido2, IOptions options, TimeProvider? timeProvider = null) { _fido2 = fido2 ?? throw new ArgumentNullException(nameof(fido2)); _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); _timeProvider = timeProvider ?? TimeProvider.System; // Pre-parse the blocklist into a HashSet for O(1) lookup. _aaguidBlocklist = new HashSet(); if (_options.AaguidBlocklist is { Count: > 0 }) { foreach (var entry in _options.AaguidBlocklist) if (Guid.TryParse(entry, out var g)) _aaguidBlocklist.Add(g); } } // ── IMfaMethod surface (intentionally throwing): orchestrator never reaches here ── private const string OrchestratorMisuse = "WebAuthn does not use the IMfaMethod OTP/code orchestration path. " + "Call MfaService.BeginWebAuthnRegistrationAsync / CompleteWebAuthnRegistrationAsync " + "/ BeginWebAuthnAssertionAsync / CompleteWebAuthnAssertionAsync instead."; public Task InitiateSetupAsync(string username, string? destination = null, CancellationToken ct = default) => throw new NotSupportedException(OrchestratorMisuse); public Task ConfirmAndApplyAsync(MfaProps props, MfaSetupInitiation initiation, string code, MfaState? state = null, CancellationToken ct = default) => throw new NotSupportedException(OrchestratorMisuse); public Task VerifyAsync(MfaProps props, string code, MfaState? state = null, CancellationToken ct = default) => throw new NotSupportedException(OrchestratorMisuse); // ── IWebAuthnMfaMethod surface ── /// public CredentialCreateOptions BeginRegistration( long userId, string username, string displayName, IReadOnlyDictionary? existingCredentials, bool enforceUv) { ArgumentNullException.ThrowIfNull(username); ArgumentNullException.ThrowIfNull(displayName); var fidoUser = new Fido2User { Id = EncodeUserHandle(userId), Name = username, DisplayName = displayName, }; var exclude = new List(); if (existingCredentials is { Count: > 0 }) { foreach (var c in existingCredentials.Values) exclude.Add(new PublicKeyCredentialDescriptor(c.CredentialId)); } // UV requirement: explicit if caller forces it (e.g. user already has UV creds), else // honour the global options default. Assertion-time ratchet adds an extra layer. var uvRequirement = enforceUv ? UserVerificationRequirement.Required : ParseUvRequirement(_options.UserVerification); var authSelection = new AuthenticatorSelection { UserVerification = uvRequirement, ResidentKey = ResidentKeyRequirement.Preferred, }; return _fido2.RequestNewCredential(new RequestNewCredentialParams { User = fidoUser, ExcludeCredentials = exclude, AuthenticatorSelection = authSelection, AttestationPreference = ParseAttestationPreference(_options.Attestation), }); } /// public async Task CompleteRegistrationAsync( AuthenticatorAttestationRawResponse attestationResponse, CredentialCreateOptions originalOptions, long userId, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(attestationResponse); ArgumentNullException.ThrowIfNull(originalOptions); // Fido2NetLib does the heavy crypto lifting. The IsCredentialIdUniqueToUser callback // is provided here purely as a defence-in-depth check — the orchestrator already holds // a row-lock on the user's MfaProps and re-checks before persistence, so this is a // belt-and-braces guard against a same-credential double-registration in the same TX. RegisteredPublicKeyCredential registered; try { registered = await _fido2.MakeNewCredentialAsync( new MakeNewCredentialParams { AttestationResponse = attestationResponse, OriginalOptions = originalOptions, IsCredentialIdUniqueToUserCallback = static (_, _) => Task.FromResult(true), }, ct).ConfigureAwait(false); } catch (Fido2VerificationException ex) { throw new WebAuthnException("attestation_failed", ex.Message, ex); } // AAGUID blocklist enforcement. Empty AAGUID (Guid.Empty) means "self attestation" // / sync passkey — there is no hardware identifier to gate, so we only check against // the blocklist when the AAGUID is set. if (registered.AaGuid != Guid.Empty && _aaguidBlocklist.Contains(registered.AaGuid)) { throw new WebAuthnException( "aaguid_blocked", $"Authenticator AAGUID {registered.AaGuid:D} is on the configured blocklist."); } // Parse UV/BE/BS flags out of the attestation's authenticatorData. Fido2NetLib v4 // does NOT surface UV directly on RegisteredPublicKeyCredential, so we derive it from // the raw attestation object's authData byte[32] (the flags byte). var authDataFlags = ExtractAuthenticatorDataFlags(attestationResponse); var uv = (authDataFlags & 0x04) != 0; return new WebAuthnCredential { CredentialId = registered.Id, PublicKey = registered.PublicKey, SignCount = registered.SignCount, DisplayName = null, Aaguid = registered.AaGuid != Guid.Empty ? registered.AaGuid.ToString("D", CultureInfo.InvariantCulture) : null, RegisteredAt = _timeProvider.GetUtcNow(), LastUsedAt = null, UserVerified = uv, BackupEligible = registered.IsBackupEligible, BackupState = registered.IsBackedUp, }; } /// public AssertionOptions BeginAssertion(IReadOnlyDictionary credentials) { ArgumentNullException.ThrowIfNull(credentials); var allowed = new List(credentials.Count); var anyUvCred = false; foreach (var c in credentials.Values) { allowed.Add(new PublicKeyCredentialDescriptor(c.CredentialId)); if (c.UserVerified) anyUvCred = true; } // Per-user UV ratchet. If at least one credential was registered with UV, demand UV // for every assertion of this user — the per-credential ratchet is finalized in // CompleteAssertionAsync (where the actual matched credential's UV flag is enforced). var uvRequirement = anyUvCred ? UserVerificationRequirement.Required : ParseUvRequirement(_options.UserVerification); return _fido2.GetAssertionOptions(new GetAssertionOptionsParams { AllowedCredentials = allowed, UserVerification = uvRequirement, }); } /// public async Task CompleteAssertionAsync( AuthenticatorAssertionRawResponse assertionResponse, AssertionOptions originalOptions, IReadOnlyDictionary credentials, long userId, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(assertionResponse); ArgumentNullException.ThrowIfNull(originalOptions); ArgumentNullException.ThrowIfNull(credentials); // Locate the credential the browser asserts about — match by raw byte equality on // CredentialId. The dictionary keys are user-friendly and not used for lookup here. WebAuthnCredential? matched = null; foreach (var c in credentials.Values) { if (BytesEqual(c.CredentialId, assertionResponse.RawId)) { matched = c; break; } } if (matched is null) { throw new WebAuthnException( "credential_not_found", "The asserted credentialId is not registered to this user."); } // Per-credential UV ratchet. Fido2NetLib enforces UV based on the OriginalOptions // (set globally per ceremony). When the matched credential was registered with UV // but the assertion lacks UV (e.g. attacker downgraded by toggling allowCredentials), // we reject before completing the verification so the failure has the correct code. var assertionFlags = ExtractAssertionAuthDataFlags(assertionResponse); var assertionUv = (assertionFlags & 0x04) != 0; if (matched.UserVerified && !assertionUv) { throw new WebAuthnException( "uv_downgrade", "Credential was registered with user-verification but assertion did not carry UV."); } VerifyAssertionResult result; try { result = await _fido2.MakeAssertionAsync( new MakeAssertionParams { AssertionResponse = assertionResponse, OriginalOptions = originalOptions, StoredPublicKey = matched.PublicKey, StoredSignatureCounter = (uint)matched.SignCount, IsUserHandleOwnerOfCredentialIdCallback = (p, _) => { // The user handle the browser echoed back must be the encoding of OUR userId. var expected = EncodeUserHandle(userId); var ok = p.UserHandle != null && CryptographicOperations.FixedTimeEquals(p.UserHandle, expected); return Task.FromResult(ok); }, }, ct).ConfigureAwait(false); } catch (Fido2VerificationException) { // Signature failure / counter rollback / origin mismatch / etc. — caller treats // null as "verification failed" and bumps FailedAttempts. return null; } // Belt-and-braces: re-check counter monotonicity. Fido2NetLib already enforces this // (Fido2VerificationException would have been thrown above when the new value goes // backwards), but converting to a typed exception lets the orchestrator tag the // audit event with the specific reason. Counter == 0 means the authenticator does // not implement counters (TouchID / Windows Hello / sync passkeys) — accept. if (result.SignCount != 0 && result.SignCount < matched.SignCount) { throw new WebAuthnException( "sign_counter_rollback", $"SignCount went backward: stored={matched.SignCount}, asserted={result.SignCount} — possible cloned credential."); } // Apply mutations onto the matched credential. Caller persists by saving MfaProps. matched.SignCount = result.SignCount; matched.LastUsedAt = _timeProvider.GetUtcNow(); matched.BackupState = result.IsBackedUp; return matched; } // ── helpers ── /// Encodes the numeric Identity userId as the WebAuthn user.handle (8-byte BE). internal static byte[] EncodeUserHandle(long userId) { var buf = new byte[8]; for (int i = 7; i >= 0; i--) { buf[i] = (byte)(userId & 0xff); userId >>= 8; } return buf; } /// Decodes the user handle back to userId (inverse of ). internal static bool TryDecodeUserHandle(byte[]? handle, out long userId) { userId = 0; if (handle is null || handle.Length != 8) return false; for (int i = 0; i < 8; i++) { userId = (userId << 8) | handle[i]; } return userId > 0; } private static bool BytesEqual(byte[] a, byte[] b) { if (a is null || b is null) return false; if (a.Length != b.Length) return false; return CryptographicOperations.FixedTimeEquals(a, b); } private static UserVerificationRequirement ParseUvRequirement(string value) => value switch { "required" => UserVerificationRequirement.Required, "discouraged" => UserVerificationRequirement.Discouraged, _ => UserVerificationRequirement.Preferred, }; private static AttestationConveyancePreference ParseAttestationPreference(string value) => value switch { "indirect" => AttestationConveyancePreference.Indirect, "direct" => AttestationConveyancePreference.Direct, "enterprise" => AttestationConveyancePreference.Enterprise, _ => AttestationConveyancePreference.None, }; /// /// Extracts the flags byte (offset 32) from authenticatorData found inside the attestation /// object's CBOR map. Throws with code malformed_attestation /// if the authData blob cannot be located. Bit 0x01 = UP, 0x04 = UV, 0x08 = BE, 0x10 = BS. /// private static byte ExtractAuthenticatorDataFlags(AuthenticatorAttestationRawResponse response) { var attObj = response.Response?.AttestationObject ?? throw new WebAuthnException("malformed_attestation", "Attestation response is missing the attestationObject blob."); var authData = ExtractAuthDataFromCbor(attObj); if (authData is null || authData.Length < 37) { throw new WebAuthnException("malformed_attestation", "Attestation authenticator data could not be parsed."); } return authData[32]; } /// /// Extracts the flags byte (offset 32) from the assertion response's authenticatorData. /// private static byte ExtractAssertionAuthDataFlags(AuthenticatorAssertionRawResponse response) { var authData = response.Response?.AuthenticatorData ?? throw new WebAuthnException("malformed_assertion", "Assertion response is missing authenticatorData."); if (authData.Length < 37) { throw new WebAuthnException("malformed_assertion", "Assertion authenticatorData is truncated (need ≥ 37 bytes for RpIdHash + flags + counter)."); } return authData[32]; } /// /// Minimal CBOR parser to pluck the authData byte-string out of an /// attestationObject. AttestationObject is a CBOR map with text-string keys /// (fmt, attStmt, authData); we walk the top-level map until we /// hit the authData key and return its byte-string value. /// private static byte[]? ExtractAuthDataFromCbor(byte[] cbor) { try { var reader = new System.Formats.Cbor.CborReader(cbor); var len = reader.ReadStartMap(); var iterations = len ?? int.MaxValue; for (var i = 0; i < iterations; i++) { if (reader.PeekState() == System.Formats.Cbor.CborReaderState.EndMap) break; var key = reader.ReadTextString(); if (string.Equals(key, "authData", StringComparison.Ordinal)) { return reader.ReadByteString(); } else { reader.SkipValue(); } } } catch { // Fall through; caller throws malformed_attestation. } return null; } } Path: redb-identity/src/redb.Identity.Core/Services/WebhookSubscriptionService.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/Services/WebhookSubscriptionService.cs ---- using System.Security.Cryptography; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// W1 — backing store for outbound webhook subscriptions. CRUD + filter /// evaluation + secret generation / rotation. The HTTP delivery is the /// route consumer's job (WebhookDeliveryRouteConsumer); this /// service is admin-side only. /// public sealed class WebhookSubscriptionService { private readonly IRedbService _redb; public WebhookSubscriptionService(IRedbService redb) => _redb = redb; public async Task> CreateAsync( string url, string? displayName, string? description, string? eventTypeFilter, bool enabled, int timeoutMs, int maxAttempts, int retryBackoffMs, Dictionary? extraHeaders, string? hmacSecret = null, CancellationToken ct = default) { var (urlErr, normalisedUrl) = ValidateUrl(url); if (urlErr is not null) throw new ArgumentException(urlErr, nameof(url)); // Operator-supplied secret takes precedence; auto-generate when blank. // Enforce a minimum length to keep weak secrets out of the store. string secret; if (!string.IsNullOrWhiteSpace(hmacSecret)) { if (hmacSecret.Length < 16) throw new ArgumentException("hmacSecret must be at least 16 characters.", nameof(hmacSecret)); secret = hmacSecret; } else { secret = GenerateHmacSecret(); } var obj = new RedbObject(new WebhookSubscriptionProps { DisplayName = string.IsNullOrWhiteSpace(displayName) ? null : displayName.Trim(), Description = description, Url = normalisedUrl, EventTypeFilter = string.IsNullOrWhiteSpace(eventTypeFilter) ? "*" : eventTypeFilter.Trim(), HmacSecret = secret, Enabled = enabled, TimeoutMs = Math.Clamp(timeoutMs, 500, 60_000), MaxAttempts = Math.Clamp(maxAttempts, 1, 10), RetryBackoffMs = Math.Clamp(retryBackoffMs, 50, 30_000), ExtraHeaders = extraHeaders, ConcurrencyToken = Guid.NewGuid().ToString("N") }) { name = displayName ?? new Uri(normalisedUrl).Host }; obj.id = await _redb.SaveAsync(obj).ConfigureAwait(false); return obj; } public async Task?> GetAsync(long id, CancellationToken ct = default) => await _redb.LoadAsync(id).ConfigureAwait(false); public async Task>> ListAsync(int offset, int count, CancellationToken ct = default) { return await _redb.Query() .OrderByRedb(o => o.Id) .Skip(offset) .Take(count) .ToListAsync() .ConfigureAwait(false); } public async Task CountAsync(CancellationToken ct = default) => (int)await _redb.Query().CountAsync().ConfigureAwait(false); /// /// Bulk-load every enabled subscription. Called once per event by the /// delivery consumer — for the worst case of a heavy operator wiring /// dozens of subscriptions this is still a single round-trip per /// event, beating per-subscription evaluation. Higher cardinalities /// should grow a small in-memory cache; not warranted at preview.1. /// public async Task>> ListEnabledAsync(CancellationToken ct = default) { return await _redb.Query() .Where(p => p.Enabled == true) .ToListAsync() .ConfigureAwait(false); } public async Task UpdateAsync( long id, string? displayName, string? description, string? url, string? eventTypeFilter, bool? enabled, int? timeoutMs, int? maxAttempts, int? retryBackoffMs, Dictionary? extraHeaders, CancellationToken ct = default) { var obj = await _redb.LoadAsync(id).ConfigureAwait(false) ?? throw new InvalidOperationException($"Webhook subscription {id} not found."); if (displayName is not null) obj.Props.DisplayName = string.IsNullOrWhiteSpace(displayName) ? null : displayName.Trim(); if (description is not null) obj.Props.Description = description; if (url is not null) { var (urlErr, normalised) = ValidateUrl(url); if (urlErr is not null) throw new ArgumentException(urlErr, nameof(url)); obj.Props.Url = normalised; } if (eventTypeFilter is not null) obj.Props.EventTypeFilter = string.IsNullOrWhiteSpace(eventTypeFilter) ? "*" : eventTypeFilter.Trim(); if (enabled.HasValue) obj.Props.Enabled = enabled.Value; if (timeoutMs.HasValue) obj.Props.TimeoutMs = Math.Clamp(timeoutMs.Value, 500, 60_000); if (maxAttempts.HasValue) obj.Props.MaxAttempts = Math.Clamp(maxAttempts.Value, 1, 10); if (retryBackoffMs.HasValue) obj.Props.RetryBackoffMs = Math.Clamp(retryBackoffMs.Value, 50, 30_000); if (extraHeaders is not null) obj.Props.ExtraHeaders = extraHeaders; obj.Props.ConcurrencyToken = Guid.NewGuid().ToString("N"); await _redb.SaveAsync(obj).ConfigureAwait(false); } public async Task DeleteAsync(long id, CancellationToken ct = default) { var obj = await _redb.LoadAsync(id).ConfigureAwait(false); if (obj is null) return; await _redb.DeleteAsync(obj).ConfigureAwait(false); } /// /// Generate a fresh secret, update the row, return the new value. The /// previous value is irrecoverable after this — receivers MUST be /// updated atomically. /// public async Task RotateSecretAsync(long id, CancellationToken ct = default) { var obj = await _redb.LoadAsync(id).ConfigureAwait(false) ?? throw new InvalidOperationException($"Webhook subscription {id} not found."); var newSecret = GenerateHmacSecret(); obj.Props.HmacSecret = newSecret; obj.Props.ConcurrencyToken = Guid.NewGuid().ToString("N"); await _redb.SaveAsync(obj).ConfigureAwait(false); return newSecret; } /// /// True when the subscription should receive the given event id / /// category pair. Public so the delivery consumer can call directly. /// public static bool Matches(WebhookSubscriptionProps sub, string eventType, string? category) { if (!sub.Enabled) return false; var filter = sub.EventTypeFilter?.Trim(); if (string.IsNullOrEmpty(filter) || filter == "*") return true; var tokens = filter.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); foreach (var token in tokens) { if (token.StartsWith("cat:", StringComparison.OrdinalIgnoreCase)) { var wantedCategory = token.Substring(4); if (!string.IsNullOrEmpty(category) && string.Equals(category, wantedCategory, StringComparison.OrdinalIgnoreCase)) return true; } else { if (string.Equals(eventType, token, StringComparison.OrdinalIgnoreCase)) return true; } } return false; } // ── Helpers ──────────────────────────────────────────────── private static (string? Error, string Normalised) ValidateUrl(string url) { if (string.IsNullOrWhiteSpace(url)) return ("url is required", ""); if (!Uri.TryCreate(url, UriKind.Absolute, out var u)) return ("url must be an absolute http(s) URL", url); if (u.Scheme != Uri.UriSchemeHttp && u.Scheme != Uri.UriSchemeHttps) return ("url scheme must be http or https", url); if (!string.IsNullOrEmpty(u.Fragment)) return ("url fragment is not allowed", url); return (null, u.ToString()); } private static string GenerateHmacSecret() { var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); return Convert.ToHexString(bytes); } } Path: redb-identity/src/redb.Identity.Core/Stores/RedbApplicationStore.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/Stores/RedbApplicationStore.cs ---- using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Text.Json; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Services; using redb.Identity.Core.Models; using redb.Identity.Core.Services; namespace redb.Identity.Core.Stores; /// /// OpenIddict application store backed by redb PROPS storage. /// Entity type: . /// internal sealed class RedbApplicationStore : IOpenIddictApplicationStore> { private readonly IRedbService _redb; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly ILogger? _logger; // [STORE-DIAG] per-request call counters & cumulative ms. // Store is Scoped, so these track one HTTP request only. private int _fbcidCalls, _fbcidHits, _fbidCalls; private long _fbcidMs, _fbidMs; // Per-request cache: store is Scoped (one instance per HTTP request), so this // dict lives only for the lifetime of one OIDC pipeline invocation. OpenIddict // built-in handlers call FindByClientIdAsync 8-11× per /connect/token request // for the same client_id; without a cache each call hits PVT join (~8ms each). // Caches null too — defends against repeated lookups for unknown client_ids. private readonly Dictionary?> _clientIdCache = new(StringComparer.Ordinal); private readonly IClientKeyResolver? _keyResolver; public RedbApplicationStore( IRedbService redb, IBackgroundDeletionService? backgroundDeletion = null, ILogger? logger = null, IClientKeyResolver? keyResolver = null) { ArgumentNullException.ThrowIfNull(redb); _redb = redb; _backgroundDeletion = backgroundDeletion; _logger = logger; _keyResolver = keyResolver; } public async ValueTask CountAsync(CancellationToken cancellationToken) { return await _redb.Query() .CountAsync() .ConfigureAwait(false); } public async ValueTask CountAsync( Func>, IQueryable> query, CancellationToken cancellationToken) { // OpenIddict managers do NOT call this internally — external code only. // Delegate to server-side CountAsync when the projected query is trivial. return await CountAsync(cancellationToken); } public async ValueTask CreateAsync(RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.id = await _redb.SaveAsync(application).ConfigureAwait(false); if ((application.Props.ClientId ?? application.value_string) is { } cid) _clientIdCache[cid] = application; } public async ValueTask DeleteAsync(RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); // Identity-wide deletion pattern: enqueue via background service if available, // otherwise fall back to SoftDelete. Application drags Authorization/Token cascades — // hard-delete here would block the request thread. await IdentityDeletionHelper.DeleteAsync(_redb, _backgroundDeletion, application.id).ConfigureAwait(false); if ((application.Props.ClientId ?? application.value_string) is { } cid) _clientIdCache.Remove(cid); } public async ValueTask?> FindByIdAsync( string identifier, CancellationToken cancellationToken) { if (!long.TryParse(identifier, out var id)) return null; var sw = Stopwatch.GetTimestamp(); // Use Query<>(): it filters out soft-deleted objects (trash scheme). // LoadAsync<>() loads by primary key and ignores deletion state. var app = await _redb.Query() .WhereRedb(o => o.Id == id) .FirstOrDefaultAsync() .ConfigureAwait(false); var ms = (long)Stopwatch.GetElapsedTime(sw).TotalMilliseconds; var n = ++_fbidCalls; _fbidMs += ms; _logger?.LogDebug("[STORE-DIAG] App.FindById call#{N} ms={Ms} cum={Cum} id={Id}", n, ms, _fbidMs, identifier); return app; } public async ValueTask?> FindByClientIdAsync( string identifier, CancellationToken cancellationToken) { if (_clientIdCache.TryGetValue(identifier, out var cached)) { var nh = ++_fbcidCalls; _fbcidHits++; _logger?.LogDebug("[STORE-DIAG] App.FindByClientId call#{N} HIT hits={Hits} cum={Cum} cid={Cid}", nh, _fbcidHits, _fbcidMs, identifier); return cached; } var sw = Stopwatch.GetTimestamp(); // V4-UNIQUE: one probe of the unique index ([RedbUnique] ClientId) instead of a scheme // query on the value_string mirror. Hot path: 8-11 calls per /connect/token request. // No Hydrate: an object found by its unique key has Props loaded from _values. var app = await _redb.GetByUniqueAsync(p => p.ClientId, identifier) .ConfigureAwait(false); _clientIdCache[identifier] = app; var ms = (long)Stopwatch.GetElapsedTime(sw).TotalMilliseconds; var n = ++_fbcidCalls; _fbcidMs += ms; _logger?.LogDebug("[STORE-DIAG] App.FindByClientId call#{N} MISS ms={Ms} cum={Cum} cid={Cid}", n, ms, _fbcidMs, identifier); return app; } public async IAsyncEnumerable> FindByPostLogoutRedirectUriAsync( string uri, [EnumeratorCancellation] CancellationToken cancellationToken) { // Array.Contains — verified working in redb PROPS (see E050_ArrayContains) var results = await _redb.Query() .Where(a => a.PostLogoutRedirectUris != null && a.PostLogoutRedirectUris.Contains(uri)) .ToListAsync() .ConfigureAwait(false); foreach (var result in results) yield return result; } public async IAsyncEnumerable> FindByRedirectUriAsync( string uri, [EnumeratorCancellation] CancellationToken cancellationToken) { var results = await _redb.Query() .Where(a => a.RedirectUris != null && a.RedirectUris.Contains(uri)) .ToListAsync() .ConfigureAwait(false); foreach (var result in results) yield return result; } public ValueTask GetApplicationTypeAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.Props.ApplicationType); } public ValueTask GetAsync( Func>, TState, IQueryable> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException( "Func cannot be translated to server-side queries. Use _redb.Query() directly."); } public ValueTask GetClientIdAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); // Props is the source of truth; value_string covers not-yet-backfilled legacy rows. return new(application.Props.ClientId ?? application.value_string); } public ValueTask GetClientSecretAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.Props.ClientSecret); } public ValueTask GetClientTypeAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.Props.ClientType); } public ValueTask GetConsentTypeAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.Props.ConsentType); } public ValueTask GetDisplayNameAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.name); } public ValueTask> GetDisplayNamesAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); var names = application.Props.DisplayNames; if (names is null || names.Count == 0) return new(ImmutableDictionary.Empty); var builder = ImmutableDictionary.CreateBuilder(); foreach (var (key, value) in names) builder[CultureInfo.GetCultureInfo(key)] = value; return new(builder.ToImmutable()); } public ValueTask GetIdAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.id.ToString()); } public ValueTask GetJsonWebKeySetAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); if (!string.IsNullOrEmpty(application.Props.JsonWebKeySet)) return new(JsonWebKeySet.Create(application.Props.JsonWebKeySet)); // RFC 7591 §2: without an inline set, the keys the client publishes at jwks_uri verify its client // assertions (private_key_jwt), through the same guarded and cached fetch as JAR request objects. if (_keyResolver is not null && !string.IsNullOrWhiteSpace(application.Props.JwksUri)) return _keyResolver.GetJsonWebKeySetAsync(application, forceRefresh: false, cancellationToken); return new(result: null); } public ValueTask> GetPermissionsAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.Props.Permissions?.ToImmutableArray() ?? []); } public ValueTask> GetPostLogoutRedirectUrisAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.Props.PostLogoutRedirectUris?.ToImmutableArray() ?? []); } public ValueTask> GetPropertiesAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); var props = application.Props.Properties; if (props is null || props.Count == 0) return new(ImmutableDictionary.Empty); var builder = ImmutableDictionary.CreateBuilder(); foreach (var (key, value) in props) builder[key] = JsonSerializer.Deserialize(value); return new(builder.ToImmutable()); } public ValueTask> GetRedirectUrisAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.Props.RedirectUris?.ToImmutableArray() ?? []); } public ValueTask> GetRequirementsAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); return new(application.Props.Requirements?.ToImmutableArray() ?? []); } public ValueTask> GetSettingsAsync( RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); var settings = application.Props.Settings; if (settings is null || settings.Count == 0) return new(ImmutableDictionary.Empty); return new(settings.ToImmutableDictionary()); } public ValueTask> InstantiateAsync(CancellationToken cancellationToken) { return new(new RedbObject { Props = new ApplicationProps() }); } public async IAsyncEnumerable> ListAsync( int? count, int? offset, [EnumeratorCancellation] CancellationToken cancellationToken) { IRedbQueryable query = _redb.Query().OrderByRedb(o => o.Id); if (offset.HasValue) query = query.Skip(offset.Value); if (count.HasValue) query = query.Take(count.Value); var results = await query.ToListAsync().ConfigureAwait(false); foreach (var result in results) yield return result; } public IAsyncEnumerable ListAsync( Func>, TState, IQueryable> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException( "Func cannot be translated to server-side queries. Use _redb.Query() directly."); } public ValueTask SetApplicationTypeAsync( RedbObject application, string? type, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.ApplicationType = type; return default; } public ValueTask SetClientIdAsync( RedbObject application, string? identifier, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.ClientId = identifier; return default; } public ValueTask SetClientSecretAsync( RedbObject application, string? secret, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.ClientSecret = secret; return default; } public ValueTask SetClientTypeAsync( RedbObject application, string? type, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.ClientType = type; return default; } public ValueTask SetConsentTypeAsync( RedbObject application, string? type, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.ConsentType = type; return default; } public ValueTask SetDisplayNameAsync( RedbObject application, string? name, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.name = name; return default; } public ValueTask SetDisplayNamesAsync( RedbObject application, ImmutableDictionary names, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.DisplayNames = names.ToDictionary( kvp => kvp.Key.Name, kvp => kvp.Value); return default; } public ValueTask SetJsonWebKeySetAsync( RedbObject application, JsonWebKeySet? set, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.JsonWebKeySet = set is not null ? JsonSerializer.Serialize(set) : null; return default; } public ValueTask SetPermissionsAsync( RedbObject application, ImmutableArray permissions, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.Permissions = permissions.IsDefaultOrEmpty ? null : [.. permissions]; return default; } public ValueTask SetPostLogoutRedirectUrisAsync( RedbObject application, ImmutableArray uris, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.PostLogoutRedirectUris = uris.IsDefaultOrEmpty ? null : [.. uris]; return default; } public ValueTask SetPropertiesAsync( RedbObject application, ImmutableDictionary properties, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); if (properties is null || properties.IsEmpty) { application.Props.Properties = null; return default; } application.Props.Properties = properties.ToDictionary( kvp => kvp.Key, kvp => kvp.Value.GetRawText()); return default; } public ValueTask SetRedirectUrisAsync( RedbObject application, ImmutableArray uris, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.RedirectUris = uris.IsDefaultOrEmpty ? null : [.. uris]; return default; } public ValueTask SetRequirementsAsync( RedbObject application, ImmutableArray requirements, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.Requirements = requirements.IsDefaultOrEmpty ? null : [.. requirements]; return default; } public ValueTask SetSettingsAsync( RedbObject application, ImmutableDictionary settings, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); application.Props.Settings = settings is null || settings.IsEmpty ? null : settings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); return default; } public async ValueTask UpdateAsync(RedbObject application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); // C11: cluster-safe atomic update — see RedbTokenStore.UpdateAsync. await _redb.Context.ExecuteAtomicAsync(async () => { await _redb.LockForUpdateAsync(application.id).ConfigureAwait(false); var current = await _redb.LoadAsync(application.id).ConfigureAwait(false); if (current is null) throw new OpenIddictExceptions.ConcurrencyException("The application was concurrently deleted."); if (current.hash != application.hash) throw new OpenIddictExceptions.ConcurrencyException("The application was concurrently updated."); await _redb.SaveAsync(application).ConfigureAwait(false); }).ConfigureAwait(false); if ((application.Props.ClientId ?? application.value_string) is { } cid) _clientIdCache[cid] = application; } } Path: redb-identity/src/redb.Identity.Core/Stores/RedbAuthorizationStore.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/Stores/RedbAuthorizationStore.cs ---- using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.Json; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Services; using redb.Identity.Core.Models; using redb.Identity.Core.Services; namespace redb.Identity.Core.Stores; /// /// OpenIddict authorization store backed by redb storage. /// Entity type: . /// Subject (GUID) → RedbObject.value_guid, CreationDate → RedbObject.date_create. /// internal sealed class RedbAuthorizationStore : IOpenIddictAuthorizationStore> { /// Default batch size for prune / soft-delete operations. private const int PruneBatchSize = 500; private readonly IRedbService _redb; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly ILogger? _logger; // [STORE-DIAG] per-request call counters & cumulative ms (Scoped store). private int _fbidCalls, _fbappCalls, _fbsubCalls; private long _fbidMs, _fbappMs, _fbsubMs; // Per-request cache: store is Scoped (one HTTP request). // OpenIddict resolves authorization-id during token validation/issuance — // cache spares repeat PVT joins. private readonly Dictionary?> _idCache = new(); public RedbAuthorizationStore( IRedbService redb, IBackgroundDeletionService? backgroundDeletion = null, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(redb); _redb = redb; _backgroundDeletion = backgroundDeletion; _logger = logger; } public async ValueTask CountAsync(CancellationToken cancellationToken) { return await _redb.Query() .CountAsync() .ConfigureAwait(false); } public async ValueTask CountAsync( Func>, IQueryable> query, CancellationToken cancellationToken) { // OpenIddict managers do NOT call this internally — external code only. // Delegate to server-side CountAsync when the projected query is trivial. return await CountAsync(cancellationToken); } public async ValueTask CreateAsync(RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); authorization.id = await _redb.SaveAsync(authorization).ConfigureAwait(false); _idCache[authorization.id] = authorization; } public async ValueTask DeleteAsync(RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); // Authorization drags child Tokens via cascade — never hard-delete on the request thread. await IdentityDeletionHelper.DeleteAsync(_redb, _backgroundDeletion, authorization.id).ConfigureAwait(false); _idCache.Remove(authorization.id); } public async IAsyncEnumerable> FindAsync( string? subject, string? client, string? status, string? type, ImmutableArray? scopes, [EnumeratorCancellation] CancellationToken cancellationToken) { var query = _redb.Query(); if (!string.IsNullOrEmpty(subject) && Guid.TryParse(subject, out var subjectGuid)) query = query.WhereRedb(o => o.ValueGuid == subjectGuid); if (!string.IsNullOrEmpty(client) && long.TryParse(client, out var clientId)) query = query.Where(a => a.ApplicationObjectId == clientId); if (!string.IsNullOrEmpty(status)) query = query.Where(a => a.Status == status); if (!string.IsNullOrEmpty(type)) query = query.Where(a => a.Type == type); var results = await query.ToListAsync().ConfigureAwait(false); foreach (var result in results) { // Scope subset filter applied in memory (redb has no "contains all" operator) if (scopes is { IsDefaultOrEmpty: false } s) { var entityScopes = result.Props.Scopes ?? []; if (!s.All(scope => entityScopes.Contains(scope))) continue; } yield return result; } } public async IAsyncEnumerable> FindByApplicationIdAsync( string identifier, [EnumeratorCancellation] CancellationToken cancellationToken) { if (!long.TryParse(identifier, out var appId)) yield break; var sw = Stopwatch.GetTimestamp(); var results = await _redb.Query() .Where(a => a.ApplicationObjectId == appId) .ToListAsync() .ConfigureAwait(false); var ms = (long)Stopwatch.GetElapsedTime(sw).TotalMilliseconds; var n = ++_fbappCalls; _fbappMs += ms; _logger?.LogDebug("[STORE-DIAG] Auth.FindByAppId call#{N} ms={Ms} cum={Cum} count={Count} appId={AppId}", n, ms, _fbappMs, results.Count, identifier); foreach (var result in results) yield return result; } public async ValueTask?> FindByIdAsync( string identifier, CancellationToken cancellationToken) { if (!long.TryParse(identifier, out var id)) return null; if (_idCache.TryGetValue(id, out var cached)) { var nh = ++_fbidCalls; _logger?.LogDebug("[STORE-DIAG] Auth.FindById call#{N} HIT cum={Cum} id={Id}", nh, _fbidMs, identifier); return cached; } var sw = Stopwatch.GetTimestamp(); // Use Query<>(): it filters out soft-deleted objects (trash scheme). // LoadAsync<>() loads by primary key and ignores deletion state. var auth = await _redb.Query() .WhereRedb(o => o.Id == id) .FirstOrDefaultAsync() .ConfigureAwait(false); _idCache[id] = auth; var ms = (long)Stopwatch.GetElapsedTime(sw).TotalMilliseconds; var n = ++_fbidCalls; _fbidMs += ms; _logger?.LogDebug("[STORE-DIAG] Auth.FindById call#{N} MISS ms={Ms} cum={Cum} id={Id}", n, ms, _fbidMs, identifier); return auth; } public async IAsyncEnumerable> FindBySubjectAsync( string subject, [EnumeratorCancellation] CancellationToken cancellationToken) { if (!Guid.TryParse(subject, out var subjectGuid)) yield break; var sw = Stopwatch.GetTimestamp(); var results = await _redb.Query() .WhereRedb(o => o.ValueGuid == subjectGuid) .ToListAsync() .ConfigureAwait(false); var ms = (long)Stopwatch.GetElapsedTime(sw).TotalMilliseconds; var n = ++_fbsubCalls; _fbsubMs += ms; _logger?.LogDebug("[STORE-DIAG] Auth.FindBySubject call#{N} ms={Ms} cum={Cum} count={Count} sub={Sub}", n, ms, _fbsubMs, results.Count, subject); foreach (var result in results) yield return result; } public ValueTask GetApplicationIdAsync( RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); var appId = authorization.Props.ApplicationObjectId; return new(appId != 0 ? appId.ToString() : null); } public ValueTask GetAsync( Func>, TState, IQueryable> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException( "Func cannot be translated to server-side queries. Use _redb.Query() directly."); } public ValueTask GetCreationDateAsync( RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); return new(authorization.date_create); } public ValueTask GetIdAsync( RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); return new(authorization.id.ToString()); } public ValueTask> GetPropertiesAsync( RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); var props = authorization.Props.Properties; if (props is null || props.Count == 0) return new(ImmutableDictionary.Empty); var builder = ImmutableDictionary.CreateBuilder(); foreach (var (key, value) in props) builder[key] = JsonSerializer.Deserialize(value); return new(builder.ToImmutable()); } public ValueTask> GetScopesAsync( RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); return new(authorization.Props.Scopes?.ToImmutableArray() ?? []); } public ValueTask GetStatusAsync( RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); return new(authorization.Props.Status); } public ValueTask GetSubjectAsync( RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); return new(authorization.value_guid?.ToString("D")); } public ValueTask GetTypeAsync( RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); return new(authorization.Props.Type); } public ValueTask> InstantiateAsync(CancellationToken cancellationToken) { return new(new RedbObject { Props = new AuthorizationProps() }); } public async IAsyncEnumerable> ListAsync( int? count, int? offset, [EnumeratorCancellation] CancellationToken cancellationToken) { IRedbQueryable query = _redb.Query().OrderByRedb(o => o.Id); if (offset.HasValue) query = query.Skip(offset.Value); if (count.HasValue) query = query.Take(count.Value); var results = await query.ToListAsync().ConfigureAwait(false); foreach (var result in results) yield return result; } public IAsyncEnumerable ListAsync( Func>, TState, IQueryable> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException( "Func cannot be translated to server-side queries. Use _redb.Query() directly."); } public async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken) { // Find non-valid authorizations created before threshold (project IDs only) var candidateIds = await _redb.Query() .Where(a => a.Status != OpenIddictConstants.Statuses.Valid) .WhereRedb(o => o.DateCreate < threshold) .Take(PruneBatchSize) .Select(o => o.Id) .ToListAsync() .ConfigureAwait(false); if (candidateIds.Count == 0) return 0; // Exclude authorizations that still have tokens attached (server-side IDs only). var referencedAuthIds = (await _redb.Query() .WhereIn(t => t.AuthorizationObjectId, candidateIds.ToArray()) .Select(t => t.Props.AuthorizationObjectId) .Distinct() .ToListAsync() .ConfigureAwait(false)).ToHashSet(); var toDelete = candidateIds.Where(id => !referencedAuthIds.Contains(id)).ToList(); if (toDelete.Count == 0) return 0; await SoftDeleteIdsAsync(toDelete).ConfigureAwait(false); // Evict the soft-deleted rows from the per-request cache so a later FindByIdAsync // in the same request goes to the DB (where Query<>() now hides them as soft-deleted) // instead of returning a stale "valid" snapshot from before the prune. foreach (var id in toDelete) _idCache.Remove(id); return toDelete.Count; } public async ValueTask RevokeAsync( string? subject, string? client, string? status, string? type, CancellationToken cancellationToken) { var query = _redb.Query(); if (!string.IsNullOrEmpty(subject) && Guid.TryParse(subject, out var subjectGuid)) query = query.WhereRedb(o => o.ValueGuid == subjectGuid); if (!string.IsNullOrEmpty(client) && long.TryParse(client, out var clientId)) query = query.Where(a => a.ApplicationObjectId == clientId); if (!string.IsNullOrEmpty(status)) query = query.Where(a => a.Status == status); if (!string.IsNullOrEmpty(type)) query = query.Where(a => a.Type == type); var targets = await query.ToListAsync().ConfigureAwait(false); if (targets.Count == 0) return 0; foreach (var target in targets) target.Props.Status = OpenIddictConstants.Statuses.Revoked; await _redb.SaveAsync(targets).ConfigureAwait(false); // Replace cache entries with the just-saved instances so that subsequent // FindByIdAsync in the same request observes Status=revoked. The previous cache // entry came in via CreateAsync and would otherwise serve the pre-revoke snapshot. foreach (var target in targets) _idCache[target.id] = target; return targets.Count; } public async ValueTask RevokeByApplicationIdAsync( string identifier, CancellationToken cancellationToken) { if (!long.TryParse(identifier, out var appId)) return 0; var targets = await _redb.Query() .Where(a => a.ApplicationObjectId == appId) .ToListAsync() .ConfigureAwait(false); if (targets.Count == 0) return 0; foreach (var target in targets) target.Props.Status = OpenIddictConstants.Statuses.Revoked; await _redb.SaveAsync(targets).ConfigureAwait(false); foreach (var target in targets) _idCache[target.id] = target; return targets.Count; } public async ValueTask RevokeBySubjectAsync( string subject, CancellationToken cancellationToken) { if (!Guid.TryParse(subject, out var subjectGuid)) return 0; var targets = await _redb.Query() .WhereRedb(o => o.ValueGuid == subjectGuid) .ToListAsync() .ConfigureAwait(false); if (targets.Count == 0) return 0; foreach (var target in targets) target.Props.Status = OpenIddictConstants.Statuses.Revoked; await _redb.SaveAsync(targets).ConfigureAwait(false); foreach (var target in targets) _idCache[target.id] = target; return targets.Count; } /// /// Identity-wide deletion helper indirection: marks through this store-owned /// so the mark joins the transaction of the caller; the background /// service purges the trash container it finds by polling. /// private Task SoftDeleteIdsAsync(IEnumerable ids) => IdentityDeletionHelper.DeleteAsync(_redb, _backgroundDeletion, ids); public ValueTask SetApplicationIdAsync( RedbObject authorization, string? identifier, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); authorization.Props.ApplicationObjectId = !string.IsNullOrEmpty(identifier) && long.TryParse(identifier, out var appId) ? appId : 0; return default; } public ValueTask SetCreationDateAsync( RedbObject authorization, DateTimeOffset? date, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); if (date.HasValue) authorization.date_create = date.Value; return default; } public ValueTask SetPropertiesAsync( RedbObject authorization, ImmutableDictionary properties, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); if (properties is null || properties.IsEmpty) { authorization.Props.Properties = null; return default; } authorization.Props.Properties = properties.ToDictionary( kvp => kvp.Key, kvp => kvp.Value.GetRawText()); return default; } public ValueTask SetScopesAsync( RedbObject authorization, ImmutableArray scopes, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); authorization.Props.Scopes = scopes.IsDefaultOrEmpty ? null : [.. scopes]; return default; } public ValueTask SetStatusAsync( RedbObject authorization, string? status, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); authorization.Props.Status = status; return default; } public ValueTask SetSubjectAsync( RedbObject authorization, string? subject, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); // Public sub is a GUID — store in value_guid (see RedbTokenStore.SetSubjectAsync). authorization.value_guid = !string.IsNullOrEmpty(subject) && Guid.TryParse(subject, out var g) ? g : null; return default; } public ValueTask SetTypeAsync( RedbObject authorization, string? type, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); authorization.Props.Type = type; return default; } public async ValueTask UpdateAsync( RedbObject authorization, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); // C11: cluster-safe atomic update — see RedbTokenStore.UpdateAsync. await _redb.Context.ExecuteAtomicAsync(async () => { await _redb.LockForUpdateAsync(authorization.id).ConfigureAwait(false); var current = await _redb.LoadAsync(authorization.id).ConfigureAwait(false); if (current is null) throw new OpenIddictExceptions.ConcurrencyException("The authorization was concurrently deleted."); if (current.hash != authorization.hash) throw new OpenIddictExceptions.ConcurrencyException("The authorization was concurrently updated."); await _redb.SaveAsync(authorization).ConfigureAwait(false); }).ConfigureAwait(false); } } Path: redb-identity/src/redb.Identity.Core/Stores/RedbScopeStore.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/Stores/RedbScopeStore.cs ---- using System.Collections.Immutable; using System.Globalization; using System.Runtime.CompilerServices; using System.Text.Json; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Services; using redb.Identity.Core.Models; using redb.Identity.Core.Services; namespace redb.Identity.Core.Stores; /// /// OpenIddict scope store backed by redb PROPS storage. /// Entity type: . /// DisplayName → RedbObject.name. /// internal sealed class RedbScopeStore : IOpenIddictScopeStore> { private readonly IRedbService _redb; private readonly IBackgroundDeletionService? _backgroundDeletion; public RedbScopeStore(IRedbService redb, IBackgroundDeletionService? backgroundDeletion = null) { ArgumentNullException.ThrowIfNull(redb); _redb = redb; _backgroundDeletion = backgroundDeletion; } public async ValueTask CountAsync(CancellationToken cancellationToken) { return await _redb.Query() .CountAsync() .ConfigureAwait(false); } public async ValueTask CountAsync( Func>, IQueryable> query, CancellationToken cancellationToken) { // OpenIddict managers do NOT call this internally — external code only. // Delegate to server-side CountAsync when the projected query is trivial. return await CountAsync(cancellationToken); } public async ValueTask CreateAsync(RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); scope.id = await _redb.SaveAsync(scope).ConfigureAwait(false); } public async ValueTask DeleteAsync(RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); await IdentityDeletionHelper.DeleteAsync(_redb, _backgroundDeletion, scope.id).ConfigureAwait(false); } public async ValueTask?> FindByIdAsync( string identifier, CancellationToken cancellationToken) { if (!long.TryParse(identifier, out var id)) return null; // Use Query<>(): it filters out soft-deleted objects (trash scheme). // LoadAsync<>() loads by primary key and ignores deletion state. var scope = await _redb.Query() .WhereRedb(o => o.Id == id) .FirstOrDefaultAsync() .ConfigureAwait(false); return scope; } public async ValueTask?> FindByNameAsync( string name, CancellationToken cancellationToken) { // V4-UNIQUE: one probe of the unique index ([RedbUnique] ScopeName); an object found // by its key has Props loaded, so no Hydrate. return await _redb.GetByUniqueAsync(p => p.ScopeName, name) .ConfigureAwait(false); } public async IAsyncEnumerable> FindByNamesAsync( ImmutableArray names, [EnumeratorCancellation] CancellationToken cancellationToken) { if (names.IsDefaultOrEmpty) yield break; // V4-UNIQUE: N point probes of the unique index. N is the scopes of one request // (single digits); each probe is the same one-row index hit FindByNameAsync does, // which beats a scheme-wide membership query at this cardinality. foreach (var name in names) { var result = await _redb.GetByUniqueAsync(p => p.ScopeName, name) .ConfigureAwait(false); if (result != null) yield return result; } } public async IAsyncEnumerable> FindByResourceAsync( string resource, [EnumeratorCancellation] CancellationToken cancellationToken) { // Array.Contains — verified working in redb PROPS (see E050_ArrayContains) var results = await _redb.Query() .Where(s => s.Resources != null && s.Resources.Contains(resource)) .ToListAsync() .ConfigureAwait(false); foreach (var result in results) yield return result; } public ValueTask GetAsync( Func>, TState, IQueryable> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException( "Func cannot be translated to server-side queries. Use _redb.Query() directly."); } public ValueTask GetDescriptionAsync( RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); return new(scope.Props.Description); } public ValueTask> GetDescriptionsAsync( RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); var descs = scope.Props.Descriptions; if (descs is null || descs.Count == 0) return new(ImmutableDictionary.Empty); var builder = ImmutableDictionary.CreateBuilder(); foreach (var (key, value) in descs) builder[CultureInfo.GetCultureInfo(key)] = value; return new(builder.ToImmutable()); } public ValueTask GetDisplayNameAsync( RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); return new(scope.name); } public ValueTask> GetDisplayNamesAsync( RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); var names = scope.Props.DisplayNames; if (names is null || names.Count == 0) return new(ImmutableDictionary.Empty); var builder = ImmutableDictionary.CreateBuilder(); foreach (var (key, value) in names) builder[CultureInfo.GetCultureInfo(key)] = value; return new(builder.ToImmutable()); } public ValueTask GetIdAsync( RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); return new(scope.id.ToString()); } public ValueTask GetNameAsync( RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); // Props is the source of truth; value_string covers not-yet-backfilled legacy rows. return new(scope.Props.ScopeName ?? scope.value_string); } public ValueTask> GetPropertiesAsync( RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); var props = scope.Props.Properties; if (props is null || props.Count == 0) return new(ImmutableDictionary.Empty); var builder = ImmutableDictionary.CreateBuilder(); foreach (var (key, value) in props) builder[key] = JsonSerializer.Deserialize(value); return new(builder.ToImmutable()); } public ValueTask> GetResourcesAsync( RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); return new(scope.Props.Resources?.ToImmutableArray() ?? []); } public ValueTask> InstantiateAsync(CancellationToken cancellationToken) { return new(new RedbObject { Props = new ScopeProps() }); } public async IAsyncEnumerable> ListAsync( int? count, int? offset, [EnumeratorCancellation] CancellationToken cancellationToken) { IRedbQueryable query = _redb.Query().OrderByRedb(o => o.Id); if (offset.HasValue) query = query.Skip(offset.Value); if (count.HasValue) query = query.Take(count.Value); var results = await query.ToListAsync().ConfigureAwait(false); foreach (var result in results) yield return result; } public IAsyncEnumerable ListAsync( Func>, TState, IQueryable> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException( "Func cannot be translated to server-side queries. Use _redb.Query() directly."); } public ValueTask SetDescriptionAsync( RedbObject scope, string? description, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); scope.Props.Description = description; return default; } public ValueTask SetDescriptionsAsync( RedbObject scope, ImmutableDictionary descriptions, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); scope.Props.Descriptions = descriptions is null || descriptions.IsEmpty ? null : descriptions.ToDictionary(kvp => kvp.Key.Name, kvp => kvp.Value); return default; } public ValueTask SetDisplayNameAsync( RedbObject scope, string? name, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); scope.name = name; return default; } public ValueTask SetDisplayNamesAsync( RedbObject scope, ImmutableDictionary names, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); scope.Props.DisplayNames = names is null || names.IsEmpty ? null : names.ToDictionary(kvp => kvp.Key.Name, kvp => kvp.Value); return default; } public ValueTask SetNameAsync( RedbObject scope, string? name, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); scope.Props.ScopeName = name; return default; } public ValueTask SetPropertiesAsync( RedbObject scope, ImmutableDictionary properties, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); if (properties is null || properties.IsEmpty) { scope.Props.Properties = null; return default; } scope.Props.Properties = properties.ToDictionary( kvp => kvp.Key, kvp => kvp.Value.GetRawText()); return default; } public ValueTask SetResourcesAsync( RedbObject scope, ImmutableArray resources, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); scope.Props.Resources = resources.IsDefaultOrEmpty ? null : [.. resources]; return default; } public async ValueTask UpdateAsync(RedbObject scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); // C11: cluster-safe atomic update — see RedbTokenStore.UpdateAsync. await _redb.Context.ExecuteAtomicAsync(async () => { await _redb.LockForUpdateAsync(scope.id).ConfigureAwait(false); var current = await _redb.LoadAsync(scope.id).ConfigureAwait(false); if (current is null) throw new OpenIddictExceptions.ConcurrencyException("The scope was concurrently deleted."); if (current.hash != scope.hash) throw new OpenIddictExceptions.ConcurrencyException("The scope was concurrently updated."); await _redb.SaveAsync(scope).ConfigureAwait(false); }).ConfigureAwait(false); } } Path: redb-identity/src/redb.Identity.Core/Stores/RedbTokenStore.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/Stores/RedbTokenStore.cs ---- using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.Json; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Services; using redb.Identity.Core.Models; using redb.Identity.Core.Services; namespace redb.Identity.Core.Stores; /// /// OpenIddict token store backed by redb storage. /// Entity type: . /// Subject (GUID) → RedbObject.value_guid, CreationDate → date_create, /// ExpirationDate → date_complete, RedemptionDate → date_begin. /// internal sealed class RedbTokenStore : IOpenIddictTokenStore> { /// Default batch size for prune / soft-delete operations. private const int PruneBatchSize = 500; private readonly IRedbService _redb; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly ILogger? _logger; // [STORE-DIAG] per-request call counters & cumulative ms (Scoped store). private int _fbidCalls, _fbrefCalls, _fbauthCalls; private long _fbidMs, _fbrefMs, _fbauthMs; // Per-request caches (Scoped store, lifetime = one HTTP request). // OpenIddict calls FindByIdAsync 2× per /connect/token for the same token id; // FindByReferenceIdAsync is hot on refresh_token rotation. // Caches null too — defends against repeated lookups for unknown ids. private readonly Dictionary?> _idCache = new(); private readonly Dictionary?> _refCache = new(StringComparer.Ordinal); public RedbTokenStore( IRedbService redb, IBackgroundDeletionService? backgroundDeletion = null, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(redb); _redb = redb; _backgroundDeletion = backgroundDeletion; _logger = logger; } public async ValueTask CountAsync(CancellationToken cancellationToken) { return await _redb.Query() .CountAsync() .ConfigureAwait(false); } public async ValueTask CountAsync( Func>, IQueryable> query, CancellationToken cancellationToken) { // OpenIddict managers do NOT call this internally — external code only. // Delegate to server-side CountAsync when the projected query is trivial. return await CountAsync(cancellationToken); } public async ValueTask CreateAsync(RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); token.id = await _redb.SaveAsync(token).ConfigureAwait(false); _idCache[token.id] = token; if ((token.Props.ReferenceId ?? token.value_string) is { } refId) _refCache[refId] = token; } public async ValueTask DeleteAsync(RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); await IdentityDeletionHelper.DeleteAsync(_redb, _backgroundDeletion, token.id).ConfigureAwait(false); _idCache.Remove(token.id); if ((token.Props.ReferenceId ?? token.value_string) is { } refId) _refCache.Remove(refId); } public async IAsyncEnumerable> FindAsync( string? subject, string? client, string? status, string? type, [EnumeratorCancellation] CancellationToken cancellationToken) { var query = _redb.Query(); if (!string.IsNullOrEmpty(subject) && Guid.TryParse(subject, out var subjectGuid)) query = query.WhereRedb(o => o.ValueGuid == subjectGuid); if (!string.IsNullOrEmpty(client) && long.TryParse(client, out var clientId)) query = query.WhereRedb(o => o.ValueLong == clientId); if (!string.IsNullOrEmpty(status)) query = query.Where(t => t.Status == status); if (!string.IsNullOrEmpty(type)) query = query.Where(t => t.Type == type); var results = await query.ToListAsync().ConfigureAwait(false); foreach (var result in results) yield return result; } public async IAsyncEnumerable> FindByApplicationIdAsync( string identifier, [EnumeratorCancellation] CancellationToken cancellationToken) { if (!long.TryParse(identifier, out var appId)) yield break; var results = await _redb.Query() .WhereRedb(o => o.ValueLong == appId) .ToListAsync() .ConfigureAwait(false); foreach (var result in results) yield return result; } public async IAsyncEnumerable> FindByAuthorizationIdAsync( string identifier, [EnumeratorCancellation] CancellationToken cancellationToken) { if (!long.TryParse(identifier, out var authId)) yield break; var sw = Stopwatch.GetTimestamp(); var results = await _redb.Query() .Where(t => t.AuthorizationObjectId == authId) .ToListAsync() .ConfigureAwait(false); var ms = (long)Stopwatch.GetElapsedTime(sw).TotalMilliseconds; var n = ++_fbauthCalls; _fbauthMs += ms; _logger?.LogDebug("[STORE-DIAG] Tok.FindByAuthId call#{N} ms={Ms} cum={Cum} count={Count} authId={AuthId}", n, ms, _fbauthMs, results.Count, identifier); foreach (var result in results) yield return result; } public async ValueTask?> FindByIdAsync( string identifier, CancellationToken cancellationToken) { if (!long.TryParse(identifier, out var id)) return null; if (_idCache.TryGetValue(id, out var cached)) { var nh = ++_fbidCalls; _logger?.LogDebug("[STORE-DIAG] Tok.FindById call#{N} HIT cum={Cum} id={Id}", nh, _fbidMs, identifier); return cached; } var sw = Stopwatch.GetTimestamp(); // Use Query<>(): it filters out soft-deleted objects (trash scheme). // LoadAsync<>() loads by primary key and ignores deletion state. var tok = await _redb.Query() .WhereRedb(o => o.Id == id) .FirstOrDefaultAsync() .ConfigureAwait(false); _idCache[id] = tok; if ((tok?.Props.ReferenceId ?? tok?.value_string) is { } refId) _refCache[refId] = tok; var ms = (long)Stopwatch.GetElapsedTime(sw).TotalMilliseconds; var n = ++_fbidCalls; _fbidMs += ms; _logger?.LogDebug("[STORE-DIAG] Tok.FindById call#{N} MISS ms={Ms} cum={Cum} id={Id}", n, ms, _fbidMs, identifier); return tok; } public async ValueTask?> FindByReferenceIdAsync( string identifier, CancellationToken cancellationToken) { if (_refCache.TryGetValue(identifier, out var cached)) { var nh = ++_fbrefCalls; _logger?.LogDebug("[STORE-DIAG] Tok.FindByRef call#{N} HIT cum={Cum}", nh, _fbrefMs); return cached; } var sw = Stopwatch.GetTimestamp(); // V4-UNIQUE: one probe of the unique index instead of a scheme query on value_string. var tok = await _redb.GetByUniqueAsync(p => p.ReferenceId, identifier) .ConfigureAwait(false); _refCache[identifier] = tok; if (tok != null) _idCache[tok.id] = tok; var ms = (long)Stopwatch.GetElapsedTime(sw).TotalMilliseconds; var n = ++_fbrefCalls; _fbrefMs += ms; _logger?.LogDebug("[STORE-DIAG] Tok.FindByRef call#{N} MISS ms={Ms} cum={Cum} hit={Hit}", n, ms, _fbrefMs, tok != null); return tok; } public async IAsyncEnumerable> FindBySubjectAsync( string subject, [EnumeratorCancellation] CancellationToken cancellationToken) { if (!Guid.TryParse(subject, out var subjectGuid)) yield break; var results = await _redb.Query() .WhereRedb(o => o.ValueGuid == subjectGuid) .ToListAsync() .ConfigureAwait(false); foreach (var result in results) yield return result; } public ValueTask GetApplicationIdAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); var appId = token.value_long; return new(appId is not null and not 0 ? appId.Value.ToString() : null); } public ValueTask GetAsync( Func>, TState, IQueryable> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException( "Func cannot be translated to server-side queries. Use _redb.Query() directly."); } public ValueTask GetAuthorizationIdAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); var authId = token.Props.AuthorizationObjectId; return new(authId != 0 ? authId.ToString() : null); } public ValueTask GetCreationDateAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); return new(token.date_create); } public ValueTask GetExpirationDateAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); return new(token.date_complete); } public ValueTask GetIdAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); return new(token.id.ToString()); } public ValueTask GetPayloadAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); return new(token.note); } public ValueTask> GetPropertiesAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); var props = token.Props.Properties; if (props is null || props.Count == 0) return new(ImmutableDictionary.Empty); var builder = ImmutableDictionary.CreateBuilder(); foreach (var (key, value) in props) builder[key] = JsonSerializer.Deserialize(value); return new(builder.ToImmutable()); } public ValueTask GetRedemptionDateAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); return new(token.date_begin); } public ValueTask GetReferenceIdAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); // Props is the source of truth; value_string covers not-yet-backfilled legacy rows. return new(token.Props.ReferenceId ?? token.value_string); } public ValueTask GetStatusAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); return new(token.Props.Status); } public ValueTask GetSubjectAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); return new(token.value_guid?.ToString("D")); } public ValueTask GetTypeAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); return new(token.Props.Type); } public ValueTask> InstantiateAsync(CancellationToken cancellationToken) { return new(new RedbObject { Props = new TokenProps() }); } public async IAsyncEnumerable> ListAsync( int? count, int? offset, [EnumeratorCancellation] CancellationToken cancellationToken) { IRedbQueryable query = _redb.Query().OrderByRedb(o => o.Id); if (offset.HasValue) query = query.Skip(offset.Value); if (count.HasValue) query = query.Take(count.Value); var results = await query.ToListAsync().ConfigureAwait(false); foreach (var result in results) yield return result; } public IAsyncEnumerable ListAsync( Func>, TState, IQueryable> query, TState state, CancellationToken cancellationToken) { throw new NotSupportedException( "Func cannot be translated to server-side queries. Use _redb.Query() directly."); } public async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken) { // Step 1: collect IDs of non-valid tokens older than threshold (projection only, no Props load). // Newest-first ordering so a single PruneAsync call sees freshly-created Revoked/Expired tokens. var nonValidIds = await _redb.Query() .Where(t => t.Status != OpenIddictConstants.Statuses.Valid) .WhereRedb(o => o.DateCreate < threshold) .OrderByDescendingRedb(o => o.DateCreate) .Take(PruneBatchSize) .Select(o => o.Id) .ToListAsync() .ConfigureAwait(false); // Step 2: collect tokens still flagged Valid but older than threshold whose authorization is no longer valid. // Newest-first to ensure recently-orphaned tokens are picked up promptly. var validCandidates = await _redb.Query() .Where(t => t.Status == OpenIddictConstants.Statuses.Valid) .WhereRedb(o => o.DateCreate < threshold) .OrderByDescendingRedb(o => o.DateCreate) .Take(PruneBatchSize) .ToListAsync() .ConfigureAwait(false); var orphanTokenIds = new List(); if (validCandidates.Count > 0) { // Filter zero-AuthId tokens client-side (they reference no auth and shouldn't be pruned here). var authIds = validCandidates .Select(t => t.Props.AuthorizationObjectId) .Where(authId => authId != 0) .Distinct() .ToArray(); // Bulk lookup: which auths are still Valid? Server-side WhereInRedb on _objects.Id + Where on Props. var validAuthIds = (await _redb.Query() .WhereInRedb(o => o.Id, authIds) .Where(a => a.Status == OpenIddictConstants.Statuses.Valid) .Select(o => o.Id) .ToListAsync() .ConfigureAwait(false)).ToHashSet(); foreach (var t in validCandidates) { if (t.Props.AuthorizationObjectId == 0) continue; if (!validAuthIds.Contains(t.Props.AuthorizationObjectId)) orphanTokenIds.Add(t.id); } } var toDelete = nonValidIds.Concat(orphanTokenIds).Distinct().ToList(); if (toDelete.Count == 0) return 0; await SoftDeleteIdsAsync(toDelete).ConfigureAwait(false); // Evict the soft-deleted rows from the per-request caches so a later // FindByIdAsync / FindByReferenceIdAsync in the same request hits the DB — // Query<>() filters out trash so the lookup correctly returns null instead of // serving a stale pre-prune snapshot. We don't know which refIds belong to // which ids without an extra lookup, so clear the ref cache wholesale rather // than load each token; the trade-off is one extra DB roundtrip per ref-id // lookup post-prune, which is a rare path. foreach (var id in toDelete) _idCache.Remove(id); _refCache.Clear(); return toDelete.Count; } public async ValueTask RevokeAsync( string? subject, string? client, string? status, string? type, CancellationToken cancellationToken) { var query = _redb.Query(); if (!string.IsNullOrEmpty(subject) && Guid.TryParse(subject, out var subjectGuid)) query = query.WhereRedb(o => o.ValueGuid == subjectGuid); if (!string.IsNullOrEmpty(client) && long.TryParse(client, out var clientId)) query = query.WhereRedb(o => o.ValueLong == clientId); if (!string.IsNullOrEmpty(status)) query = query.Where(t => t.Status == status); if (!string.IsNullOrEmpty(type)) query = query.Where(t => t.Type == type); var targets = await query.ToListAsync().ConfigureAwait(false); if (targets.Count == 0) return 0; foreach (var target in targets) TokenStatus.Set(target, OpenIddictConstants.Statuses.Revoked); // Single batch save: ChangeTracking writes only the changed Status value and the row's value_bool. await _redb.SaveAsync(targets).ConfigureAwait(false); return targets.Count; } public async ValueTask RevokeByApplicationIdAsync( string identifier, CancellationToken cancellationToken = default) { if (!long.TryParse(identifier, out var appId)) return 0; var targets = await _redb.Query() .WhereRedb(o => o.ValueLong == appId) .ToListAsync() .ConfigureAwait(false); if (targets.Count == 0) return 0; foreach (var target in targets) TokenStatus.Set(target, OpenIddictConstants.Statuses.Revoked); await _redb.SaveAsync(targets).ConfigureAwait(false); RefreshCachesAfterBulkUpdate(targets); return targets.Count; } public async ValueTask RevokeByAuthorizationIdAsync( string identifier, CancellationToken cancellationToken) { if (!long.TryParse(identifier, out var authId)) return 0; var targets = await _redb.Query() .Where(t => t.AuthorizationObjectId == authId) .ToListAsync() .ConfigureAwait(false); if (targets.Count == 0) return 0; foreach (var target in targets) TokenStatus.Set(target, OpenIddictConstants.Statuses.Revoked); await _redb.SaveAsync(targets).ConfigureAwait(false); RefreshCachesAfterBulkUpdate(targets); return targets.Count; } public async ValueTask RevokeBySubjectAsync( string subject, CancellationToken cancellationToken = default) { if (!Guid.TryParse(subject, out var subjectGuid)) return 0; var targets = await _redb.Query() .WhereRedb(o => o.ValueGuid == subjectGuid) .ToListAsync() .ConfigureAwait(false); if (targets.Count == 0) return 0; foreach (var target in targets) TokenStatus.Set(target, OpenIddictConstants.Statuses.Revoked); await _redb.SaveAsync(targets).ConfigureAwait(false); RefreshCachesAfterBulkUpdate(targets); return targets.Count; } /// /// After a bulk mutation that bypassed FindByIdAsync (RevokeBy*, etc.), replace the /// per-request cache entries with the just-saved instances so later FindByIdAsync or /// FindByReferenceIdAsync calls in the same request observe the new state instead of /// returning the pre-mutation snapshot a previous CreateAsync or FindByIdAsync may /// have populated. /// private void RefreshCachesAfterBulkUpdate(IEnumerable> targets) { foreach (var target in targets) { _idCache[target.id] = target; var refId = target.Props.ReferenceId; if (!string.IsNullOrEmpty(refId)) _refCache[refId] = target; } } /// /// Identity-wide deletion helper indirection: marks through this store-owned /// so the mark joins the transaction of the caller; the background /// service purges the trash container it finds by polling. /// private Task SoftDeleteIdsAsync(IEnumerable ids) => IdentityDeletionHelper.DeleteAsync(_redb, _backgroundDeletion, ids); public ValueTask SetApplicationIdAsync( RedbObject token, string? identifier, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); token.value_long = !string.IsNullOrEmpty(identifier) && long.TryParse(identifier, out var appId) ? appId : null; return default; } public ValueTask SetAuthorizationIdAsync( RedbObject token, string? identifier, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); token.Props.AuthorizationObjectId = !string.IsNullOrEmpty(identifier) && long.TryParse(identifier, out var authId) ? authId : 0; return default; } public ValueTask SetCreationDateAsync( RedbObject token, DateTimeOffset? date, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); if (date.HasValue) token.date_create = date.Value; return default; } public ValueTask SetExpirationDateAsync( RedbObject token, DateTimeOffset? date, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); token.date_complete = date; return default; } public ValueTask SetPayloadAsync( RedbObject token, string? payload, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); token.note = payload; return default; } public ValueTask SetPropertiesAsync( RedbObject token, ImmutableDictionary properties, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); if (properties is null || properties.IsEmpty) { token.Props.Properties = null; return default; } token.Props.Properties = properties.ToDictionary( kvp => kvp.Key, kvp => kvp.Value.GetRawText()); return default; } public ValueTask SetRedemptionDateAsync( RedbObject token, DateTimeOffset? date, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); token.date_begin = date; return default; } public ValueTask SetReferenceIdAsync( RedbObject token, string? identifier, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); // V4-UNIQUE: the key lives in Props under [RedbUnique]. Before V4 this method wrote // ONLY the value_string mirror, leaving _values.ReferenceId empty for store-created // tokens; the boot backfill repaired existing rows. token.Props.ReferenceId = identifier; return default; } public ValueTask SetStatusAsync( RedbObject token, string? status, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); TokenStatus.Set(token, status); return default; } public ValueTask SetSubjectAsync( RedbObject token, string? subject, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); // Public sub is a GUID (per IdentityPrincipalBuilder). Store in value_guid so all // subject queries hit a single indexed column. The legacy bigint `key` linkage is // intentionally dropped — it pointed to _users._id, but with multi-instance // identity deployments that linkage is no longer stable across hosts. token.value_guid = !string.IsNullOrEmpty(subject) && Guid.TryParse(subject, out var g) ? g : null; return default; } public ValueTask SetTypeAsync( RedbObject token, string? type, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); token.Props.Type = type; return default; } public async ValueTask UpdateAsync( RedbObject token, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(token); // C11: cluster-safe single-use. Wrap Load+state-check+Save in a transaction with // SELECT ... FOR UPDATE on the token row. Two concurrent redeem attempts serialize // at the DB level; the loser observes that the row has already left the "valid" // state (e.g. Status=redeemed/revoked) and raises ConcurrencyException → OpenIddict // translates to invalid_grant. // // We do NOT rely on a generic hash compare because OpenIddict may invoke // UpdateAsync more than once per request (e.g. metadata touches that don't move // Status), allowing concurrent callers to pass an in-memory hash equality check // even though the row was already redeemed by another request. await _redb.Context.ExecuteAtomicAsync(async () => { await _redb.LockForUpdateAsync(token.id).ConfigureAwait(false); var current = await _redb.LoadAsync(token.id).ConfigureAwait(false); if (current is null) throw new OpenIddictExceptions.ConcurrencyException("The token was concurrently deleted."); // Single-use enforcement: only when the caller is REDEEMING (or REVOKING) a // token. If the row in the DB is no longer Valid, another request already won // the race, raise ConcurrencyException → invalid_grant. For all other status // transitions (Inactive → Valid for device-code verification, metadata-only // updates, Inactive → Inactive bumps, etc.) fall through to the generic // hash-based optimistic concurrency check below. var incomingStatus = token.Props.Status; var dbStatus = current.Props.Status; var consumingValid = string.Equals(incomingStatus, OpenIddictConstants.Statuses.Redeemed, StringComparison.Ordinal) || string.Equals(incomingStatus, OpenIddictConstants.Statuses.Revoked, StringComparison.Ordinal); if (consumingValid && !string.Equals(dbStatus, OpenIddictConstants.Statuses.Valid, StringComparison.Ordinal)) { throw new OpenIddictExceptions.ConcurrencyException( "The token was concurrently updated and is no longer valid."); } // General optimistic concurrency: any other update path still requires that // the in-memory snapshot matches the DB row before persisting. if (current.hash != token.hash) throw new OpenIddictExceptions.ConcurrencyException("The token was concurrently updated."); await _redb.SaveAsync(token).ConfigureAwait(false); }).ConfigureAwait(false); } } Path: redb-identity/src/redb.Identity.Core/Stores/TokenStatus.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/Stores/TokenStatus.cs ---- using OpenIddict.Abstractions; using redb.Core.Models.Entities; using redb.Identity.Core.Models; namespace redb.Identity.Core.Stores; /// /// The one way to set a token's status. Besides it keeps the object row's base /// value_bool in step: only for valid, for every other /// status. The resource side then checks a token by reading that one row (no values). A row written before this /// mirror existed has value_bool NULL and is checked by the full read. /// /// Every write of a token's status goes through in the same save; a test fails when /// Props.Status of a token is assigned anywhere else. /// /// internal static class TokenStatus { internal static void Set(RedbObject token, string? status) { ArgumentNullException.ThrowIfNull(token); token.Props.Status = status; token.value_bool = string.Equals(status, OpenIddictConstants.Statuses.Valid, StringComparison.Ordinal); } } Path: redb-identity/src/redb.Identity.Core/redb.Identity.Core.config.json 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/redb.Identity.Core.config.json ---- { "//": [ "redb.Identity.Core module configuration template (Tsak Layer 4: {Module}.config.json).", "Override any value via the standard Tsak 5-layer pipeline:", " Layer 1 (host appsettings): Tsak:Contexts:default:Identity:*", " Layer 2 (per-context): Tsak:Contexts:{contextName}:Identity:*", " Layer 3 (context.json): same shape as below, merged before this file", " Layer 4 (THIS file): defaults shipped with the .tpkg", " Layer 5 (Override, wins): Tsak:Contexts:{contextName}:Override:Identity:*", "Environment-variable overrides use the standard .NET IConfiguration mapping, e.g.:", " Tsak__Contexts__identity__Override__Identity__AccessTokenLifetime=01:00:00", " Tsak__Contexts__identity__Override__Identity__RateLimit__Enabled=true", "", "SECRETS — there is intentionally NO 'SecretsFilePath' option. Do NOT commit real", "secrets to this file. All secret-bearing fields are designed to be supplied at", "runtime via the Layer-5 Override channel (env-vars, Docker secrets, K8s secrets", "mounted as env, or host appsettings outside source control). The fields that", "qualify as secrets are:", " Identity:RecoveryCodePepper (base64 random)", " Identity:RecoveryCodePreviousPeppers[i] (base64, after a rotation)", " Identity:DynamicRegistrationInitialAccessToken (bearer token)", " Identity:FederationProviders[i]:ClientSecret (per provider)", " Identity:RateLimit:RedisConnectionString (if Redis backend)", " Identity:FederationState:RedisConnectionString (if Redis backend)", " Redb:{instance}:ConnectionString (DB credentials)", "Example env-var (Linux/Docker, double-underscore = section separator):", " Tsak__Contexts__identity__Override__Identity__RecoveryCodePepper=", " Tsak__Contexts__identity__Override__Identity__FederationProviders__0__ClientSecret=", "", "Cryptographic keys (SigningCredentials/EncryptionCredentials) are NOT loaded from", "JSON. Set AllowEphemeralKeys=true for development. For production they are loaded", "from a redb-backed RSA key store (mechanism #2) — see the Identity bootstrap docs.", "", "OBSERVABILITY (F3) — the Identity routes emit OTEL spans + metrics on the security-", "critical hot paths. Names are static (cardinality-safe) and surface in any OTEL or", "Prometheus exporter the host wires up:", " identity.token-request span + counter + latency histogram (token endpoint)", " identity.login span + counter + latency histogram (credential check)", " identity.mfa-verify span + counter + latency histogram (TOTP / OTP verify)", "Plus the per-module health probe registered as 'module:identity' in Tsak's", "/api/health/{startup,live,ready} endpoints (database + signing-key + DP-keyring).", "Enable Tsak's Prometheus scrape endpoint via host appsettings:", " Tsak:Metrics:Prometheus:Enabled=true", " Tsak:Metrics:Prometheus:Path=/metrics" ], "ContextName": "identity.core", "AutoStart": true, "Redb": { "identity-pg": { "Provider": "postgres", "UsePro": true, "ConnectionString": "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true", "EnsureCreated": true } }, "Identity": { // "RedbInstanceName": "identity-pg", "Issuer": "http://127.0.0.1:8080", "AllowEphemeralKeys": true, "AccessTokenLifetime": "01:00:00", "RefreshTokenLifetime": "14.00:00:00", "RefreshTokenReuseLeeway": "00:00:00", "AuthorizationCodeLifetime": "00:05:00", "IdentityTokenLifetime": "00:05:00", "DisableAccessTokenEncryption": false, "TokenThrottleMaxPerPeriod": 10, "TokenThrottlePeriod": "00:00:01", "TokenRetentionDays": 30, "TokenCleanupInterval": "01:00:00", "TokenCleanupBatchSize": 50, "SessionRetentionDays": 14, "SessionCleanupInterval": "01:00:00", "SessionCookieLifetime": "08:00:00", "ManagementScope": "identity:manage", "AccountScope": "identity:account", "EnableDynamicRegistration": false, "DynamicRegistrationAllowedGrantTypes": [ "authorization_code", "refresh_token" ], "DynamicRegistrationAllowedScopes": [ "openid", "profile", "email", "phone", "address", "offline_access", "groups", "roles" ], "DynamicRegistrationInitialAccessToken": null, "EnableDeviceCodeFlow": false, "DeviceCodeLifetime": "00:10:00", "DeviceCodePollingInterval": 5, "EnablePasswordFlow": false, "EnableTokenExchange": false, "TokenExchangeAllowImpersonation": false, "TokenExchangeMaxDelegationDepth": 5, "LoginPath": "/login", "ConsentPath": "/consent", "MfaPath": "/mfa", "MfaRecoveryPath": "/mfa/recovery", "OtpCooldown": "00:01:00", "OtpMaxPerHour": 5, "MfaLockoutClockSkew": "00:00:05", "RecoveryCodePepper": null, "RecoveryCodePreviousPeppers": null, "RecoveryCodePbkdf2Iterations": 600000, "LoginTitle": "Sign In", "LogoUrl": null, "PrimaryColor": "#2563eb", "PrimaryColorHover": "#1d4ed8", "CustomCss": null, "EnableScim": false, "ScimScope": "scim", "EnableFederation": false, "FederationProviders": [ { "//": "Example placeholder — remove or replace with real providers.", "ProviderId": "google", "DisplayName": "Google", "Authority": "https://accounts.google.com", "ClientId": "REPLACE_ME", "ClientSecret": "REPLACE_ME", "Scopes": [ "openid", "profile", "email" ], "AutoProvision": true, "Priority": 100 } ], "ReverseProxies": { "//": [ "Secure-by-default: TrustForwardedFor=false ignores X-Forwarded-For entirely", "and uses the socket IP as the client IP. Enable ONLY when behind a trusted", "proxy whose IPs are listed below — otherwise per-IP rate limits can be spoofed." ], "TrustForwardedFor": false, "KnownProxies": [], "KnownNetworks": [] }, "RateLimit": { "//": "C1: per-IP and per-(IP+username) throttling on /connect/token and /login.", "Enabled": false, "PerIpPerMinute": 30, "PerIpUsernameFailures": 5, "PerIpUsernameWindow": "00:15:00", "DefaultRetryAfterSeconds": 60, "Backend": "memory", "RedisConnectionString": null, "RedisKeyPrefix": "redb:identity:rl:" }, "Validation": { "//": [ "Server-side input-length limits applied by management & registration processors.", "Regex overrides: leave null to use the source-generated defaults shown in comments.", "NOTE: password length/policy lives in 'PasswordPolicy' below — Min/MaxPasswordLength", "here remain only for legacy non-password fields (client_secret length sanity etc.)." ], "MaxIdentifierLength": 128, "MaxDisplayNameLength": 256, "MaxDescriptionLength": 1024, "MinPasswordLength": 8, "MaxPasswordLength": 512, "IdentifierPattern": null, "//IdentifierPatternDefault": "^[a-zA-Z0-9\\-_.]+$", "EmailPattern": null, "//EmailPatternDefault": "^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$", "PhonePattern": null, "//PhonePatternDefault": "^\\+[1-9]\\d{1,14}$" }, "PasswordPolicy": { "//": [ "H10 — server-side password policy applied by:", " • POST /api/v1/identity/users (admin Create)", " • PUT /api/v1/identity/users/{id}/password (admin Change)", " • PUT /me/password (self-service)", " • POST /scim/v2/Users + PATCH (SCIM)", "Defaults are STRICT (NIST SP 800-63B / OWASP ASVS 4.0.3 §2.1).", "Each knob is overridable through the standard 5-layer Tsak pipeline, e.g.:", " Tsak__Contexts__identity__Override__Identity__PasswordPolicy__MinLength=14", "Set HistoryCount=0 to disable history checks entirely.", "Set MaxAge='00:00:00' to disable forced password expiration on login.", "Set BreachCheckEnabled=true ONLY when a checker is registered (e.g. via the", "redb.Identity.PasswordPolicy.Hibp companion package); otherwise the flag is a no-op." ], "MinLength": 12, "MaxLength": 512, "RequireDigit": true, "RequireUppercase": true, "RequireLowercase": true, "RequireSpecial": false, "SpecialChars": "!@#$%^&*()-_=+[]{}|;:,.<>?/`~\"'\\\\", "HistoryCount": 5, "MaxAge": "90.00:00:00", "BreachCheckEnabled": false }, "FederationState": { "//": [ "C6 — hardening of the federation state parameter (encrypted with DataProtection).", "StateMaxAge: TTL for the encrypted blob (HH:mm:ss). Issued-at timestamp is checked against this.", "RequireOneTimeUse: reject replay of the same state blob (jti tracked in the nonce store).", "RequireBrowserBinding: tie the state to a per-flow cookie (set on /challenge, verified on /callback).", "Backend: 'memory' (default; per-process) or 'redis' (cluster-safe; required behind multiple instances).", "RedisConnectionString: optional override; falls back to RateLimit.RedisConnectionString when null." ], "StateMaxAge": "00:05:00", "RequireOneTimeUse": true, "RequireBrowserBinding": false, "BindingCookieName": "redb_fed_b", "Backend": "memory", "RedisConnectionString": null, "RedisKeyPrefix": "redb:identity:fed:nonce:" } } } Path: redb-identity/src/redb.Identity.Core/redb.Identity.Core.csproj 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/redb.Identity.Core.csproj ---- redb.Identity.Core redb.Identity.Core OAuth 2.1 / OpenID Connect engine for redb.Identity — OpenIddict pipeline on redb.Route, redb-backed stores, MFA, WebAuthn, federation, DataProtection and signing keys. Path: redb-identity/src/redb.Identity.Core/sql/audit/mssql_create_table.sql 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/sql/audit/mssql_create_table.sql ---- -- MSSQL DDL for identity audit log table. -- Embedded resource — executed at module startup by -- IdentityAuditLogTableInitListener via redb.Context.ExecuteAsync. -- Idempotent (IF NOT EXISTS / OBJECT_ID checks). IF OBJECT_ID('identity_audit_log', 'U') IS NULL CREATE TABLE identity_audit_log ( id BIGINT IDENTITY(1,1) PRIMARY KEY, event_id UNIQUEIDENTIFIER NOT NULL, event_type NVARCHAR(100) NOT NULL, category NVARCHAR(50), [timestamp] DATETIMEOFFSET NOT NULL DEFAULT SYSDATETIMEOFFSET(), user_id BIGINT, login NVARCHAR(200), client_id NVARCHAR(200), actor_subject NVARCHAR(200), ip_address NVARCHAR(50), user_agent NVARCHAR(500), details NVARCHAR(MAX), CONSTRAINT uq_audit_event_id UNIQUE (event_id) ); -- Reconcile an existing table. -- -- The OBJECT_ID guard above skips the CREATE entirely when the table is already there, so a database -- created before a column existed never gains it — and nothing says so. The audit query selects -- `category` and `login`; without them it fails, the route's DbException handler retries and answers -- "Database temporarily unavailable", and an operator reads a schema gap as a database outage. The index -- statements below fail for the same reason, which is why this block comes first. -- -- Each check is a no-op on a current database. Not covered: a column that exists with the wrong TYPE -- (user_id was VARCHAR before it was BIGINT) — that is a data migration, not idempotent DDL. IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('identity_audit_log') AND name = 'category') ALTER TABLE identity_audit_log ADD category NVARCHAR(50); IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('identity_audit_log') AND name = 'user_id') ALTER TABLE identity_audit_log ADD user_id BIGINT; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('identity_audit_log') AND name = 'login') ALTER TABLE identity_audit_log ADD login NVARCHAR(200); IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('identity_audit_log') AND name = 'client_id') ALTER TABLE identity_audit_log ADD client_id NVARCHAR(200); -- actor_subject: two nodes starting at once may both see it missing; the one that loses the race gets error 2705 -- (column names must be unique), which means it is there now. IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('identity_audit_log') AND name = 'actor_subject') BEGIN BEGIN TRY ALTER TABLE identity_audit_log ADD actor_subject NVARCHAR(200); END TRY BEGIN CATCH IF ERROR_NUMBER() <> 2705 THROW; END CATCH; END; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('identity_audit_log') AND name = 'ip_address') ALTER TABLE identity_audit_log ADD ip_address NVARCHAR(50); IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('identity_audit_log') AND name = 'user_agent') ALTER TABLE identity_audit_log ADD user_agent NVARCHAR(500); IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('identity_audit_log') AND name = 'details') ALTER TABLE identity_audit_log ADD details NVARCHAR(MAX); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'ix_audit_timestamp') CREATE INDEX ix_audit_timestamp ON identity_audit_log([timestamp]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'ix_audit_event_type') CREATE INDEX ix_audit_event_type ON identity_audit_log(event_type); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'ix_audit_category') CREATE INDEX ix_audit_category ON identity_audit_log(category); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'ix_audit_user_id') CREATE INDEX ix_audit_user_id ON identity_audit_log(user_id); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'ix_audit_login') CREATE INDEX ix_audit_login ON identity_audit_log(login); Path: redb-identity/src/redb.Identity.Core/sql/audit/pg_create_table.sql 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/sql/audit/pg_create_table.sql ---- -- PostgreSQL DDL for identity audit log table. -- Embedded resource — executed at module startup by -- IdentityAuditLogTableInitListener via redb.Context.ExecuteAsync. -- Idempotent (IF NOT EXISTS) so re-running on an existing database is safe. CREATE TABLE IF NOT EXISTS identity_audit_log ( id BIGSERIAL PRIMARY KEY, event_id UUID NOT NULL, event_type VARCHAR(100) NOT NULL, category VARCHAR(50), "timestamp" TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- BIGINT (not VARCHAR) — every event we emit carries an internal -- redb _users.id, which is bigint. Smaller fixed-width index, direct -- integer compare, no text collation overhead. Emitters that hand us -- non-numeric identifiers (e.g. pre-link federated provider subjects) -- log a warning and land user_id = NULL — they still get filed under -- login + details. user_id BIGINT, login VARCHAR(200), client_id VARCHAR(200), actor_subject VARCHAR(200), ip_address VARCHAR(50), user_agent VARCHAR(500), -- Stored as text (not jsonb) so the dialect-agnostic parameter binding -- in IRedbContext.ExecuteAsync — string-typed positional args — round-trips -- without a per-driver cast. Querying by individual keys was never the use -- case here (operators slice by event_type / user_id / login / timestamp). -- Operators wanting jsonb queries can ALTER the column locally; the audit -- query path doesn't read this column for filtering. details TEXT, CONSTRAINT uq_audit_event_id UNIQUE (event_id) ); -- Reconcile an existing table. -- -- CREATE TABLE IF NOT EXISTS above is a no-op when the table is already there, which means a database -- created before a column existed never gains it — and nothing says so. The audit query selects `category` -- and `login`, so on such a database it fails with `column "category" does not exist`, the route's -- DbException handler retries three times and answers "Database temporarily unavailable", and an operator -- reads that as a database outage instead of a schema gap. The two CREATE INDEX statements below fail for -- the same reason, which is why this block has to come first. -- -- ADD COLUMN IF NOT EXISTS is a no-op on a current database, so this costs a fresh install nothing. -- Not covered here: a column that exists with the wrong TYPE (user_id was VARCHAR before it was BIGINT). -- Widening a populated column is a data migration, not an idempotent DDL step, and is left to the operator. ALTER TABLE identity_audit_log ADD COLUMN IF NOT EXISTS category VARCHAR(50); ALTER TABLE identity_audit_log ADD COLUMN IF NOT EXISTS user_id BIGINT; ALTER TABLE identity_audit_log ADD COLUMN IF NOT EXISTS login VARCHAR(200); ALTER TABLE identity_audit_log ADD COLUMN IF NOT EXISTS client_id VARCHAR(200); ALTER TABLE identity_audit_log ADD COLUMN IF NOT EXISTS actor_subject VARCHAR(200); ALTER TABLE identity_audit_log ADD COLUMN IF NOT EXISTS ip_address VARCHAR(50); ALTER TABLE identity_audit_log ADD COLUMN IF NOT EXISTS user_agent VARCHAR(500); ALTER TABLE identity_audit_log ADD COLUMN IF NOT EXISTS details TEXT; -- Reconcile column TYPES that drifted. -- -- Two columns changed type after the first release, and ADD COLUMN above cannot fix a column that is -- already there. Both conversions are guarded on the current type, so they run at most once and cost a -- current database nothing. -- -- details: jsonb -> text. The dialect-agnostic parameter binding in IRedbContext.ExecuteAsync passes -- strings; against a jsonb column Postgres refuses with "column is of type jsonb but expression is of -- type text" and every audit write fails silently into the sink's error log. -- -- user_id: varchar -> bigint. Converted only when every existing value is numeric; otherwise the table -- is left alone and a notice is raised, because turning unparseable identifiers into NULL behind the -- operator's back is a data loss they did not agree to. DO $$ BEGIN IF (SELECT data_type FROM information_schema.columns WHERE table_name = 'identity_audit_log' AND column_name = 'details') = 'jsonb' THEN ALTER TABLE identity_audit_log ALTER COLUMN details TYPE TEXT USING details::text; RAISE NOTICE 'identity_audit_log.details converted from jsonb to text'; END IF; IF (SELECT data_type FROM information_schema.columns WHERE table_name = 'identity_audit_log' AND column_name = 'user_id') = 'character varying' THEN IF EXISTS (SELECT 1 FROM identity_audit_log WHERE user_id IS NOT NULL AND user_id !~ '^[0-9]+$') THEN RAISE NOTICE 'identity_audit_log.user_id left as varchar: it holds non-numeric values. ' 'Migrate them by hand — converting would silently null them out.'; ELSE ALTER TABLE identity_audit_log ALTER COLUMN user_id TYPE BIGINT USING NULLIF(user_id, '')::bigint; RAISE NOTICE 'identity_audit_log.user_id converted from varchar to bigint'; END IF; END IF; END $$; CREATE INDEX IF NOT EXISTS ix_audit_timestamp ON identity_audit_log("timestamp"); CREATE INDEX IF NOT EXISTS ix_audit_event_type ON identity_audit_log(event_type); CREATE INDEX IF NOT EXISTS ix_audit_category ON identity_audit_log(category); CREATE INDEX IF NOT EXISTS ix_audit_user_id ON identity_audit_log(user_id); CREATE INDEX IF NOT EXISTS ix_audit_login ON identity_audit_log(login); Path: redb-identity/src/redb.Identity.Core/sql/audit/sqlite_create_table.sql 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/sql/audit/sqlite_create_table.sql ---- -- SQLite DDL for identity audit log table. -- Embedded resource — executed at module startup by -- IdentityAuditLogTableInitListener via redb.Context.ExecuteAsync. -- Idempotent (CREATE ... IF NOT EXISTS). -- -- SQLite notes: -- * INTEGER PRIMARY KEY = rowid alias, behaves like BIGSERIAL on autoincrement. -- * No native UUID / JSONB types — GUIDs and details are stored as TEXT (RFC 4122 -- strings, plain JSON) and decoded by the app layer. -- * timestamp is REAL: the redb SQLite provider encodes every DateTimeOffset -- parameter as a Julian day number (UTC) and decodes REAL columns back to -- DateTimeOffset — the same convention as the _date_* base columns. A TEXT column -- here would receive that number as text, and the query layer would then fail to -- parse it (timestamps read back as 0001-01-01, date filters compare text to a -- number). DEFAULT mirrors the encoding for rows inserted outside redb. -- * No NVARCHAR — SQLite columns are typeless (NUMERIC affinity by default, -- TEXT for our string-heavy schema). We still spell out a width so dialect -- parity is obvious to a human reader; SQLite ignores it but PostgreSQL / -- MSSQL share the same source. -- * UNIQUE / index DDL syntax is straightforward and idempotent. CREATE TABLE IF NOT EXISTS identity_audit_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, event_id TEXT NOT NULL, event_type TEXT NOT NULL, category TEXT, timestamp REAL NOT NULL DEFAULT (julianday('now')), user_id INTEGER, login TEXT, client_id TEXT, actor_subject TEXT, ip_address TEXT, user_agent TEXT, details TEXT, CONSTRAINT uq_audit_event_id UNIQUE (event_id) ); -- Reconciling an existing table: NOT possible here, and deliberately not faked. -- -- The Postgres and MSSQL scripts add missing columns idempotently, because a database created before a -- column existed never gains it from CREATE TABLE IF NOT EXISTS — the audit query then fails on -- `category` / `login` and the operator sees "Database temporarily unavailable", which points at the -- wrong thing. SQLite has no conditional DDL: `ALTER TABLE ... ADD COLUMN` cannot be guarded by -- IF NOT EXISTS, and re-running it on a current database is an error rather than a no-op. -- -- So an existing SQLite file predating these columns must be migrated by hand: -- -- ALTER TABLE identity_audit_log ADD COLUMN category TEXT; -- ALTER TABLE identity_audit_log ADD COLUMN login TEXT; -- -- Check first with `PRAGMA table_info(identity_audit_log);`. Fresh files are unaffected: the CREATE above -- already carries every column. CREATE INDEX IF NOT EXISTS ix_audit_timestamp ON identity_audit_log(timestamp); CREATE INDEX IF NOT EXISTS ix_audit_event_type ON identity_audit_log(event_type); CREATE INDEX IF NOT EXISTS ix_audit_category ON identity_audit_log(category); CREATE INDEX IF NOT EXISTS ix_audit_user_id ON identity_audit_log(user_id); CREATE INDEX IF NOT EXISTS ix_audit_login ON identity_audit_log(login); Path: redb-identity/src/redb.Identity.Core/sql/events/mssql.sql 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/sql/events/mssql.sql ---- -- SQL Server statements of IdentityEventStore. Sections start with "-- @name "; the store reads -- them by key. Positional parameters @p0... Every time comparison and every stored time uses the -- database clock (SYSUTCDATETIME()), never the clock of the node. -- @name create_outbox IF OBJECT_ID(N'dbo.identity_delivery_outbox', N'U') IS NULL BEGIN CREATE TABLE dbo.identity_delivery_outbox ( id BIGINT IDENTITY(1,1) PRIMARY KEY, delivery_id UNIQUEIDENTIFIER NOT NULL, event_id UNIQUEIDENTIFIER NOT NULL, kind NVARCHAR(20) NOT NULL, destination NVARCHAR(200) NOT NULL, event_type NVARCHAR(100) NOT NULL, payload NVARCHAR(MAX) NOT NULL, status NVARCHAR(20) NOT NULL CONSTRAINT df_outbox_status DEFAULT N'pending', attempts INT NOT NULL CONSTRAINT df_outbox_attempts DEFAULT 0, next_attempt_at DATETIME2 NOT NULL CONSTRAINT df_outbox_next DEFAULT SYSUTCDATETIME(), lease_until DATETIME2 NULL, leased_by NVARCHAR(200) NULL, last_error NVARCHAR(1000) NULL, created_at DATETIME2 NOT NULL CONSTRAINT df_outbox_created DEFAULT SYSUTCDATETIME(), finished_at DATETIME2 NULL, CONSTRAINT uq_outbox_delivery_id UNIQUE (delivery_id) ); CREATE INDEX ix_outbox_due ON dbo.identity_delivery_outbox (status, next_attempt_at); CREATE INDEX ix_outbox_destination ON dbo.identity_delivery_outbox (kind, destination, status); CREATE INDEX ix_outbox_created ON dbo.identity_delivery_outbox (created_at); END; -- @name insert_audit INSERT INTO identity_audit_log (event_id, event_type, category, [timestamp], user_id, login, client_id, ip_address, user_agent, details, actor_subject) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10); -- @name insert_outbox INSERT INTO dbo.identity_delivery_outbox (delivery_id, event_id, kind, destination, event_type, payload) VALUES (@p0, @p1, @p2, @p3, @p4, @p5); -- @name due SELECT TOP (@p0) id, delivery_id, kind, destination, event_type, payload, attempts FROM dbo.identity_delivery_outbox WHERE status = N'pending' AND next_attempt_at <= SYSUTCDATETIME() AND (lease_until IS NULL OR lease_until < SYSUTCDATETIME()) ORDER BY next_attempt_at, id; -- @name claim UPDATE dbo.identity_delivery_outbox SET lease_until = DATEADD(second, @p1, SYSUTCDATETIME()), leased_by = @p2 WHERE id = @p0 AND status = N'pending' AND next_attempt_at <= SYSUTCDATETIME() AND (lease_until IS NULL OR lease_until < SYSUTCDATETIME()) AND attempts = @p3; -- @name delivered UPDATE dbo.identity_delivery_outbox SET status = N'delivered', attempts = attempts + 1, finished_at = SYSUTCDATETIME(), lease_until = NULL, leased_by = NULL, last_error = NULL WHERE id = @p0 AND leased_by = @p1; -- @name retry UPDATE dbo.identity_delivery_outbox SET attempts = attempts + 1, next_attempt_at = DATEADD(millisecond, @p2, SYSUTCDATETIME()), last_error = @p3, lease_until = NULL, leased_by = NULL WHERE id = @p0 AND leased_by = @p1; -- @name failed UPDATE dbo.identity_delivery_outbox SET status = N'failed', attempts = attempts + 1, finished_at = SYSUTCDATETIME(), last_error = @p2, lease_until = NULL, leased_by = NULL WHERE id = @p0 AND leased_by = @p1; -- @name cancelled UPDATE dbo.identity_delivery_outbox SET status = N'cancelled', finished_at = SYSUTCDATETIME(), last_error = @p2, lease_until = NULL, leased_by = NULL WHERE id = @p0 AND leased_by = @p1; -- @name cleanup -- One batch of finished rows past their retention: delivered after @p0 seconds, failed and cancelled after @p1. -- A pending row is never touched. DELETE TOP (@p2) FROM dbo.identity_delivery_outbox WHERE (status = N'delivered' AND finished_at < DATEADD(second, -@p0, SYSUTCDATETIME())) OR (status IN (N'failed', N'cancelled') AND finished_at < DATEADD(second, -@p1, SYSUTCDATETIME())); -- @name stats SELECT COUNT_BIG(*) AS pending, CAST(COALESCE(DATEDIFF_BIG(millisecond, MIN(created_at), SYSUTCDATETIME()), 0) AS float) / 1000.0 AS oldest_seconds FROM dbo.identity_delivery_outbox WHERE status = N'pending'; -- @name list -- Filters are '' for "any". SELECT id, delivery_id, event_id, kind, destination, event_type, status, attempts, last_error, CONVERT(nvarchar(30), created_at, 127) + N'Z' AS created_at, CONVERT(nvarchar(30), next_attempt_at, 127) + N'Z' AS next_attempt_at, CONVERT(nvarchar(30), finished_at, 127) + N'Z' AS finished_at FROM dbo.identity_delivery_outbox WHERE (@p0 = N'' OR status = @p0) AND (@p1 = N'' OR kind = @p1) AND (@p2 = N'' OR destination = @p2) ORDER BY id DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY; -- @name redeliver -- A failed or cancelled row becomes due again, as a new run of attempts; any other row is left as it is. UPDATE dbo.identity_delivery_outbox SET status = N'pending', attempts = 0, next_attempt_at = SYSUTCDATETIME(), lease_until = NULL, leased_by = NULL, last_error = NULL, finished_at = NULL WHERE id = @p0 AND status IN (N'failed', N'cancelled'); -- @name status_of SELECT status FROM dbo.identity_delivery_outbox WHERE id = @p0; Path: redb-identity/src/redb.Identity.Core/sql/events/pg.sql 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/sql/events/pg.sql ---- -- PostgreSQL statements of IdentityEventStore. Sections start with "-- @name "; the store reads -- them by key. Positional parameters @p0.. (rewritten to $1.. by the redb connection). Every time -- comparison and every stored time uses the database clock (now()), never the clock of the node. -- @name create_outbox CREATE TABLE IF NOT EXISTS identity_delivery_outbox ( id BIGSERIAL PRIMARY KEY, delivery_id UUID NOT NULL, event_id UUID NOT NULL, kind VARCHAR(20) NOT NULL, destination VARCHAR(200) NOT NULL, event_type VARCHAR(100) NOT NULL, payload TEXT NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(), lease_until TIMESTAMPTZ NULL, leased_by VARCHAR(200) NULL, last_error VARCHAR(1000) NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), finished_at TIMESTAMPTZ NULL, CONSTRAINT uq_outbox_delivery_id UNIQUE (delivery_id) ); CREATE INDEX IF NOT EXISTS ix_outbox_due ON identity_delivery_outbox (status, next_attempt_at); CREATE INDEX IF NOT EXISTS ix_outbox_destination ON identity_delivery_outbox (kind, destination, status); CREATE INDEX IF NOT EXISTS ix_outbox_created ON identity_delivery_outbox (created_at); -- @name insert_audit INSERT INTO identity_audit_log (event_id, event_type, category, "timestamp", user_id, login, client_id, ip_address, user_agent, details, actor_subject) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10); -- @name insert_outbox INSERT INTO identity_delivery_outbox (delivery_id, event_id, kind, destination, event_type, payload) VALUES (@p0, @p1, @p2, @p3, @p4, @p5); -- @name due SELECT id, delivery_id, kind, destination, event_type, payload, attempts FROM identity_delivery_outbox WHERE status = 'pending' AND next_attempt_at <= now() AND (lease_until IS NULL OR lease_until < now()) ORDER BY next_attempt_at, id LIMIT @p0; -- @name claim UPDATE identity_delivery_outbox SET lease_until = now() + make_interval(secs => @p1), leased_by = @p2 WHERE id = @p0 AND status = 'pending' AND next_attempt_at <= now() AND (lease_until IS NULL OR lease_until < now()) AND attempts = @p3; -- @name delivered UPDATE identity_delivery_outbox SET status = 'delivered', attempts = attempts + 1, finished_at = now(), lease_until = NULL, leased_by = NULL, last_error = NULL WHERE id = @p0 AND leased_by = @p1; -- @name retry UPDATE identity_delivery_outbox SET attempts = attempts + 1, next_attempt_at = now() + make_interval(secs => @p2 / 1000.0), last_error = @p3, lease_until = NULL, leased_by = NULL WHERE id = @p0 AND leased_by = @p1; -- @name failed UPDATE identity_delivery_outbox SET status = 'failed', attempts = attempts + 1, finished_at = now(), last_error = @p2, lease_until = NULL, leased_by = NULL WHERE id = @p0 AND leased_by = @p1; -- @name cancelled UPDATE identity_delivery_outbox SET status = 'cancelled', finished_at = now(), last_error = @p2, lease_until = NULL, leased_by = NULL WHERE id = @p0 AND leased_by = @p1; -- @name cleanup -- One batch of finished rows past their retention: delivered after @p0 seconds, failed and cancelled after @p1. -- A pending row is never touched. DELETE FROM identity_delivery_outbox WHERE id IN ( SELECT id FROM identity_delivery_outbox WHERE (status = 'delivered' AND finished_at < now() - make_interval(secs => @p0)) OR (status IN ('failed', 'cancelled') AND finished_at < now() - make_interval(secs => @p1)) LIMIT @p2); -- @name stats SELECT COUNT(*) AS pending, COALESCE(EXTRACT(EPOCH FROM (now() - MIN(created_at)))::float8, 0) AS oldest_seconds FROM identity_delivery_outbox WHERE status = 'pending'; -- @name list -- Filters are '' for "any". SELECT id, delivery_id, event_id, kind, destination, event_type, status, attempts, last_error, to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS created_at, to_char(next_attempt_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS next_attempt_at, to_char(finished_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS finished_at FROM identity_delivery_outbox WHERE (@p0 = '' OR status = @p0) AND (@p1 = '' OR kind = @p1) AND (@p2 = '' OR destination = @p2) ORDER BY id DESC LIMIT @p3 OFFSET @p4; -- @name redeliver -- A failed or cancelled row becomes due again, as a new run of attempts; any other row is left as it is. UPDATE identity_delivery_outbox SET status = 'pending', attempts = 0, next_attempt_at = now(), lease_until = NULL, leased_by = NULL, last_error = NULL, finished_at = NULL WHERE id = @p0 AND status IN ('failed', 'cancelled'); -- @name status_of SELECT status FROM identity_delivery_outbox WHERE id = @p0; Path: redb-identity/src/redb.Identity.Core/sql/events/sqlite.sql 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/sql/events/sqlite.sql ---- -- SQLite statements of IdentityEventStore. Sections start with "-- @name "; the store reads -- them by key. Times are julianday REAL values, as in identity_audit_log; every time comparison and -- every stored time uses the database clock (julianday('now')), never the clock of the node. -- @name create_outbox CREATE TABLE IF NOT EXISTS identity_delivery_outbox ( id INTEGER PRIMARY KEY AUTOINCREMENT, delivery_id TEXT NOT NULL, event_id TEXT NOT NULL, kind TEXT NOT NULL, destination TEXT NOT NULL, event_type TEXT NOT NULL, payload TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at REAL NOT NULL DEFAULT (julianday('now')), lease_until REAL NULL, leased_by TEXT NULL, last_error TEXT NULL, created_at REAL NOT NULL DEFAULT (julianday('now')), finished_at REAL NULL, CONSTRAINT uq_outbox_delivery_id UNIQUE (delivery_id) ); CREATE INDEX IF NOT EXISTS ix_outbox_due ON identity_delivery_outbox (status, next_attempt_at); CREATE INDEX IF NOT EXISTS ix_outbox_destination ON identity_delivery_outbox (kind, destination, status); CREATE INDEX IF NOT EXISTS ix_outbox_created ON identity_delivery_outbox (created_at); -- @name insert_audit INSERT INTO identity_audit_log (event_id, event_type, category, "timestamp", user_id, login, client_id, ip_address, user_agent, details, actor_subject) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10); -- @name insert_outbox INSERT INTO identity_delivery_outbox (delivery_id, event_id, kind, destination, event_type, payload) VALUES (@p0, @p1, @p2, @p3, @p4, @p5); -- @name due SELECT id, delivery_id, kind, destination, event_type, payload, attempts FROM identity_delivery_outbox WHERE status = 'pending' AND next_attempt_at <= julianday('now') AND (lease_until IS NULL OR lease_until < julianday('now')) ORDER BY next_attempt_at, id LIMIT @p0; -- @name claim UPDATE identity_delivery_outbox SET lease_until = julianday('now') + (@p1 / 86400.0), leased_by = @p2 WHERE id = @p0 AND status = 'pending' AND next_attempt_at <= julianday('now') AND (lease_until IS NULL OR lease_until < julianday('now')) AND attempts = @p3; -- @name delivered UPDATE identity_delivery_outbox SET status = 'delivered', attempts = attempts + 1, finished_at = julianday('now'), lease_until = NULL, leased_by = NULL, last_error = NULL WHERE id = @p0 AND leased_by = @p1; -- @name retry UPDATE identity_delivery_outbox SET attempts = attempts + 1, next_attempt_at = julianday('now') + (@p2 / 86400000.0), last_error = @p3, lease_until = NULL, leased_by = NULL WHERE id = @p0 AND leased_by = @p1; -- @name failed UPDATE identity_delivery_outbox SET status = 'failed', attempts = attempts + 1, finished_at = julianday('now'), last_error = @p2, lease_until = NULL, leased_by = NULL WHERE id = @p0 AND leased_by = @p1; -- @name cancelled UPDATE identity_delivery_outbox SET status = 'cancelled', finished_at = julianday('now'), last_error = @p2, lease_until = NULL, leased_by = NULL WHERE id = @p0 AND leased_by = @p1; -- @name cleanup -- One batch of finished rows past their retention: delivered after @p0 seconds, failed and cancelled after @p1. -- A pending row is never touched. DELETE FROM identity_delivery_outbox WHERE id IN ( SELECT id FROM identity_delivery_outbox WHERE (status = 'delivered' AND finished_at < julianday('now') - (@p0 / 86400.0)) OR (status IN ('failed', 'cancelled') AND finished_at < julianday('now') - (@p1 / 86400.0)) LIMIT @p2); -- @name stats SELECT COUNT(*) AS pending, COALESCE((julianday('now') - MIN(created_at)) * 86400.0, 0) AS oldest_seconds FROM identity_delivery_outbox WHERE status = 'pending'; -- @name list -- Filters are '' for "any". SELECT id, delivery_id, event_id, kind, destination, event_type, status, attempts, last_error, strftime('%Y-%m-%dT%H:%M:%fZ', created_at) AS created_at, strftime('%Y-%m-%dT%H:%M:%fZ', next_attempt_at) AS next_attempt_at, strftime('%Y-%m-%dT%H:%M:%fZ', finished_at) AS finished_at FROM identity_delivery_outbox WHERE (@p0 = '' OR status = @p0) AND (@p1 = '' OR kind = @p1) AND (@p2 = '' OR destination = @p2) ORDER BY id DESC LIMIT @p3 OFFSET @p4; -- @name redeliver -- A failed or cancelled row becomes due again, as a new run of attempts; any other row is left as it is. UPDATE identity_delivery_outbox SET status = 'pending', attempts = 0, next_attempt_at = julianday('now'), lease_until = NULL, leased_by = NULL, last_error = NULL, finished_at = NULL WHERE id = @p0 AND status IN ('failed', 'cancelled'); -- @name status_of SELECT status FROM identity_delivery_outbox WHERE id = @p0;