Bundle: redb-identity / src/redb.Identity.Core (src.redb.Identity.Core.txt), 283 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/ChangeEmail/IChangeEmailTokenStore.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/ChangeEmail/IChangeEmailTokenStore.cs
----
using System;
using System.Threading;
using System.Threading.Tasks;
namespace redb.Identity.Core.ChangeEmail;
///
/// N-4 (Session E, sub-step N4-7): server-side store for single-use
/// change-of-e-mail tokens. Direct mirror of
/// with two extra bindings —
/// the address the user wants to switch to (newEmail) and a snapshot of
/// the address at issue time (currentEmail) so the confirm step can detect a
/// race where the e-mail was modified through another path between request and confirm.
///
public interface IChangeEmailTokenStore
{
///
/// Issues a new change-of-e-mail token. Generates a 32-byte CSPRNG secret
/// (base64url-encoded), persists its peppered SHA-256 hash + the bound
/// and snapshots, and
/// returns the jti + plaintext token so the caller can embed both into the
/// confirm URL.
///
/// User the change is bound to.
/// Lower-cased target address (committed on confirm).
/// Lower-cased snapshot of the user's e-mail at issue time.
/// Caller-supplied landing URL captured at issue time.
/// Time-to-live for this token. Typically 1 hour.
/// When true, mark all prior unconsumed tokens
/// for this user as Consumed so a stolen earlier link cannot race the new one.
Task IssueAsync(
long userId,
string newEmail,
string currentEmail,
string callerConfirmUrl,
TimeSpan ttl,
bool invalidatePrevious,
CancellationToken ct = default);
///
/// Verifies and atomically consumes a change-of-e-mail token keyed by .
/// On success the row is marked Consumed and the bound user id + new/current
/// snapshots are returned so the caller can apply the race-guard and atomic swap.
///
Task VerifyAndConsumeAsync(
Guid jti,
string token,
CancellationToken ct = default);
}
/// Result of .
public readonly record struct ChangeEmailIssueResult(
Guid Jti,
string PlaintextToken,
DateTimeOffset ExpiresAt);
/// Result of .
/// Whether the token verified AND the row was successfully consumed.
/// Owner user id when is true; otherwise 0.
/// Lower-cased target address bound at issue time; empty when is false.
/// Lower-cased snapshot of the e-mail at issue time; empty when is false.
/// Diagnostic reason; values: ok, not_found, expired, already_consumed, bad_token.
public readonly record struct ChangeEmailVerifyResult(
bool Success,
long UserId,
string NewEmail,
string CurrentEmail,
string Reason);
Path: redb-identity/src/redb.Identity.Core/ChangeEmail/RedbChangeEmailTokenStore.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/ChangeEmail/RedbChangeEmailTokenStore.cs
----
using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
namespace redb.Identity.Core.ChangeEmail;
///
/// N-4 (Session E, sub-step N4-7): redb-backed
/// . Direct mirror of
/// RedbEmailVerificationTokenStore with two extra fields on the persisted props
/// ( +
/// ) and the
/// invalidatePrevious housekeeping pass at issue time.
///
public sealed class RedbChangeEmailTokenStore : IChangeEmailTokenStore
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly RecoveryCodePepperProvider _pepperProvider;
private readonly ILogger _logger;
private readonly TimeProvider _timeProvider;
public RedbChangeEmailTokenStore(
IServiceScopeFactory scopeFactory,
RecoveryCodePepperProvider pepperProvider,
ILogger logger,
TimeProvider? timeProvider = null)
{
_scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
_pepperProvider = pepperProvider ?? throw new ArgumentNullException(nameof(pepperProvider));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_timeProvider = timeProvider ?? TimeProvider.System;
}
///
public async Task IssueAsync(
long userId,
string newEmail,
string currentEmail,
string callerConfirmUrl,
TimeSpan ttl,
bool invalidatePrevious,
CancellationToken ct = default)
{
if (userId <= 0) throw new ArgumentOutOfRangeException(nameof(userId));
if (string.IsNullOrWhiteSpace(newEmail)) throw new ArgumentException("newEmail is required", nameof(newEmail));
if (string.IsNullOrWhiteSpace(currentEmail)) throw new ArgumentException("currentEmail is required", nameof(currentEmail));
if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl));
var jti = Guid.NewGuid();
var token = GenerateToken();
var now = _timeProvider.GetUtcNow();
var expires = now + ttl;
var hash = RecoveryCodePepperProvider.PepperedSha256Hex(_pepperProvider.Pepper, token);
await using var scope = _scopeFactory.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
// Housekeeping: invalidate any prior unconsumed tokens for this user so a
// previously-issued link cannot race the new one.
if (invalidatePrevious)
{
var prior = await redb.Query()
.Where(o => o.UserId == userId && !o.Consumed)
.ToListAsync()
.ConfigureAwait(false);
if (prior.Count > 0)
{
foreach (var p in prior)
p.Props.Consumed = true;
await redb.SaveAsync(prior).ConfigureAwait(false);
}
}
var obj = new RedbObject(new ChangeEmailTokenProps
{
Jti = jti.ToString("N"),
UserId = userId,
NewEmail = newEmail.Trim().ToLowerInvariant(),
CurrentEmail = currentEmail.Trim().ToLowerInvariant(),
TokenHash = hash,
PepperId = _pepperProvider.PepperId,
IssuedAt = now,
ExpiresAt = expires,
Consumed = false,
Attempts = 0,
CallerConfirmUrl = callerConfirmUrl ?? string.Empty,
});
obj.name = jti.ToString("N");
await redb.SaveAsync(obj).ConfigureAwait(false);
return new ChangeEmailIssueResult(jti, token, expires);
}
///
public async Task VerifyAndConsumeAsync(
Guid jti,
string token,
CancellationToken ct = default)
{
if (jti == Guid.Empty) return new ChangeEmailVerifyResult(false, 0, "", "", "not_found");
if (string.IsNullOrEmpty(token)) return new ChangeEmailVerifyResult(false, 0, "", "", "bad_token");
await using var scope = _scopeFactory.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
var key = jti.ToString("N");
await using var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false);
var row = await redb.Query()
.Where(o => o.Jti == key)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (row is null)
{
await tx.RollbackAsync().ConfigureAwait(false);
return new ChangeEmailVerifyResult(false, 0, "", "", "not_found");
}
if (row.key.HasValue)
await redb.LockForUpdateAsync(row.key.Value).ConfigureAwait(false);
var p = row.Props;
var now = _timeProvider.GetUtcNow();
if (p.Consumed)
{
await tx.CommitAsync().ConfigureAwait(false);
return new ChangeEmailVerifyResult(false, 0, "", "", "already_consumed");
}
if (p.ExpiresAt < now)
{
await tx.CommitAsync().ConfigureAwait(false);
return new ChangeEmailVerifyResult(false, 0, "", "", "expired");
}
if (_pepperProvider.PeppersFor(p.PepperId).Count == 0)
_logger.LogWarning("The token was hashed with pepper {PepperId}, which is no longer configured.", p.PepperId);
var ok = _pepperProvider.MatchesTokenHash(token.Trim(), p.TokenHash, p.PepperId);
p.Attempts++;
if (ok)
{
p.Consumed = true;
}
try
{
await redb.SaveAsync(row).ConfigureAwait(false);
await tx.CommitAsync().ConfigureAwait(false);
}
catch
{
await tx.RollbackAsync().ConfigureAwait(false);
throw;
}
return ok
? new ChangeEmailVerifyResult(true, p.UserId, p.NewEmail, p.CurrentEmail, "ok")
: new ChangeEmailVerifyResult(false, 0, "", "", "bad_token");
}
private static string GenerateToken()
{
Span buf = stackalloc byte[32];
RandomNumberGenerator.Fill(buf);
return Base64UrlEncode(buf);
}
private static string Base64UrlEncode(ReadOnlySpan bytes)
{
var s = Convert.ToBase64String(bytes);
return s.TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
}
Path: redb-identity/src/redb.Identity.Core/Configuration/AdminScopeEntitlementOptions.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/Configuration/AdminScopeEntitlementOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// Role-driven entitlement for administrative scopes.
///
/// OAuth checks a scope against the client: may this application ask for it? That answer says
/// nothing about the person signing in, so a console permitted to request identity:manage handed
/// the master management scope to every account that could log into it. This gate adds the missing half
/// for user-bound grants: an administrative scope survives only when the user's effective roles carry
/// it. The client_credentials grant is untouched — it has no user, and the application's
/// scp:{scope} permission remains its authoritative gate.
///
///
/// What counts as administrative is deliberately narrow and explicit: Identity's own management surface
/// (identity:*) and SCIM. An operator's own scopes are none of this gate's business unless they
/// are listed here. identity:account is exempt — it is the self-service scope every signed-in
/// user is meant to hold.
///
///
public sealed class AdminScopeEntitlementOptions
{
///
/// Master switch, on by default. Turning it off restores the pre-gate behaviour, where any account
/// that can sign in to a console permitted to request identity:manage holds it. Present so a
/// deployment that locks itself out can recover from configuration alone, without a rebuild.
///
public bool Enabled { get; set; } = true;
/// Scope-name prefixes that require an entitling role. Default: identity:.
public List GatedPrefixes { get; set; } = new() { "identity:" };
/// Individual scope names that require an entitling role. Default: scim.
public List GatedScopes { get; set; } = new() { "scim" };
///
/// Scopes never gated even when a prefix matches. Default: identity:account — self-service
/// over one's own profile, which every signed-in user is supposed to have.
///
public List Exempt { get; set; } = new() { "identity:account" };
/// True when may only be issued to a user whose roles carry it.
public bool IsGated(string scope)
{
if (string.IsNullOrEmpty(scope)) return false;
foreach (var exempt in Exempt)
{
if (string.Equals(scope, exempt, StringComparison.Ordinal)) return false;
}
foreach (var gated in GatedScopes)
{
if (string.Equals(scope, gated, StringComparison.Ordinal)) return true;
}
foreach (var prefix in GatedPrefixes)
{
if (!string.IsNullOrEmpty(prefix) && scope.StartsWith(prefix, StringComparison.Ordinal)) return true;
}
return false;
}
}
Path: redb-identity/src/redb.Identity.Core/Configuration/BackchannelLogoutOptions.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/Configuration/BackchannelLogoutOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// Which addresses a client's backchannel_logout_uri (OIDC Back-Channel Logout 1.0) may point at. The server
/// POSTs a logout_token there when a session of that client ends, so the address is checked by the outbound
/// URL guard when it is registered (management API, dynamic registration) and again before every POST.
///
public sealed class BackchannelLogoutOptions
{
///
/// Require https for backchannel_logout_uri. Default: . Set to
/// only for relying parties on a trusted network that serve plain HTTP.
///
public bool RequireHttps { get; set; } = true;
///
/// Allow backchannel_logout_uri to resolve to loopback, private (RFC 1918), link-local or otherwise
/// non-public addresses. Default: . Enable it when relying parties are reached on an
/// internal network (a container network, a private subnet); then any registrant can make the server POST to
/// such an address, so keep dynamic registration behind an initial access token.
///
public bool AllowPrivateNetworkTargets { get; set; }
}
Path: redb-identity/src/redb.Identity.Core/Configuration/ChangeEmailOptions.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/Configuration/ChangeEmailOptions.cs
----
using System;
namespace redb.Identity.Core.Configuration;
///
/// N-4 (Session E, sub-step N4-7): tunables for the verify-then-commit change-of-e-mail
/// flow (direct-vm://identity-me-change-email-request +
/// direct-vm://identity-change-email-confirm).
///
/// Unlike the soft path on /me/profile (which overwrites the e-mail immediately
/// and lazily resets EmailVerified=false), the change-email flow defers the
/// commit until the user proves control of the new address: the confirmation link is
/// e-mailed to the new address; the current address remains the canonical login
/// until the link is clicked. On successful confirm the swap is atomic and
/// EmailVerified is set to true in the same transaction.
///
///
/// Feature-gated by : when false (default), neither route is
/// registered and the HTTP facade returns 404. Per-client URL whitelisting lives on
/// ApplicationProps.ChangeEmailUris.
///
///
public sealed class ChangeEmailOptions
{
///
/// Master switch. When false (default), the request + confirm direct-vm routes
/// are not registered. Opt-in until a host wires an IEmailNotificationChannel
/// and configures per-client ApplicationProps.ChangeEmailUris.
///
public bool Enabled { get; set; } = false;
///
/// Time-to-live for an issued single-use change-of-e-mail token. Recommended range:
/// 30 minutes – 24 hours. Default: 1 hour — short enough to limit the window during
/// which a stolen link can hijack the address, long enough for a user to retrieve
/// the e-mail from spam folders.
///
public TimeSpan TokenTtl { get; set; } = TimeSpan.FromHours(1);
///
/// When true (default), issuing a new change-of-e-mail token marks any prior
/// unconsumed tokens for the same user as Consumed. Prevents an attacker who
/// previously coerced the user into requesting a change from racing the legitimate
/// new request.
///
public bool InvalidatePreviousTokensOnRequest { get; set; } = true;
///
/// When true, ignores the
/// email field on inbound MeUpdateProfileRequest bodies so users
/// cannot bypass verification by hitting the soft path. Default false keeps
/// the soft path functional alongside the strict path (back-office deployments).
///
public bool RejectSoftEmailChange { get; set; } = false;
}
Path: redb-identity/src/redb.Identity.Core/Configuration/ClientKeysOptions.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/Configuration/ClientKeysOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// Governs how the server fetches a client's JWKS from its jwks_uri
/// (RFC 7517), used to verify things the client signed: JAR request objects (RFC 9101)
/// and private_key_jwt assertions (RFC 7523).
///
/// These are SSRF controls, not tuning knobs. The URL comes from the client record,
/// so a fetch makes the server issue an outbound request to an address someone else chose.
/// Without the restrictions below that is a probe into the internal network — including cloud
/// metadata endpoints such as 169.254.169.254, which hand out credentials to anyone
/// who can reach them. Loosen them only for local development.
///
///
public sealed class ClientKeysOptions
{
///
/// How long a fetched JWKS is reused before a background refresh. Default: 12 hours.
/// A kid miss triggers one immediate out-of-band refresh regardless of this value,
/// so client key rotation is picked up without waiting for the TTL.
///
public TimeSpan CacheLifetime { get; set; } = TimeSpan.FromHours(12);
///
/// Minimum interval between forced refreshes of the same URL. Bounds how often an
/// unauthenticated caller can make us fetch by replaying requests with unknown kids.
/// Default: 5 minutes.
///
public TimeSpan MinimumRefreshInterval { get; set; } = TimeSpan.FromMinutes(5);
///
/// Timeout for a single JWKS fetch. Default: 5 seconds — an authorization request is
/// waiting on it, so this must stay short.
///
public TimeSpan FetchTimeout { get; set; } = TimeSpan.FromSeconds(5);
///
/// Maximum accepted JWKS document size in bytes. Default: 512 KiB. A real key set is a
/// few KiB; the cap stops a hostile endpoint from streaming an endless body at us.
///
public int MaxDocumentBytes { get; set; } = 512 * 1024;
///
/// Most jwks_uri addresses whose key sets are kept at once. With open dynamic registration every new
/// client can name its own address, so the cache is bounded: over the limit, entries whose cache lifetime has
/// passed go first, then the least recently used; an entry with a fetch in flight stays. A dropped address is
/// fetched again the next time it is needed. Worst-case memory is this times .
/// Default: 256.
///
public int MaxCachedKeySets { get; set; } = 256;
///
/// Require https for jwks_uri. Default: true.
/// Only set to false for local development against a plain-HTTP test client —
/// over HTTP the key set can be swapped in transit, which defeats the signature check
/// it is supposed to anchor.
///
public bool RequireHttps { get; set; } = true;
///
/// Allow jwks_uri to resolve to loopback, private (RFC 1918), link-local or
/// otherwise non-public addresses. Default: false.
/// Only enable for local development or integration tests that host a JWKS on
/// localhost; in production this is the difference between an outbound fetch and
/// an internal port scan driven by whoever can edit a client record.
///
public bool AllowPrivateNetworkTargets { get; set; }
}
Path: redb-identity/src/redb.Identity.Core/Configuration/DeliveryOptions.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/Configuration/DeliveryOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// Delivery of events to webhook subscribers and to the external audit targets through the outbox table
/// identity_delivery_outbox.
///
/// Guarantee: at least once, no order. An event reaches the outbox in the same pass that writes its
/// audit row, after the request that caused it has committed; a delivery whose success was not
/// recorded (the node stopped between the answer and the status update) is sent again with the same
/// X-RedbIdentity-Delivery id. Receivers deduplicate by that id (or by the event's
/// EventId) and order by the event's Timestamp, not by arrival.
///
///
public sealed class DeliveryOptions
{
/// How often a node looks for due deliveries. Default: 2 seconds.
public TimeSpan PollInterval { get; set; } = TimeSpan.FromSeconds(2);
/// Due rows read per pass. Default: 50.
public int BatchSize { get; set; } = 50;
/// Deliveries in flight at once on one node. Default: 8.
public int MaxParallel { get; set; } = 8;
///
/// Deliveries in flight at once for one destination: a subscriber that hangs holds at most this
/// many slots, the others keep the rest. Default: 2.
///
public int MaxParallelPerDestination { get; set; } = 2;
///
/// How long a claimed row stays reserved to the node that took it. Raised to the delivery timeout
/// plus a margin when a subscription's timeout is longer. Default: 60 seconds.
///
public TimeSpan Lease { get; set; } = TimeSpan.FromSeconds(60);
///
/// How long the list of enabled subscriptions is kept in memory. The webhook management API
/// refreshes it on this node at once; other nodes see a change within this time. Default: 30 seconds.
///
public TimeSpan SubscriptionCache { get; set; } = TimeSpan.FromSeconds(30);
/// How long a delivered row is kept before the cleanup deletes it. Default: 7 days.
public TimeSpan DeliveredRetention { get; set; } = TimeSpan.FromDays(7);
///
/// How long a failed or cancelled row is kept, for inspection and redelivery through the management
/// API, before the cleanup deletes it. Default: 30 days.
///
public TimeSpan FailedRetention { get; set; } = TimeSpan.FromDays(30);
///
/// How often the cleanup runs (leader-only under a Tsak cluster); 0 or infinite turns it off.
/// Default: 1 hour.
///
public TimeSpan CleanupInterval { get; set; } = TimeSpan.FromHours(1);
/// Rows one cleanup statement deletes, so no statement holds the table long. Default: 1000.
public int CleanupBatchSize { get; set; } = 1000;
///
/// The module reports itself Degraded when the oldest undelivered row is older than this: the
/// worker is not running, or a destination has been down that long. Default: 5 minutes.
///
public TimeSpan DegradedAfter { get; set; } = TimeSpan.FromMinutes(5);
}
Path: redb-identity/src/redb.Identity.Core/Configuration/DpopOptions.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/Configuration/DpopOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// Z4 (RFC 9449): Demonstrating Proof-of-Possession at the Application Layer.
/// Configures DPoP proof validation and replay prevention for the Identity server's
/// token endpoint. When = false, all DPoP headers are ignored
/// and access tokens are issued as plain bearer tokens.
///
/// Default policy: SOFT — clients MAY send a DPoP proof; absence of one yields
/// a normal bearer token. Per-client strict enforcement is opt-in via
/// ApplicationProps.RequireDpop (when present) or via
/// =true (server-wide).
///
///
public sealed class DpopOptions
{
///
/// Master switch for DPoP support (validation + cnf.jkt binding + discovery).
/// Default: false.
///
public bool Enabled { get; set; }
///
/// When true, every access-token request MUST present a valid DPoP proof
/// or be rejected with invalid_dpop_proof. Default: false (soft mode —
/// clients opt-in by sending the header).
///
public bool RequireForAccessTokens { get; set; }
///
/// Allowed JWS algorithms in DPoP proofs. RFC 9449 §4.2 mandates asymmetric
/// algorithms only. Defaults to ES256, ES384, RS256, PS256.
///
public string[] AllowedSigningAlgorithms { get; set; } =
["ES256", "ES384", "ES512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512"];
///
/// Maximum age of the iat claim in seconds (clock-skew + transit tolerance).
/// RFC 9449 §11.1 recommends a small window. Default: 60 seconds.
///
public int IatToleranceSeconds { get; set; } = 60;
///
/// Replay-store backend selector — see .
///
public DpopReplayStoreOptions ReplayStore { get; set; } = new();
///
/// Z4 P2 (RFC 9449 §8): when true, every DPoP proof MUST carry a valid
/// server-issued nonce claim, and proofs without one are rejected with
/// use_dpop_nonce + DPoP-Nonce response header. Default: false.
///
public bool RequireNonce { get; set; }
///
/// Z4 P2 (RFC 9449 §8): nonce validity window for stateless HMAC nonces. The
/// server emits a fresh nonce on every response; clients have this much time to
/// reuse it before they MUST request a new one. Default: 5 minutes.
///
public TimeSpan NonceLifetime { get; set; } = TimeSpan.FromMinutes(5);
///
/// Z4 P2 (RFC 9449 §8): override secret used to sign stateless HMAC nonces.
/// When unset, a process-stable random secret is generated at startup so a
/// cluster of servers will not honour each other's nonces unless this is
/// pinned to a shared value (e.g. via IConfiguration).
///
public string? NonceSigningSecret { get; set; }
}
///
/// Replay-store configuration for DPoP proof jti de-duplication.
///
/// SECURITY: the in-process Memory backend is single-instance only. In
/// multi-node deployments behind a load balancer the same DPoP proof can land on
/// different nodes, defeating replay protection. Switch to redis or
/// redb for any multi-instance setup.
///
///
public sealed class DpopReplayStoreOptions
{
///
/// Backend identifier — memory (default), redis, or redb.
///
public string Backend { get; set; } = "memory";
///
/// Connection string for the Redis backend. Falls back to
/// 's Redis CS when omitted.
///
public string? RedisConnectionString { get; set; }
/// Key prefix for Redis entries. Default: identity:dpop:jti:.
public string RedisKeyPrefix { get; set; } = "identity:dpop:jti:";
///
/// Sweep interval for the in-memory backend (cleanup of expired entries).
/// Default: 5 minutes.
///
public TimeSpan MemorySweepInterval { get; set; } = TimeSpan.FromMinutes(5);
}
Path: redb-identity/src/redb.Identity.Core/Configuration/EmailVerificationOptions.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/Configuration/EmailVerificationOptions.cs
----
using System;
namespace redb.Identity.Core.Configuration;
///
/// N-4 (Session C, sub-step N4-6): tunables for the e-mail-verification flow
/// (direct-vm://identity-me-email-verify-send +
/// direct-vm://identity-email-verify-confirm).
///
/// Defaults follow common practice (Auth0=5d, Okta=7d, Cognito=24h, Microsoft Entra B2C=24h)
/// at the conservative end. A 24-hour TTL is long enough for a user to retrieve the e-mail
/// from spam folders / corporate quarantines but short enough to limit replay risk if the
/// inbox is later compromised.
///
///
/// The flow itself is feature-gated by : when false, neither
/// the send nor the confirm direct-vm route is registered and the HTTP facade returns 404.
/// Per-client URL whitelisting lives on ApplicationProps.EmailVerifyUris (mirror of
/// PasswordResetUris) so multi-tenant deployments can scope each BFF to its own
/// verify page.
///
///
public sealed class EmailVerificationOptions
{
///
/// Master switch. When false (default), the send + confirm direct-vm routes
/// are not registered and Core does NOT automatically clear
/// UserProps.EmailVerified on /me e-mail change. Opt-in until a host wires an
/// IEmailNotificationChannel and configures per-client
/// ApplicationProps.EmailVerifyUris.
///
public bool Enabled { get; set; } = false;
///
/// Time-to-live for an issued single-use verification token. Recommended range:
/// 1 hour – 7 days. Default: 24 hours.
///
public TimeSpan TokenTtl { get; set; } = TimeSpan.FromHours(24);
///
/// When true (default) Core flips UserProps.EmailVerified to false
/// as soon as a /me profile update changes the user's e-mail address. The BFF is then
/// expected to call POST /api/v1/identity/me/verify-email/send to dispatch a
/// fresh verification e-mail. When false, the flag is preserved across changes
/// (legacy behaviour — only suitable for trusted-back-office deployments).
///
public bool AutoResetOnChange { get; set; } = true;
}
Path: redb-identity/src/redb.Identity.Core/Configuration/IdempotencyOptions.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/Configuration/IdempotencyOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// E2 — RFC-style Idempotency-Key support for admin/SCIM mutation endpoints.
///
/// When enabled, repeated requests carrying the same Idempotency-Key header (within
/// ) replay the cached response body and HTTP status code instead of
/// re-executing the underlying mutation. Storage backend: redb PROPS
/// (identity.idempotency_record) with TTL cleanup via
/// — no Redis dependency.
///
///
/// Token issuance is auto-idempotent through the one-time code grant (see C11), so
/// the protocol routes do not consult this cache.
///
///
public sealed class IdempotencyOptions
{
///
/// Master switch for idempotency caching. When false, the
/// Idempotency-Key header is ignored and every mutation executes normally.
/// Default: true.
///
public bool Enabled { get; set; } = true;
///
/// How long a cached response is replayed for the same key. After this window the
/// stored record is eligible for background deletion and a fresh request creates a new
/// resource. Default: 24 hours (de-facto industry standard, e.g. Stripe).
///
public TimeSpan Ttl { get; set; } = TimeSpan.FromHours(24);
///
/// Maximum accepted length of the inbound Idempotency-Key header value. Keys
/// longer than this limit are silently ignored (treated as if no key was supplied) so a
/// caller cannot blow up the PROPS name index with arbitrary payload. Default: 200.
///
public int MaxKeyLength { get; set; } = 200;
}
Path: redb-identity/src/redb.Identity.Core/Configuration/IdentityAuditOptions.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/Configuration/IdentityAuditOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// Configuration for the identity audit subsystem.
/// Audit events are dispatched to one or more configurable targets (any redb.Route URI).
///
public class IdentityAuditOptions
{
///
/// Master switch for audit event dispatch. Default: true.
/// When disabled, events are still logged via ILogger but not sent to any target.
///
/// R1 made local persistence cheap (single INSERT into a flat
/// identity_audit_log table instead of a multi-row props write),
/// so the gate flipped to opt-out — every operator's first question on a
/// fresh Identity deployment was "where's the audit log?".
///
///
public bool Enabled { get; set; } = true;
///
/// Global event type filter. "*" means all events.
/// Comma-separated whitelist: "TokenIssued,UserLoggedOut,AuthorizationGranted".
/// Applies to all targets uniformly.
///
public string Filter { get; set; } = "*";
///
/// H9 (v1.0 DoD): When true and is also true, every event is persisted to the
/// built-in identity.audit_event PROPS store (queryable via GET /api/v1/identity/audit).
/// External streaming remain independent. Default: true.
///
public bool PersistToProps { get; set; } = true;
///
/// Events of one route that go to the events route at the same time (the wire taps' thread pool profile
/// identity-audit). Up to 1000 more wait; past that the request that raised the event runs it
/// itself. Default: 8.
///
public int TapConcurrency { get; set; } = 8;
///
/// List of audit targets. Each target is a redb.Route URI endpoint.
///
public List Targets { get; set; } = [];
}
///
/// A single audit target — any redb.Route producer URI (sql:, kafka:, es:, rabbitmq:, log:, etc.).
///
public class AuditTarget
{
///
/// Name of this target, required and unique among the enabled targets: the outbox rows of the target
/// carry it (at most 200 characters), and logs and metrics name the target by it. Renaming a target
/// leaves its pending rows behind as cancelled.
///
public string Name { get; set; } = string.Empty;
/// Attempts before a delivery to this target ends failed. Default: 10.
public int MaxAttempts { get; set; } = 10;
///
/// Wait before the second attempt, in milliseconds; it doubles with every attempt, up to 60 seconds.
/// Default: 1000.
///
public int RetryBackoffMs { get; set; } = 1000;
/// Time one attempt may take, in milliseconds. Default: 10000.
public int TimeoutMs { get; set; } = 10_000;
///
/// Whether this target is active. Default: false.
///
public bool Enabled { get; set; }
///
/// redb.Route URI for the target endpoint.
///
/// SQL parameters are written :#name (the Camel form). @name is NOT a parameter —
/// it reaches the database as-is, because it collides with T-SQL and MySQL variables. A target
/// still carrying the old @name form stops writing rows and fails with a database error.
/// Each parameter is bound by param.name=..., then a header of that name, then a key of
/// the body dictionary; casts work (:#details::jsonb).
///
/// Examples:
///
/// sql:INSERT INTO identity_audit_log(event_id, details) VALUES(:#event_id, :#details::jsonb)?dataSource=#pg-audit¶m.event_id=${header.event_id}¶m.details=${header.details}
/// kafka:identity-audit?brokers=localhost:29092
/// es:identity-audit?server=localhost&port=9200
/// rabbitmq:identity-audit?host=localhost
/// log:identity-audit?level=Information
///
///
public string Uri { get; set; } = string.Empty;
}
Path: redb-identity/src/redb.Identity.Core/Configuration/IdentityWebAuthnOptions.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/Configuration/IdentityWebAuthnOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// MFA-3 (WebAuthn / FIDO2 / Passkeys): Relying-Party configuration.
///
/// Crypto-binding fields are explicit and fail-fast on misconfig. RpId and Origins
/// participate in WebAuthn signature verification — once a credential is registered against
/// a given RpId, that credential is permanently bound to that RpId (the RpIdHash is part
/// of the signed authenticatorData). Changing RpId after deployment invalidates every
/// existing credential. To prevent that footgun, the validator ()
/// requires RpId and at least one Origin to be explicitly set; null/empty defaults are
/// rejected with at startup. A wrong default would
/// cause silent breakage on the next domain rename.
///
///
/// is cosmetic-only (shown in the OS authenticator UI as
/// "Sign in to {RpName}") and is auto-derived from the Identity issuer when unset.
///
///
public sealed class IdentityWebAuthnOptions
{
///
/// Master switch. When false (default) WebAuthn registration/assertion routes are
/// not exposed and the WebAuthn challenge store is not required to be registered.
/// When true, is invoked at startup and will throw if
/// / are unset.
///
public bool Enabled { get; set; }
///
/// WebAuthn Relying Party ID — typically the registrable domain or a subdomain of it
/// (e.g. auth.example.com or just example.com). Must NOT include scheme,
/// port, or path. The browser will only release a credential to an RP whose origin's
/// effective domain equals this value or is a registrable suffix.
///
/// Required. No default — must be set explicitly because changing it after
/// credentials are registered breaks all of them.
///
///
public string? RpId { get; set; }
///
/// Display name shown in the OS authenticator's prompt ("Sign in to {RpName} on
/// auth.example.com"). Cosmetic only, not part of the cryptographic binding.
/// Auto-derives from 's host if null.
///
public string? RpName { get; set; }
///
/// Allowed origins for WebAuthn ceremonies, including scheme and port for non-default
/// ports (e.g. https://auth.example.com, https://auth.example.com:8443).
/// The browser includes the origin in clientDataJSON; the server rejects any
/// origin not listed here. Multiple origins are valid for multi-app SSO scenarios where
/// several apps share a single registrable domain.
///
/// Required: must contain at least one origin.
///
///
public List Origins { get; set; } = new();
///
/// Browser-side ceremony timeout in milliseconds. Authenticator will cancel after this
/// elapses without user interaction. Default: 60 000 (60s) — WebAuthn-spec recommended
/// for cross-platform / sync-passkey ceremonies. Server-side challenge TTL
/// () is independent.
///
public int TimeoutMs { get; set; } = 60_000;
///
/// Server-side TTL of issued challenges, in seconds. Must be ≥ TimeoutMs/1000 to give
/// the browser ceremony enough time. Default: 300 (5 min) — matches OTP TTL and aligns
/// with the encrypted setup-token / mfa_state TTL in MfaStateProtector.
/// Consumed-challenge markers () are
/// retained until this point past completion to anchor anti-replay.
///
public int ChallengeTtlSeconds { get; set; } = 300;
///
/// User-verification requirement: required | preferred | discouraged.
///
/// required = AAL2-strict; PIN/biometric every time. Breaks
/// older U2F-only authenticators (Yubikey 4 / Neo without FIPS firmware).
/// preferred = AAL2 with graceful downgrade for legacy keys
/// (default). NIST AAL2 satisfied for credentials registered with UV; per-credential
/// ratchet (registered-with-UV →
/// must-assert-with-UV) blocks downgrade attacks.
/// discouraged = single-factor (do NOT use for MFA).
///
/// Default: preferred.
///
public string UserVerification { get; set; } = "preferred";
///
/// Attestation conveyance preference: none | indirect | direct |
/// enterprise. none is recommended for passkey/MFA scenarios because
/// sync-passkeys (iCloud Keychain, Google Password Manager) never produce attestation
/// chains and would break under direct. Use direct only when AAL3 / FIDO L2
/// certification is in scope (typically gov / regulated industries) — and have an
/// AaguidBlocklist or MDS in place to act on the data. Default: none.
///
public string Attestation { get; set; } = "none";
///
/// Whether to fetch the FIDO Metadata Service (MDS3) on startup for AAGUID lookups
/// (vendor name / icon / certification status / revocation list). Disabled by default
/// — MDS requires HTTPS reachability of https://mds3.fidoalliance.org/ and a
/// JWT chain validation up to GlobalSign root, which is unsuitable for air-gapped /
/// on-prem deployments. When false, is the only AAGUID
/// gating. v1.0 default: false (MFA AAL2 satisfied without MDS).
///
public bool UseFidoMetadataService { get; set; }
///
/// Manual list of banned authenticator AAGUIDs (16-byte GUIDs in the canonical
/// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx form). A registration request whose
/// attested AAGUID matches an entry is rejected with aaguid_blocked. Useful for
/// known-bad models (compromised supply-chain runs, recalled hardware) without bringing
/// up MDS infra. Null/empty disables blocklist enforcement.
///
public List? AaguidBlocklist { get; set; }
///
/// Interval between automatic cleanup of expired
/// rows. Set to
/// or to disable.
/// Default: 1 hour. Clustered — runs on the route-leader node only.
///
public TimeSpan ChallengeCleanupInterval { get; set; } = TimeSpan.FromHours(1);
///
/// Throws if required fields are unset or invalid.
/// Called from RedbIdentityServiceExtensions.AddRedbIdentity after
/// Configure<IdentityWebAuthnOptions> binds the appsettings section, so a
/// misconfigured deployment fails on startup rather than at first registration request.
///
public void Validate()
{
if (string.IsNullOrWhiteSpace(RpId))
throw new InvalidOperationException(
"IdentityWebAuthnOptions.RpId is required (e.g. \"auth.example.com\"). " +
"Note: changing RpId after credentials are registered invalidates them — choose carefully.");
if (RpId.Contains("://", StringComparison.Ordinal) || RpId.Contains('/', StringComparison.Ordinal))
throw new InvalidOperationException(
$"IdentityWebAuthnOptions.RpId must be a bare host name without scheme/path, got '{RpId}'.");
if (Origins is null || Origins.Count == 0)
throw new InvalidOperationException(
"IdentityWebAuthnOptions.Origins is required and must contain at least one https:// origin " +
"(e.g. [\"https://auth.example.com\"]).");
foreach (var origin in Origins)
{
if (!Uri.TryCreate(origin, UriKind.Absolute, out var uri)
|| (uri.Scheme != "https" && !(uri.Scheme == "http" && uri.Host == "localhost")))
{
throw new InvalidOperationException(
$"IdentityWebAuthnOptions.Origins entry '{origin}' must be an absolute https:// URL " +
"(http://localhost is also allowed for local dev).");
}
}
if (TimeoutMs <= 0)
throw new InvalidOperationException(
$"IdentityWebAuthnOptions.TimeoutMs must be positive, got {TimeoutMs}.");
if (ChallengeTtlSeconds <= 0 || ChallengeTtlSeconds * 1000 < TimeoutMs)
throw new InvalidOperationException(
$"IdentityWebAuthnOptions.ChallengeTtlSeconds ({ChallengeTtlSeconds}) must be positive " +
$"and ≥ TimeoutMs/1000 ({TimeoutMs / 1000}).");
if (UserVerification is not ("required" or "preferred" or "discouraged"))
throw new InvalidOperationException(
$"IdentityWebAuthnOptions.UserVerification must be one of required/preferred/discouraged, got '{UserVerification}'.");
if (Attestation is not ("none" or "indirect" or "direct" or "enterprise"))
throw new InvalidOperationException(
$"IdentityWebAuthnOptions.Attestation must be one of none/indirect/direct/enterprise, got '{Attestation}'.");
if (AaguidBlocklist is { Count: > 0 })
{
foreach (var entry in AaguidBlocklist)
{
if (!Guid.TryParse(entry, out _))
throw new InvalidOperationException(
$"IdentityWebAuthnOptions.AaguidBlocklist entry '{entry}' is not a valid GUID.");
}
}
}
}
Path: redb-identity/src/redb.Identity.Core/Configuration/JarOptions.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/Configuration/JarOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// How strictly a client's declared request_object_signing_alg is enforced once
/// JAR (RFC 9101) is switched on.
///
public enum JarEnforcementMode
{
///
/// The declared algorithm is ignored: any algorithm this server supports is accepted,
/// as long as the signature itself verifies.
///
Off,
///
/// A mismatch is logged as a warning and the request proceeds. Use this to find out who
/// would break before switching to — the values were editable
/// long before anything read them, so some are guesses rather than statements of fact.
///
LogOnly,
///
/// A mismatch is rejected with invalid_request_object. The intended end state.
///
Enforce,
}
///
/// JAR (RFC 9101) — JWT-Secured Authorization Request. Applies only when
/// Features.EnableJar is .
///
public sealed class JarOptions
{
///
/// How to treat a mismatch between the request object's alg and the client's stored
/// RequestObjectSigningAlg. Default: .
///
/// The default is deliberately not . Those per-client
/// values were accepted by the admin API and UI for releases while nothing enforced them, so an
/// existing deployment may hold values nobody verified. Starting in LogOnly surfaces the
/// mismatches in the log instead of turning them into sign-in failures on upgrade day.
///
///
public JarEnforcementMode EnforcementMode { get; set; } = JarEnforcementMode.LogOnly;
///
/// Signature algorithms accepted on a request object. Asymmetric only — see
/// IClientKeyResolver for why HS* cannot work here (the client secret is
/// stored as a BCrypt hash). none is never accepted and cannot be added.
///
public string[] AllowedSigningAlgorithms { get; set; } =
["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"];
///
/// Clock-skew tolerance when checking exp / nbf / iat. Default: 60 seconds.
///
public TimeSpan ClockSkew { get; set; } = TimeSpan.FromSeconds(60);
///
/// Maximum accepted size of the request parameter in characters. Default: 50 000.
/// A real request object is a few hundred bytes; the cap keeps a hostile client from making
/// us parse megabytes on an unauthenticated endpoint.
///
public int MaxRequestObjectLength { get; set; } = 50_000;
///
/// Require that exp be present. RFC 9101 §4 lists it as required; some clients omit it.
/// Default: — without an expiry a captured request object stays
/// replayable forever.
///
public bool RequireExpiration { get; set; } = true;
///
/// Accept a request_uri parameter (the request object by reference, fetched over HTTP)
/// in addition to an inline request. Default: when JAR is on.
///
/// PAR's urn:ietf:params:oauth:request_uri:* values are never affected by this — those
/// are resolved by the PAR pipeline, not fetched.
///
///
public bool EnableRequestUri { get; set; } = true;
///
/// Fetch a request_uri only when it equals one of the client's registered request_uris
/// (OIDC Dynamic Client Registration 1.0 §2), compared exactly: the whole value, query and fragment included.
/// A client without registered values cannot use request_uri; an inline request is not affected.
/// Discovery publishes the value as require_request_uri_registration. Default: .
///
/// With a client that registered values is still held to them, and a client without
/// any may use any address, as before 4.8.0; every such use is logged as a warning naming the client, so the
/// clients to register can be found before this is switched back on.
///
///
public bool RequireRequestUriRegistration { get; set; } = true;
///
/// Timeout for fetching a request_uri. Default: 5 seconds — an authorization request is
/// blocked on it.
///
public TimeSpan RequestUriFetchTimeout { get; set; } = TimeSpan.FromSeconds(5);
///
/// Require https for a request_uri. Default: . Over plain
/// HTTP the request object could be swapped in transit, defeating the signature it carries.
/// Relax only for local development.
///
public bool RequestUriRequireHttps { get; set; } = true;
///
/// Allow a request_uri to resolve to a non-public address (loopback, private, link-local).
/// Default: — the URL comes from the client, so an internal target is an
/// SSRF attempt. Enable only for local development / integration tests.
///
public bool RequestUriAllowPrivateNetworkTargets { get; set; }
}
Path: redb-identity/src/redb.Identity.Core/Configuration/MintingKeySource.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/Configuration/MintingKeySource.cs
----
namespace redb.Identity.Core.Configuration;
///
/// Which key source signs and encrypts new tokens when both configured credentials
/// ( / )
/// and the props signing-key store () are present.
/// Both sources are trusted for validation and published in the JWKS either way; only the minting key differs.
///
public enum MintingKeySource
{
///
/// The configured credentials mint; the store's keys only validate. The state of a deployment moving its
/// keys to an HSM or a certificate: tokens signed by the store keep validating until they expire.
///
Configured,
///
/// The store's active key mints; the configured credentials only validate. The state of a deployment
/// moving off configured keys onto the store.
///
Store,
}
Path: redb-identity/src/redb.Identity.Core/Configuration/PasswordHashingOptions.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/Configuration/PasswordHashingOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// C12 — password hashing configuration.
///
/// selects the primary algorithm used for new password hashes.
/// On successful verification of a legacy hash (different algorithm, or same algorithm with
/// weaker parameters than the current configuration), the login flow re-hashes the plaintext
/// and persists it — the standard OWASP upgrade-on-login pattern. See
/// Security.MultiFormatPasswordHasher + Services.LoginService for the
/// implementation.
///
///
public sealed class PasswordHashingOptions
{
///
/// Primary algorithm used for new hashes. Default:
/// (OWASP 2023+ recommendation for password storage; memory-hard, GPU-resistant).
///
public PasswordHashAlgorithm Algorithm { get; set; } = PasswordHashAlgorithm.Argon2id;
/// Argon2id parameters (used when = ).
public Argon2idHashOptions Argon2id { get; set; } = new();
/// BCrypt parameters (used when =
/// and for verifying legacy BCrypt hashes).
public BcryptHashOptions Bcrypt { get; set; } = new();
}
/// Enumeration of supported primary password-hashing algorithms.
public enum PasswordHashAlgorithm
{
/// Argon2id — OWASP 2023+ recommended primary.
Argon2id,
/// BCrypt — legacy-compatible fallback.
Bcrypt,
}
///
/// Argon2id parameters. Defaults match OWASP 2023 guidance for password storage:
/// m=64 MiB, t=3, p=4, salt=16 bytes, hash=32 bytes (≈50–150 ms per verify on a modern CPU).
/// Tune per deployment and measure with identity.password.verify.duration histogram.
///
public sealed class Argon2idHashOptions
{
/// Memory cost in KiB. Default: 65536 (64 MiB).
public int MemoryKib { get; set; } = 65536;
/// Iterations (time cost). Default: 3.
public int Iterations { get; set; } = 3;
/// Degree of parallelism (lanes). Default: 4.
public int Parallelism { get; set; } = 4;
/// Salt length in bytes. Default: 16 (128 bit).
public int SaltBytes { get; set; } = 16;
/// Hash length in bytes. Default: 32 (256 bit).
public int HashBytes { get; set; } = 32;
}
///
/// BCrypt parameters. Defaults match current redb.Core.Security.BcryptPasswordHasher.
///
public sealed class BcryptHashOptions
{
/// BCrypt work factor. Default: 12 (~250 ms per verify on a modern CPU).
public int WorkFactor { get; set; } = 12;
}
Path: redb-identity/src/redb.Identity.Core/Configuration/PasswordPolicyOptions.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/Configuration/PasswordPolicyOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// H10 — server-side password policy applied by management, self-service and SCIM
/// password mutations. All knobs are exposed via the standard Tsak 5-layer config
/// pipeline (see redb.Identity.Core.config.json:Identity.PasswordPolicy).
/// Defaults are STRICT (NIST SP 800-63B Draft + OWASP ASVS 4.0.3 §2.1) so a freshly
/// bootstrapped deployment is secure-by-default; tune per environment.
///
public sealed class PasswordPolicyOptions
{
/// Minimum number of characters required. Default 12.
public int MinLength { get; set; } = 12;
///
/// Maximum number of characters accepted. Acts as a DoS guard against pathologically
/// long inputs reaching the Argon2id hasher. Default 512.
///
public int MaxLength { get; set; } = 512;
/// Require at least one ASCII digit (0-9). Default true.
public bool RequireDigit { get; set; } = true;
/// Require at least one ASCII uppercase letter (A-Z). Default true.
public bool RequireUppercase { get; set; } = true;
/// Require at least one ASCII lowercase letter (a-z). Default true.
public bool RequireLowercase { get; set; } = true;
///
/// Require at least one character from . Default false
/// — modern guidance (NIST SP 800-63B §5.1.1.2) deprecates forced symbol classes in
/// favour of length + breach screening.
///
public bool RequireSpecial { get; set; } = false;
///
/// Set of characters that count as "special" when is on.
/// Default covers the OWASP-recommended ASCII punctuation set.
///
public string SpecialChars { get; set; } = "!@#$%^&*()-_=+[]{}|;:,.<>?/`~\"'\\";
///
/// Number of recent password hashes (per user) to retain and reject on reuse. Set to
/// 0 to disable history checks. Default 5.
///
public int HistoryCount { get; set; } = 5;
///
/// Maximum age of a password before the user is forced to change it on next login.
/// Use to disable expiration entirely. Default
/// 90 days (industry baseline; turn off in deployments using passkeys/MFA-only).
///
public System.TimeSpan MaxAge { get; set; } = System.TimeSpan.FromDays(90);
///
/// When true, the configured IBreachedPasswordChecker is consulted on
/// every change/set. Default false — opt in by registering a checker
/// implementation (e.g. redb.Identity.PasswordPolicy.Hibp). With no checker
/// registered the flag is a no-op.
///
public bool BreachCheckEnabled { get; set; } = false;
}
Path: redb-identity/src/redb.Identity.Core/Configuration/PasswordRecoveryOptions.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/Configuration/PasswordRecoveryOptions.cs
----
using System;
namespace redb.Identity.Core.Configuration;
///
/// N-4 (Session C): tunables for the password-recovery flow
/// (direct-vm://identity-password-forgot +
/// direct-vm://identity-password-reset).
///
/// Defaults follow OWASP ASVS V6.1.3 ("reset token expires within 60 minutes") and the
/// industry midpoint (Auth0=60m, Okta=60m, Microsoft=15m, Cognito=60m) at the lower end
/// to minimise the window in which a leaked link is exploitable.
///
///
public sealed class PasswordRecoveryOptions
{
///
/// Time-to-live for an issued single-use reset token. Recommended range: 15–60 minutes.
/// Default: 30 minutes.
///
public TimeSpan TokenTtl { get; set; } = TimeSpan.FromMinutes(30);
}
Path: redb-identity/src/redb.Identity.Core/Configuration/RateLimitOptions.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/Configuration/RateLimitOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// C1 — Configuration for per-IP / per-(IP+username) rate limiting that sits in front of
/// /connect/token, /login, /mfa/verify, /mfa/recovery and
/// /mfa/methods routes.
///
///
///
/// The per-IP limit drops distributed brute-force attempts pooled across many usernames; the
/// per-(IP+username) failure counter blocks credential-stuffing against a single account from
/// one source. They run orthogonally to the per-account lockout enforced inside
/// (B5/B6).
///
///
/// In-memory backend (default). A ConcurrentDictionary-backed sliding-window
/// counter PER NODE — across an N-node cluster the effective ceiling is N × limit
/// (acceptable trade-off for online brute-force; matches NGINX/Envoy node-local limits).
///
///
/// Redis backend (opt-in). Sliding window via a sorted set (ZADD/ZREMRANGEBYSCORE/
/// ZCARD/EXPIRE) executed atomically — gives a true global limit across the cluster but
/// adds one round-trip per gated request.
///
///
public sealed class RateLimitOptions
{
/// Master switch. false = no rate-limit processors are wired into routes.
public bool Enabled { get; set; }
///
/// Per-IP requests-per-minute ceiling. Bucket = client IP (after C2 trust resolution).
/// Applies to /login and /connect/token. Default: 30.
///
public int PerIpPerMinute { get; set; } = 30;
///
/// Per-(IP+username) failure ceiling within .
/// Counts every login / MFA / token failure tied to a particular (IP, username) pair.
/// Default: 5.
///
public int PerIpUsernameFailures { get; set; } = 5;
/// Window for the per-(IP+username) failure counter. Default: 15 minutes.
public TimeSpan PerIpUsernameWindow { get; set; } = TimeSpan.FromMinutes(15);
///
/// Value sent as the Retry-After header on 429 responses when the store cannot
/// compute a precise hint. Default: 60 (seconds).
///
public int DefaultRetryAfterSeconds { get; set; } = 60;
///
/// Backing store identifier. "memory" (default) keeps counters per node;
/// "redis" requires and gives a global limit.
///
public string Backend { get; set; } = "memory";
///
/// StackExchange.Redis connection string used when is "redis".
/// Example: localhost:6379. Ignored otherwise.
///
public string? RedisConnectionString { get; set; }
///
/// Optional prefix applied to Redis keys to scope counters per environment / tenant.
/// Default: redb:identity:rl:.
///
public string RedisKeyPrefix { get; set; } = "redb:identity:rl:";
}
Path: redb-identity/src/redb.Identity.Core/Configuration/RedbIdentityOptions.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/Configuration/RedbIdentityOptions.cs
----
using Microsoft.IdentityModel.Tokens;
using redb.Identity.Contracts.Configuration;
namespace redb.Identity.Core.Configuration;
///
/// Configuration options for redb.Identity.
///
public class RedbIdentityOptions
{
///
/// Named redb instance to use. When null or empty, resolves default IRedbService.
///
public string? RedbInstanceName { get; set; }
///
/// Cross-module shared options (Issuer + Features). Single source of truth
/// for both Core (DI registration, OpenIddict configuration, direct-vm
/// route registration) and Http (discovery URL formatting, cookie Secure
/// detection, HTTP endpoint mounting). Bound from the Identity:*
/// section of context.json. The convenience properties
/// and are proxies onto this
/// instance so existing call-sites keep working unchanged.
///
public IdentitySharedOptions Shared { get; set; } = new();
///
/// Cross-module feature toggles. Proxy onto ..
///
public IdentityFeatureFlags Features
{
get => Shared.Features;
set => Shared.Features = value;
}
///
/// Token endpoint throttle: max requests per period per client.
/// Default: 10.
///
public int TokenThrottleMaxPerPeriod { get; set; } = 10;
///
/// Token endpoint throttle period.
/// Default: 1 second.
///
public TimeSpan TokenThrottlePeriod { get; set; } = TimeSpan.FromSeconds(1);
///
/// Retention period (days) for expired/revoked tokens before cleanup deletes them.
/// Default: 30.
///
public int TokenRetentionDays { get; set; } = 30;
///
/// Interval between automatic token cleanup runs.
/// Set to or Timeout.InfiniteTimeSpan to disable automatic cleanup.
/// Default: 1 hour.
///
public TimeSpan TokenCleanupInterval { get; set; } = TimeSpan.FromHours(1);
///
/// Batch size for soft-delete purge operations in .
/// Default: 50.
///
public int TokenCleanupBatchSize { get; set; } = 50;
///
/// Retention period (days) for revoked sessions before cleanup deletes them.
/// Default: 14.
///
public int SessionRetentionDays { get; set; } = 14;
///
/// S-track: idle timeout. A session whose LastAccessedAt is older
/// than this is auto-revoked on the next SessionService.ListAsync /
/// SessionCleanupProcessor pass. Mirrors industry defaults
/// (Keycloak 30 min, Okta 2 h, Auth0 3 days). Default: 24 h — middle of
/// the range, lets active dev / cli sessions stay alive overnight while
/// killing forgotten ones within a day.
///
public TimeSpan SessionIdleTimeout { get; set; } = TimeSpan.FromHours(24);
///
/// S-track: absolute timeout regardless of activity. A session whose
/// DateCreate is older than this is auto-revoked even if it was
/// just refreshed. Cap on total lifetime so a long-lived refresh-token
/// chain doesn't keep one cookie alive forever. Default: 30 days.
///
public TimeSpan SessionAbsoluteTimeout { get; set; } = TimeSpan.FromDays(30);
///
/// Interval between automatic session cleanup runs.
/// Set to or Timeout.InfiniteTimeSpan to disable.
/// Default: 1 hour.
///
public TimeSpan SessionCleanupInterval { get; set; } = TimeSpan.FromHours(1);
///
/// B3: interval between automatic cleanup runs for expired server-side MFA OTP rows
/// (). Set to or
/// Timeout.InfiniteTimeSpan to disable. Default: 1 hour. Clustered — runs on
/// the route-leader node only.
///
public TimeSpan MfaOtpCleanupInterval { get; set; } = TimeSpan.FromHours(1);
///
/// W6-0: maximum lifetime of an entry in the backchannel revoked-sids list. Server clamps
/// any client-supplied ExpiresAt to now + RevokedSidsMaxRetention. Should be
/// at least the longest cookie / refresh-token lifetime among Relying Parties.
/// Default: 24 hours.
///
public TimeSpan RevokedSidsMaxRetention { get; set; } = TimeSpan.FromHours(24);
///
/// W6-0: interval between cleanup runs that purge expired entries from the
/// identity.revoked_sid PROPS table. Set to or
/// Timeout.InfiniteTimeSpan to disable. Clustered — runs on the route-leader
/// node only. Default: 1 hour.
///
public TimeSpan RevokedSidsCleanupInterval { get; set; } = TimeSpan.FromHours(1);
///
/// Interval between cleanup runs that delete idempotency records whose time to live
/// () has ended. Set to or
/// Timeout.InfiniteTimeSpan to disable. Clustered: runs on the route-leader node only.
/// Default: 1 hour.
///
public TimeSpan IdempotencyCleanupInterval { get; set; } = TimeSpan.FromHours(1);
///
/// Records deleted per batch by the idempotency record cleanup. A run deletes batch after batch until no
/// expired record is left. Default: 500.
///
public int IdempotencyCleanupBatchSize { get; set; } = 500;
///
/// Interval at which each replica reloads the DataProtection XML key-ring snapshot
/// () from PROPS storage. Runs per-node
/// (NOT cluster-leader-only) so every replica picks up keys rotated by other nodes,
/// preventing split-key-ring windows after rotation.
/// Set to or to disable
/// — safe for single-instance deployments where initial snapshot at
/// RedbXmlRepositoryInitListener.OnContextStarting is sufficient.
/// Default: 12 hours (≤ half of KeyManagementOptions.AutoRefreshIntervalForActiveKey 24h, per Nyquist).
///
public TimeSpan XmlRepositoryRefreshInterval { get; set; } = TimeSpan.FromHours(12);
///
/// MFA-3: WebAuthn (FIDO2 / Passkey) configuration. Disabled by default; set
/// to true and configure
/// +
/// to expose /connect/mfa/webauthn/* routes and the per-credential CRUD endpoints.
///
public IdentityWebAuthnOptions WebAuthn { get; set; } = new();
///
/// Issuer URI for the identity server (appears in iss claim and discovery document).
/// Required for production; defaults to https://localhost/ for development.
/// Proxy onto ..
///
public Uri Issuer
{
get => Shared.Issuer;
set => Shared.Issuer = value;
}
///
/// Signing credentials for JWT tokens. When empty, ephemeral keys are used (dev only).
///
public List SigningCredentials { get; set; } = [];
///
/// Encryption credentials for token payloads. When empty, ephemeral keys are used (dev only).
///
public List EncryptionCredentials { get; set; } = [];
///
/// When true, allows AddRedbIdentityServer to fall back to ephemeral signing /
/// encryption keys if no /
/// were configured. Must remain false in production — ephemeral keys split the
/// JWKS across cluster replicas (tokens issued by one node fail validation on another) and
/// invalidate every live token on restart. Set to true only in Development /
/// integration-test fixtures. Default: false.
///
public bool AllowEphemeralKeys { get; set; } = false;
///
/// A3: when true, OpenIddict signing / encryption credentials are populated from
/// the PROPS-backed . Initial keys are generated on
/// first context start () if the store is
/// empty; private PEM material is encrypted with the DataProtection key ring. Cluster
/// replicas share one JWKS because they read from the same PROPS rows.
///
/// Can be combined with pre-populated /
/// — the state of a deployment moving its keys to or from
/// configured ones. Both sources are then trusted for validation and published in the JWKS, and
/// must say which one signs and encrypts new tokens. Not with
/// : ephemeral keys stand in for persistent ones, and this is them.
///
/// Default: false (feature is opt-in until rotation automation ships).
///
public bool UsePropsSigningKeyStore { get; set; } = false;
///
/// Which key source signs and encrypts new tokens when both /
/// and the props signing-key store
/// () are configured. Both sources are always trusted for
/// validation and published in the JWKS; this decides the minting key only. Required when both sources
/// are present and refused when they are not: the pair is a migration state, and who mints during it is
/// the operator's decision, not the order two registrations happen to run in.
///
public MintingKeySource? MintingKeySource { get; set; }
/// Access token lifetime. Default: 1 hour.
public TimeSpan AccessTokenLifetime { get; set; } = TimeSpan.FromHours(1);
/// Refresh token lifetime. Default: 14 days.
public TimeSpan RefreshTokenLifetime { get; set; } = TimeSpan.FromDays(14);
///
/// Refresh token reuse leeway. After rotation, the old token remains valid for this window.
/// TimeSpan.Zero = strict rotation (old token rejected immediately).
/// Default: TimeSpan.Zero (strict).
///
public TimeSpan RefreshTokenReuseLeeway { get; set; } = TimeSpan.Zero;
/// Authorization code lifetime. Default: 5 minutes.
public TimeSpan AuthorizationCodeLifetime { get; set; } = TimeSpan.FromMinutes(5);
/// Identity token lifetime. Default: 5 minutes.
public TimeSpan IdentityTokenLifetime { get; set; } = TimeSpan.FromMinutes(5);
///
/// Issue access tokens as plain JWS (signed, not encrypted). Only access tokens: authorization codes,
/// refresh tokens, device and user codes and OpenIddict's state tokens stay encrypted, so an encryption
/// credential is required either way. Default: false.
///
public bool DisableAccessTokenEncryption { get; set; }
///
/// The OP's own audience for access tokens (RFC 9068 §3 default resource indicator).
/// Issued access tokens carry it whenever an identity:* scope is granted, or when
/// the granted scopes' Resources and the application's AccessTokenAudiences
/// are both empty; the local validation stack (management API) accepts only tokens that
/// carry it. null resolves to {Issuer}/resources
/// (see ).
///
public string? DefaultAccessTokenAudience { get; set; }
///
/// Resolves the effective OP audience: a configured value wins (trimmed), otherwise
/// {issuer}/resources with a single slash regardless of the issuer's trailing slash.
///
public static string ResolveDefaultAccessTokenAudience(Uri issuer, string? configured)
{
ArgumentNullException.ThrowIfNull(issuer);
if (!string.IsNullOrWhiteSpace(configured))
return configured.Trim();
return issuer.AbsoluteUri.TrimEnd('/') + "/resources";
}
///
/// Required OAuth scope for management API access.
/// Clients must request this scope to call /api/v1/identity/* endpoints.
/// Default: identity:manage.
///
public string ManagementScope { get; set; } = "identity:manage";
///
/// OAuth scope granting self-service access to the management API (B8).
/// A token bearing this scope may invoke management endpoints only when the body / route
/// userId matches the token's sub claim. Tokens bearing
/// are treated as administrators and may target any user.
/// Modeled on Keycloak's manage-account (self) vs realm-admin (cross-user)
/// split. Default: identity:account.
///
public string AccountScope { get; set; } = "identity:account";
///
/// Group-membership gate for selected OAuth scopes. Maps
/// scopeName → groupName. When a user-bound token request
/// (authorization_code, password, device_code, or a refresh_token derived from
/// these) requests one of the listed scopes, the OpenIddict pipeline rejects the
/// request with error=access_denied unless the authenticated user is a
/// (non-expired) member of the required group.
///
/// The client_credentials grant is intentionally unaffected — it has no
/// user identity, so the existing scp:{scope} permission on the
/// application is the authoritative gate for that flow.
///
///
/// Typical bootstrap configuration:
/// { ["identity:manage"] = "identity-admins" } — restricts the
/// management scope to members of the admin group.
///
/// Default: empty (no scope restrictions).
///
public Dictionary ScopeRequiredGroups { get; set; }
= new(StringComparer.Ordinal);
///
/// Role-driven entitlement for administrative scopes — the user-side half of the scope check that
/// OAuth only performs against the client. See .
///
/// Complements rather than replacing it: that one gates by group
/// membership and stays available for deployments modelling access with groups.
///
///
public AdminScopeEntitlementOptions AdminScopeEntitlement { get; set; } = new();
// ── Dynamic Client Registration (RFC 7591) ──
// Note: the on/off toggle moved to .EnableDynamicRegistration.
///
/// Grant types allowed for dynamically registered clients.
/// Default: ["authorization_code", "refresh_token"].
///
public string[] DynamicRegistrationAllowedGrantTypes { get; set; } =
["authorization_code", "refresh_token"];
///
/// Scopes allowed for dynamically registered clients.
/// Default: ["openid", "profile", "email", "phone", "address", "offline_access", "groups", "roles"].
/// All of these are user-info scopes (claims about the user) and standard OIDC profile/contact
/// scopes — none grant API privilege. Admin scopes (identity:*) and SCIM are intentionally
/// excluded so anonymous DCR cannot self-elevate. Override the list to restrict further if needed.
///
public string[] DynamicRegistrationAllowedScopes { get; set; } =
["openid", "profile", "email", "phone", "address", "offline_access", "groups", "roles"];
///
/// Optional initial access token (RFC 7591 §1.2). When set, the POST /connect/register
/// request must include Authorization: Bearer {token}. When null, empty or whitespace, no token
/// is configured: the endpoint is open (rate-limited only) and an anonymous registrant is refused
/// every administrative scope (see ), whatever
/// lists.
///
public string? DynamicRegistrationInitialAccessToken { get; set; }
///
/// Per-IP throttle for the Dynamic Client Registration endpoint: max requests per
/// . Tunable independently from
/// because DCR is a write-heavy admin
/// endpoint with very different traffic shape than the token endpoint.
/// Default: 5.
///
public int DynamicRegistrationThrottleMaxPerPeriod { get; set; } = 5;
///
/// Window for . Default: 10 seconds.
///
public TimeSpan DynamicRegistrationThrottlePeriod { get; set; } = TimeSpan.FromSeconds(10);
// ── Device Code Flow (RFC 8628) ──
// Note: the on/off toggle moved to .EnableDeviceCodeFlow.
// ── Pushed Authorization Requests (RFC 9126 / Z6) ──
// Note: the on/off toggle moved to .EnablePushedAuthorization.
///
/// Z6 (RFC 9126 §2.1): when true, the authorization endpoint REJECTS requests
/// that did not originate as a PAR (i.e. requests not carrying a request_uri issued
/// by this server). Effective only when
/// is also true. Default: false.
///
public bool RequirePushedAuthorizationRequests { get; set; }
///
/// Z6: lifetime of a request_uri issued by the PAR endpoint. RFC 9126 §2.2 mandates
/// it MUST be SHORT-LIVED; the typical value is 60 seconds. Default: 90 seconds.
///
public TimeSpan PushedAuthorizationRequestLifetime { get; set; } = TimeSpan.FromSeconds(90);
///
/// Z4 (RFC 9449): DPoP support — proof-of-possession-bound access tokens.
/// See for full configuration.
///
public DpopOptions Dpop { get; set; } = new();
///
/// How the server fetches a client's JWKS from its jwks_uri — SSRF limits,
/// cache lifetime and timeouts. Used to verify what a client signed: JAR request objects
/// (Z7 / RFC 9101) and private_key_jwt assertions. See .
///
public ClientKeysOptions ClientKeys { get; set; } = new();
///
/// Which addresses a client's backchannel_logout_uri may point at, checked at registration and before
/// every logout POST. See .
///
public BackchannelLogoutOptions BackchannelLogout { get; set; } = new();
///
/// Z7 (RFC 9101): JWT-Secured Authorization Request. Effective only when
/// is .
/// See .
///
public JarOptions Jar { get; set; } = new();
///
/// Webhook delivery through the outbox: polling, parallelism, lease and the subscription cache.
/// See .
///
public DeliveryOptions Delivery { get; set; } = new();
///
/// Lifetime of the device_code / user_code pair.
/// Default: 10 minutes (RFC 8628 §3.2 recommends ≤ 15 min).
///
public TimeSpan DeviceCodeLifetime { get; set; } = TimeSpan.FromMinutes(10);
///
/// Polling interval in seconds returned to the client in the device authorization response.
/// Default: 5 seconds (per RFC 8628 §3.2).
///
public int DeviceCodePollingInterval { get; set; } = 5;
// ── Resource Owner Password Credentials (RFC 6749 §4.3) ──
///
/// Enable the ROPC grant (grant_type=password). Opt-in only.
/// Allows direct username/password to token exchange via POST /connect/token.
/// Default: false.
///
public bool EnablePasswordFlow { get; set; }
// ── PKCE (RFC 7636) ──
///
/// Require Proof Key for Code Exchange (PKCE) on EVERY authorization_code request.
/// When true (default), an /connect/authorize request without a code_challenge
/// is rejected — the OAuth 2.1 hardening posture. Set to false to also accept plain
/// authorization_code flows without PKCE (e.g. legacy clients, or to certify the OpenID
/// "Basic OP" profile, whose non-PKCE tests require the OP to accept such requests).
/// PKCE, when present, is ALWAYS S256-only (RFC 7636 §4.2 — plain is never accepted),
/// regardless of this flag.
/// Default: true.
///
public bool RequirePkce { get; set; } = true;
///
/// RFC 8252 §7.3 — accept any port on a client's registered loopback redirect URI.
///
/// A native or CLI app (think az login, gh auth login) cannot know its callback
/// port before it starts: it asks the OS for an ephemeral one, so the port changes on every run
/// and cannot be registered ahead of time. §7.3 requires the authorization server to compare
/// everything about a loopback redirect URI EXCEPT the port. With this off, desktop clients
/// simply cannot use this provider.
///
///
/// The widening is narrow by construction: it applies only when the client has ALREADY
/// registered a redirect URI whose host is the loopback literal 127.0.0.1 or
/// [::1] (never the name localhost — §8.3 warns that a name goes through
/// resolution and can be pointed elsewhere), and only the port is ignored — scheme, host, path,
/// query and fragment must still match exactly. A web client registered at
/// https://app.example.com/cb has no loopback URI to match, so nothing about it changes.
///
/// Default: true — this is a MUST in RFC 8252 §7.3, not an opt-in feature.
///
public bool AllowLoopbackRedirectPortWildcard { get; set; } = true;
// ── Token Exchange (RFC 8693) ──
///
/// Enable the Token Exchange grant (grant_type=urn:ietf:params:oauth:grant-type:token-exchange).
/// Allows delegation and impersonation token flows (RFC 8693).
/// Default: false.
///
public bool EnableTokenExchange { get; set; }
///
/// Allow impersonation token exchange (the actor disappears — the new token looks like
/// it was issued directly to the subject). When false, only delegation is allowed
/// (the act claim preserves the actor chain).
/// Default: false.
///
public bool TokenExchangeAllowImpersonation { get; set; }
///
/// Maximum depth of the act claim delegation chain.
/// Prevents runaway chained exchanges. 0 = unlimited.
/// Default: 5.
///
public int TokenExchangeMaxDelegationDepth { get; set; } = 5;
// ── Session / Login ──
///
/// Path to the login page. Used for redirect when login_required on authorize.
/// Default: /login.
///
public string LoginPath { get; set; } = "/login";
///
/// Path to the consent page. Used for redirect when consent_required on authorize.
/// Default: /consent.
///
public string ConsentPath { get; set; } = "/consent";
///
/// Path to the MFA verification page. Used for redirect when MFA is required after login.
/// Default: /mfa.
///
public string MfaPath { get; set; } = "/mfa";
///
/// Path to the MFA recovery code page.
/// Default: /mfa/recovery.
///
public string MfaRecoveryPath { get; set; } = "/mfa/recovery";
///
/// Minimum delay between consecutive OTP send requests (SMS/Email).
/// Prevents spamming an end user / running up SMS bills. Default: 60 seconds.
///
public TimeSpan OtpCooldown { get; set; } = TimeSpan.FromSeconds(60);
///
/// Maximum OTP sends per user per rolling hour (SMS/Email combined).
/// Default: 5.
///
public int OtpMaxPerHour { get; set; } = 5;
///
/// Tolerance (clock skew) applied to MFA lockout-window comparisons (B9 / BUG-5).
/// A user is treated as locked out while now < LockedUntil + skew and unlocked
/// once now >= LockedUntil + skew. Prevents premature unlock when the server
/// clock is slightly fast relative to the clock that wrote LockedUntil.
/// Default: 5 seconds.
///
public TimeSpan MfaLockoutClockSkew { get; set; } = TimeSpan.FromSeconds(5);
// ── MFA recovery codes (B4: PBKDF2 + per-user salt + pepper) ──
///
/// Server-wide pepper applied to recovery-code hashing in addition to the per-user salt
/// (base64-encoded, 16+ bytes recommended). When null:
///
/// If is true, an ephemeral random
/// pepper is generated at startup. Recovery codes are then unverifiable across restarts /
/// across replicas.
/// If is false, registration of
/// the identity server fails with an explanatory exception.
///
/// Production deployments must configure a stable pepper distributed via a secret store.
///
public string? RecoveryCodePepper { get; set; }
///
/// Earlier values of , kept so that a rotation does not void what was issued
/// under them: MFA recovery codes and the open password-reset, e-mail-verification and change-e-mail links.
/// Each value is base64 of 16 or more bytes and differs from the current pepper; a bad value fails the start.
/// New hashes always use ; these are only tried on verification. Every stored
/// hash records the id of its pepper, so a record is checked against that one pepper; records written before
/// 4.8.0 carry no id and are tried with the current pepper, then with these in order.
///
/// While the list is not empty the leader logs once after start and then daily, per previous pepper id, how many
/// users still hold recovery codes under it. A value can be removed when its count is 0 and the longest link
/// lifetime has passed since the rotation. Set the same values on every node at once. Default: none.
///
///
public string[]? RecoveryCodePreviousPeppers { get; set; }
///
/// PBKDF2-HMAC-SHA256 work factor (iterations) used when hashing newly generated recovery
/// codes. OWASP guidance (2024) recommends ≥ 600 000 for SHA-256. Existing stored hashes
/// continue to verify against the iteration count embedded in their format string.
/// Default: 600 000.
///
public int RecoveryCodePbkdf2Iterations { get; set; } = 600_000;
///
/// Lifetime of the session cookie. After this the user must log in again.
/// Default: 8 hours.
///
public TimeSpan SessionCookieLifetime { get; set; } = TimeSpan.FromHours(8);
// ── UI Customization ──
///
/// Title shown on the login page. Default: Sign In.
///
public string LoginTitle { get; set; } = "Sign In";
///
/// URL of a logo image shown above the login form. When null, no logo is rendered.
///
public string? LogoUrl { get; set; }
///
/// Primary color for buttons and accents (CSS color value). Default: #2563eb.
///
public string PrimaryColor { get; set; } = "#2563eb";
///
/// Primary color hover state. Default: #1d4ed8.
///
public string PrimaryColorHover { get; set; } = "#1d4ed8";
///
/// Extra CSS injected into every identity page (login, consent, logout).
///
public string? CustomCss { get; set; }
// ── SCIM 2.0 (RFC 7643/7644) ──
// Note: the on/off toggles moved to .EnableScim / EnableScimBulk.
///
/// Required OAuth scope for SCIM API access.
/// Clients must request this scope to call /scim/v2/* endpoints.
/// Default: scim.
///
public string ScimScope { get; set; } = "scim";
///
/// H1: maximum number of operations accepted in one SCIM Bulk request. Mirrors the
/// bulk.maxOperations field advertised in /scim/v2/ServiceProviderConfig.
/// Default: 1000.
///
public int ScimBulkMaxOperations { get; set; } = 1000;
///
/// H1: maximum payload size (bytes) accepted in one SCIM Bulk request. Mirrors the
/// bulk.maxPayloadSize field advertised in /scim/v2/ServiceProviderConfig.
/// Default: 1 MiB.
///
public int ScimBulkMaxPayloadSize { get; set; } = 1_048_576;
// ── Federation (OIDC / external IdP) ──
// Note: the on/off toggle moved to .EnableFederation.
/// Configured external OIDC federation providers.
public List FederationProviders { get; set; } = [];
// ── C2: Trusted reverse-proxy whitelist for client-IP resolution ──
///
/// Whitelist of trusted reverse-proxy IPs / networks consulted by
/// when sanitizing the
/// redbHttp.RemoteAddress exchange header before per-IP throttling (C1) sees it.
///
/// Secure-by-default: is false,
/// so X-Forwarded-For / Forwarded headers are ignored entirely and the socket
/// IP is always used. To enable forwarded-IP resolution behind a reverse proxy, set
/// TrustForwardedFor=true AND populate
/// or with the proxy address(es).
///
///
public ReverseProxyOptions ReverseProxies { get; set; } = new();
// ── C1: Per-IP / per-(IP+username) rate limiting ──
///
/// Configuration for the C1 rate-limit guard sitting in front of /connect/token,
/// /login and the MFA endpoints. See for trust model
/// and backend selection. Disabled by default; enable + select a backend to activate.
///
public RateLimitOptions RateLimit { get; set; } = new();
///
/// Length / size limits applied by management & registration processors when validating
/// inbound payloads. Defaults match historical hardcoded values; tune per deployment.
///
public IdentityValidationOptions Validation { get; set; } = new();
///
/// Hardening knobs for the OIDC federation state parameter (anti-replay, browser-binding, TTL).
///
public FederationStateOptions FederationState { get; set; } = new();
///
/// N-4 (Session C): outbound SMTP transport used by the transactional e-mail channel
/// (password recovery, MFA delivery, account notices). Disabled by default — a host
/// that does not enable SMTP must register an alternative IEmailNotificationChannel
/// (e.g. the in-memory channel used by integration tests, or a SendGrid adapter).
///
public SmtpOptions Smtp { get; set; } = new();
///
/// N-4 (Session C): tunables for the anonymous password-recovery flow (TTL etc.).
///
public PasswordRecoveryOptions PasswordRecovery { get; set; } = new();
///
/// N-4 (Session C, sub-step N4-6): tunables + feature gate for the e-mail-verification
/// flow. Disabled by default — opt-in until a host wires an
/// and configures per-client
/// ApplicationProps.EmailVerifyUris.
///
public EmailVerificationOptions EmailVerification { get; set; } = new();
///
/// N-4 (Session E, sub-step N4-7): tunables + feature gate for the strict
/// verify-then-commit change-of-e-mail flow. Disabled by default — opt-in until a
/// host wires an and configures
/// per-client ApplicationProps.ChangeEmailUris. When this option is enabled
/// hosts SHOULD also set to
/// true so the soft /me/profile path stops accepting an unverified
/// e-mail update and forces all e-mail changes through the strict flow.
///
public ChangeEmailOptions ChangeEmail { get; set; } = new();
///
/// N-3 (sub-step N3-7): feature gate + tunables for the anonymous self-service
/// account-registration flow. Disabled by default — corporate identity deployments
/// that provision users via admin / SCIM should leave this off.
///
public RegistrationOptions Registration { get; set; } = new();
///
/// C9 — cookie security defaults: __Host-/__Secure- name prefixes,
/// SameSite mode, etc. All cookies emitted by Identity inherit
/// HttpOnly and Secure (when issuer is https) automatically;
/// these knobs cover the spec-defined extras.
///
public IdentityCookieOptions Cookies { get; set; } = new();
///
/// C10 — at-rest encryption for the ASP.NET DataProtection key-ring stored in redb PROPS.
/// Without an encryptor configured, key-ring elements live in the database in plaintext;
/// a database leak then compromises every Identity-issued cookie / federation state /
/// MFA setup token.
///
public DataProtectionOptions DataProtection { get; set; } = new();
///
/// E2 — Idempotency-Key response cache for admin/SCIM mutations. See
/// for behaviour and storage details.
///
public IdempotencyOptions Idempotency { get; set; } = new();
///
/// C12 — password hashing algorithm + parameters for newly stored passwords, and
/// auto-rehash of legacy formats on successful login. See
/// .
///
public PasswordHashingOptions PasswordHashing { get; set; } = new();
///
/// H10 — server-side password policy: length, composition, history reuse,
/// expiration, breach screening. Defaults are STRICT (NIST SP 800-63B / OWASP
/// ASVS 4.0.3 §2.1) so a freshly bootstrapped deployment is secure-by-default;
/// every knob is overridable via the standard 5-layer config pipeline.
///
public PasswordPolicyOptions PasswordPolicy { get; set; } = new();
///
/// B1 — emergency local-admin bootstrap endpoint (POST /internal/bootstrap-admin).
/// On a brand-new deployment with an empty identity database (no users, groups, OIDC
/// clients) there is no way to log in — even client_credentials requires a
/// pre-registered confidential client. This endpoint atomically creates the first
/// admin user, the identity-admins group, the identity-web OIDC client
/// and a SystemFlag(name=bootstrap_completed) sentinel; subsequent calls
/// return 410 Gone. Disabled by default — set
/// +
/// (env-only!) to enable.
///
public BootstrapOptions Bootstrap { get; set; } = new();
///
/// Default-credential seeder for the well-known admin user that ships
/// in the base redb SQL seed (_users.id = 1, login = "admin",
/// empty password). On host startup, SeedAdminPasswordHostedService
/// looks up the user by ; if found and its
/// stored password is empty or still the default admin (a Tsak dashboard on the
/// same database writes admin/admin first), is
/// hashed via the configured and persisted, so a fresh
/// install supports admin/admin sign-in out-of-the-box. Logs a loud
/// startup WARNING when the password is the default admin.
///
public SeedAdminOptions SeedAdmin { get; set; } = new();
///
/// Default OIDC-client seeder that ensures the canonical Web Console client
/// () exists in the OpenIddict
/// application store on host startup. Sister to —
/// fully idempotent (no-op when the client already exists), opinionated
/// defaults wired for the bundled redb.Identity.Web BFF running on
/// https://localhost:7000. For non-default deployments override
/// and
/// via
/// context.json / env-vars.
///
public SeedWebClientOptions SeedWebClient { get; set; } = new();
///
/// W6-0 — default seeder for the client_credentials service-account
/// used by a polling Web BFF to push/poll the backchannel revoked-sids list.
/// Sister to ; disabled by default so it does not
/// inflate the OpenIddict client store on hosts that don't run the Web BFF.
///
public SeedBackchannelClientOptions SeedBackchannelClient { get; set; } = new();
}
///
/// Options for the default-admin password seeder that ensures the well-known
/// admin user from the base redb SQL seed has a usable password on a fresh
/// install. Idempotent: only updates when the stored password is empty or still the
/// default admin; a password the operator changed is never overwritten.
///
public sealed class SeedAdminOptions
{
/// Default plaintext password used when no override is supplied.
public const string DefaultPassword = "admin";
/// Master switch; default true. Set to false to disable seeding entirely.
public bool Enabled { get; set; } = true;
/// Login of the seed admin user; default admin.
public string Login { get; set; } = "admin";
///
/// Plain-text password to hash and store when the user has no password. Default
/// admin. Convenience for fresh deployments only — change this
/// (or rotate the password via the management API) before exposing the host to
/// untrusted networks. Leaving the default produces a startup WARNING.
///
public string Password { get; set; } = DefaultPassword;
}
///
/// Options for the default OIDC-client seeder that ensures the canonical
/// identity-web client exists in the OpenIddict application store on a
/// fresh install. Idempotent: skips when a client with the same
/// already exists. Defaults are wired for the bundled
/// redb.Identity.Web BFF.
///
public sealed class SeedWebClientOptions
{
/// Master switch; default true. Set to false to disable seeding entirely.
public bool Enabled { get; set; } = true;
/// OIDC client identifier; default identity-web (matches Web BFF appsettings).
public string ClientId { get; set; } = "identity-web";
///
/// Optional client secret. When empty the client is registered as a Public
/// client (PKCE-only). The bundled redb.Identity.Web BFF runs as a
/// public client by default — leave this empty unless you flip Web to
/// confidential mode.
///
public string ClientSecret { get; set; } = string.Empty;
/// Display name shown on the consent page; default "Identity Web Console".
public string DisplayName { get; set; } = "Identity Web Console";
///
/// Allowed redirect URIs (post-authorization callback). Default points at
/// https://localhost:7000/signin-oidc (Web BFF dev binding).
///
public List RedirectUris { get; set; } = new()
{
"https://localhost:7000/signin-oidc",
};
///
/// Allowed post-logout redirect URIs. Default points at
/// https://localhost:7000/signout-callback-oidc.
///
public List PostLogoutRedirectUris { get; set; } = new()
{
"https://localhost:7000/signout-callback-oidc",
};
///
/// Allowed scopes the client may request. Default mirrors the Web BFF
/// requested scopes (openid, profile, email, roles, offline_access,
/// identity:manage, identity:account). Standard OIDC scopes are always permitted
/// regardless of this list — entries here additionally grant non-standard scopes via
/// Permissions.Prefixes.Scope. identity:account is included so the
/// BFF can call self-service /me/* endpoints (e.g. native consent grant)
/// on behalf of the signed-in user without further deployment configuration.
///
public List Scopes { get; set; } = new()
{
"openid", "profile", "email", "roles", "offline_access", "identity:manage", "identity:account",
};
}
///
/// Options for the W6-0 backchannel service-account seeder. Ensures a confidential
/// client_credentials OpenIddict application exists so a polling Web BFF
/// can push and read revoked-sids without holding an end-user token. Idempotent:
/// skipped when an application with the same already exists.
///
public sealed class SeedBackchannelClientOptions
{
/// Master switch. Default false — opt-in per deployment.
public bool Enabled { get; set; } = false;
/// Client identifier of the service account. Default identity-backchannel.
public string ClientId { get; set; } = "identity-backchannel";
///
/// Client secret. Must be non-empty when is true — the
/// seeder logs and skips when missing rather than registering a public client
/// (client_credentials requires a confidential client per RFC 6749 §4.4).
///
public string ClientSecret { get; set; } = string.Empty;
/// Display name shown in admin UI / logs.
public string DisplayName { get; set; } = "Identity Backchannel Service Account";
///
/// Scopes the service account is allowed to request. Default identity:manage
/// — sufficient to call /api/v1/identity/revoked-sids.
///
public List Scopes { get; set; } = new() { "identity:manage" };
}
///
/// B1 — emergency local-admin bootstrap: a one-shot internal endpoint
/// (POST /internal/bootstrap-admin). The secret MUST come from environment
/// (e.g. IDENTITY__BOOTSTRAP__SECRET) and never from context.json
/// (which is checked into source control).
///
public sealed class BootstrapOptions
{
///
/// Master switch. When false (default) the route is registered but
/// always returns 404 Not Found — operators can leave the option in
/// context.json permanently disabled and only flip it via env-var on
/// the very first deploy.
///
public bool Enabled { get; set; } = false;
///
/// Shared secret required in the X-Bootstrap-Secret header.
/// Compared with
/// so the comparison does not leak information through timing.
/// Must be at least 32 characters when is true
/// (validated at startup); env-only by convention.
///
public string? Secret { get; set; }
///
/// Name of the group that the freshly-created admin user joins. Should
/// match RedbIdentityOptions.ScopeRequiredGroups["identity:admin"]
/// so the new admin can immediately use the management scope. Default
/// identity-admins.
///
public string AdminGroupName { get; set; } = "identity-admins";
///
/// OAuth scope that the bootstrap admin needs in order to call the
/// management surface. Defaults to the conventional
/// identity:admin. The processor creates the scope (if absent),
/// the gating entry,
/// and a mapping
/// group() → scope().
///
public string AdminScope { get; set; } = "identity:admin";
///
/// ClientId issued for the canonical first-party admin web application.
/// Default identity-web.
///
public string WebClientId { get; set; } = "identity-web";
}
///
/// Server-side input-length limits used by Identity validation helpers.
/// All values default to the original hardcoded constants.
///
public sealed class IdentityValidationOptions
{
/// Max length for identifier-like fields (login, name, etc.). Default 128.
public int MaxIdentifierLength { get; set; } = 128;
/// Max length for free-form display names. Default 256.
public int MaxDisplayNameLength { get; set; } = 256;
/// Max length for free-form descriptions. Default 1024.
public int MaxDescriptionLength { get; set; } = 1024;
/// Minimum length for passwords / client secrets. Default 8.
public int MinPasswordLength { get; set; } = 8;
/// Maximum length for passwords / client secrets. Default 512.
public int MaxPasswordLength { get; set; } = 512;
///
/// Optional override for the identifier regex (logins, role names, etc.).
/// Default (when null/empty): ^[a-zA-Z0-9\-_.]+$.
/// Invalid patterns silently fall back to the default.
///
public string? IdentifierPattern { get; set; }
///
/// Optional override for the email regex.
/// Default (when null/empty): ^[^@\s]+@[^@\s]+\.[^@\s]+$.
///
public string? EmailPattern { get; set; }
///
/// Optional override for the phone-number regex.
/// Default (when null/empty): E.164 — ^\+[1-9]\d{1,14}$.
///
public string? PhonePattern { get; set; }
}
///
/// C6 — hardening for the encrypted federation state blob and the
/// surrounding callback ceremony.
///
public sealed class FederationStateOptions
{
///
/// Maximum lifetime of an encrypted state blob from issuance to redeem.
/// Default: 5 minutes (matches OIDC spec recommendation for short-lived
/// authorization-request artefacts).
///
public TimeSpan StateMaxAge { get; set; } = TimeSpan.FromMinutes(5);
///
/// When true (default), every state blob carries a unique jti
/// that is recorded in the nonce store on first use; subsequent presentations
/// with the same jti are rejected (one-time-use, RFC 6749 §10.12-style).
/// Disable only for testing.
///
public bool RequireOneTimeUse { get; set; } = true;
///
/// When true, the challenge processor mints a per-flow secret, hashes it
/// into the state blob, and the HTTP layer pins the secret to the user-agent via
/// a Secure HttpOnly SameSite=Lax cookie. The callback rejects the flow
/// if the cookie is absent or its hash mismatches. Default: false —
/// opt-in because non-HTTP callers (CLI / SPA without cookie jar) cannot satisfy
/// the binding contract. See .
///
public bool RequireBrowserBinding { get; set; } = false;
///
/// Name of the cookie that carries the per-flow browser-binding secret when
/// is enabled. Default: redb_fed_b.
///
public string BindingCookieName { get; set; } = "redb_fed_b";
///
/// Backend for the one-time-use nonce store. memory (default) is single-node;
/// redis is required for multi-instance Identity deployments to make the
/// guarantee cluster-global. See .
///
public string Backend { get; set; } = "memory";
///
/// Redis connection string for the nonce store. When null/empty and
/// = redis, falls back to ..
///
public string? RedisConnectionString { get; set; }
///
/// Key prefix used by the Redis nonce store. Default: redb:identity:fed:nonce:.
///
public string RedisKeyPrefix { get; set; } = "redb:identity:fed:nonce:";
}
///
/// C10 — DataProtection at-rest hardening.
/// Three variants are supported (in priority order if multiple are set):
///
/// Custom KMS via — caller supplies an
/// IXmlEncryptor wired to Vault / Azure Key Vault / AWS KMS / etc.
/// X.509 certificate via — thumbprint lookup in
/// the local store, or PFX path on disk. Cross-platform; preferred for cluster.
/// AES-GCM master key via — 32-byte key in base64.
/// Smallest deployments / single-node dev.
///
/// If is true AND
/// is false AND none of the above
/// is configured, AddRedbIdentityServer throws on startup.
/// Migration: existing plaintext key-ring entries stay readable
/// (ASP.NET DataProtection handles mixed plain+encrypted entries natively).
/// New keys written after enabling encryption are encrypted; rotation eventually
/// retires the plaintext entries.
///
public sealed class DataProtectionOptions
{
///
/// When true (default) and ephemeral keys are not allowed, startup fails
/// unless one of , , or
/// is configured.
///
public bool RequireAtRestEncryption { get; set; } = true;
///
/// 32-byte AES-256 key, base64-encoded. Used by the built-in
/// AES-GCM XML encryptor when no certificate or KMS hook is configured.
///
public string? MasterKey { get; set; }
///
/// X.509 certificate options. If
/// or is set, the certificate-based
/// encryptor is used. Takes precedence over .
///
public DataProtectionCertificateOptions Certificate { get; set; } = new();
///
/// Optional callback that returns a custom IXmlEncryptor. The
/// IServiceProvider argument is the application root provider — caller can resolve
/// any registered service. Takes precedence over and
/// . Use this hook for KMS-backed encryptors.
///
public Func? CustomEncryptorFactory { get; set; }
///
/// A file key ring directory to import into redb at startup, in addition to the ASP.NET Core default
/// directory of the process user. Up to 4.3 the key ring was written to the file system instead of
/// redb; set this when that ring was kept somewhere else (for example a volume mounted on a custom
/// path). Keys already in redb are skipped, so leaving it set is harmless.
///
public string? ImportKeysFromPath { get; set; }
///
/// True when at least one of the three variants is configured.
///
public bool HasEncryptorConfigured =>
CustomEncryptorFactory is not null
|| Certificate.IsConfigured
|| !string.IsNullOrWhiteSpace(MasterKey);
}
///
/// X.509 certificate selector for the DataProtection key-ring encryptor.
/// Either (local store lookup) or
/// (file on disk, optional password) must be set. If both are set, the PFX path wins.
///
public sealed class DataProtectionCertificateOptions
{
/// SHA-1 (or SHA-256) thumbprint of the certificate to look up. Case- and whitespace-insensitive.
public string? Thumbprint { get; set; }
/// Certificate store name when looking up by thumbprint. Default: My.
public string StoreName { get; set; } = "My";
///
/// Certificate store location. Default: CurrentUser. Use LocalMachine
/// when running as a service account that doesn't have a personal user store.
///
public string StoreLocation { get; set; } = "CurrentUser";
/// Path to a PFX/PKCS#12 file on disk. Mutually exclusive-ish with .
public string? PfxPath { get; set; }
/// Password for the PFX file. Leave null for password-less PFX.
public string? PfxPassword { get; set; }
/// True when at least one source is set (thumbprint or PFX path).
public bool IsConfigured =>
!string.IsNullOrWhiteSpace(Thumbprint) || !string.IsNullOrWhiteSpace(PfxPath);
}
Path: redb-identity/src/redb.Identity.Core/Configuration/RegistrationOptions.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/Configuration/RegistrationOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// N-3 (sub-step N3-7): tunables + feature gate for the self-service account
/// registration flow (direct-vm://identity-account-register +
/// POST /api/v1/identity/account/register).
///
/// Disabled by default — opt-in for deployments that want public sign-up; corporate
/// identity deployments that provision users via admin / SCIM should leave this off.
///
///
public sealed class RegistrationOptions
{
/// Master switch. When false the route is not built and the facade returns 404.
public bool Enabled { get; set; } = false;
///
/// When true and is also
/// enabled, the processor automatically dispatches an e-mail verification link after
/// account creation. The user's EmailVerified flag stays false until
/// the link is consumed. Defaults to true.
///
public bool SendVerifyEmail { get; set; } = true;
///
/// When true (default) the processor enforces e-mail uniqueness alongside
/// login uniqueness. Set to false only for deployments that explicitly allow
/// the same e-mail to back multiple accounts.
///
public bool RequireUniqueEmail { get; set; } = true;
}
Path: redb-identity/src/redb.Identity.Core/Configuration/ReverseProxyOptions.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/Configuration/ReverseProxyOptions.cs
----
using System.Net;
namespace redb.Identity.Core.Configuration;
///
/// C2 — Configuration for the trusted-reverse-proxy whitelist consulted by
/// .
///
///
/// Secure-by-default: with = false (the default),
/// the resolver ignores all X-Forwarded-For / Forwarded headers and the
/// socket IP carried by redbHttp.RemoteAddress is propagated unchanged. This means
/// per-IP throttling (C1) sees only the immediate TCP peer — correct when the service is
/// exposed directly. Enable forwarded-IP resolution only when the service sits behind a
/// trusted reverse proxy whose IPs are listed here; otherwise an attacker can spoof
/// X-Forwarded-For and bypass per-IP rate limits.
///
public sealed class ReverseProxyOptions
{
///
/// When true, the resolver consults the X-Forwarded-For header on requests
/// arriving from a peer in / , walks
/// the chain right-to-left skipping any further trusted hops, and uses the first untrusted
/// IP as the client address. When false (default), the socket IP is used as-is.
///
public bool TrustForwardedFor { get; set; }
/// Individual IP addresses of trusted reverse proxies.
public List KnownProxies { get; set; } = new();
/// CIDR networks of trusted reverse proxies.
public List KnownNetworks { get; set; } = new();
}
Path: redb-identity/src/redb.Identity.Core/Configuration/SmtpOptions.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/Configuration/SmtpOptions.cs
----
namespace redb.Identity.Core.Configuration;
///
/// N-4 (Session C): SMTP transport configuration consumed by the e-mail dispatch route
/// (direct-vm://identity-email-send) and the SmtpEmailNotificationChannel.
/// Empty / disabled by default — a host either enables SMTP here or registers an
/// alternative IEmailNotificationChannel implementation (e.g. SendGrid, in-memory
/// channel for tests, or a noop channel that drops messages).
///
public sealed class SmtpOptions
{
/// Master switch. When false the route is not built and no SMTP channel is registered.
public bool Enabled { get; set; } = false;
/// SMTP server host (e.g. smtp.gmail.com, 127.0.0.1).
public string? Host { get; set; }
/// SMTP server port. Common values: 25 (plain), 465 (Ssl), 587 (StartTls), 3025 (greenmail no-auth).
public int Port { get; set; } = 25;
///
/// Security mode passed straight to the redb.Route.Mail builder
/// (None, StartTls, Ssl, Auto). Defaults to None;
/// production deployments should set StartTls or Ssl.
///
public string Security { get; set; } = "None";
/// Optional username (omit for unauthenticated greenmail-style relays).
public string? Username { get; set; }
/// Optional password (omit for unauthenticated greenmail-style relays).
public string? Password { get; set; }
/// Envelope From address used when the channel does not supply one per message.
public string FromAddress { get; set; } = "noreply@redb.local";
/// Skip TLS certificate validation. Test / dev only — never enable in production.
public bool SkipCertificateValidation { get; set; } = false;
}
Path: redb-identity/src/redb.Identity.Core/DataProtection/CertificateLoader.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/DataProtection/CertificateLoader.cs
----
using System.Security.Cryptography.X509Certificates;
using redb.Identity.Core.Configuration;
namespace redb.Identity.Core.DataProtection;
///
/// C10 — loads an X.509 certificate from configuration. Supports two sources:
///
/// PFX file on disk via
/// (+ optional ).
/// Local certificate store by thumbprint via
/// in
/// /
/// .
///
/// PFX-on-disk wins when both are set.
///
internal static class CertificateLoader
{
public static X509Certificate2 Load(DataProtectionCertificateOptions options)
{
ArgumentNullException.ThrowIfNull(options);
if (!string.IsNullOrWhiteSpace(options.PfxPath))
return LoadFromPfx(options.PfxPath!, options.PfxPassword);
if (!string.IsNullOrWhiteSpace(options.Thumbprint))
return LoadFromStore(options.Thumbprint!, options.StoreName, options.StoreLocation);
throw new InvalidOperationException(
"DataProtection.Certificate is not configured: set Thumbprint or PfxPath.");
}
private static X509Certificate2 LoadFromPfx(string path, string? password)
{
if (!File.Exists(path))
throw new InvalidOperationException(
$"DataProtection.Certificate.PfxPath '{path}' does not exist.");
// X509KeyStorageFlags.EphemeralKeySet keeps the private key in memory only — avoids
// writing key material to %APPDATA%/.dotnet on every load (Linux/macOS especially).
// MachineKeySet is not used because Identity may run as a service account that
// doesn't have write access to the machine key store.
try
{
return X509CertificateLoader.LoadPkcs12FromFile(
path,
password,
X509KeyStorageFlags.EphemeralKeySet);
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Failed to load PFX from '{path}'. Verify the file is a valid PKCS#12 archive " +
"and the password (if any) is correct.", ex);
}
}
private static X509Certificate2 LoadFromStore(string thumbprint, string storeName, string storeLocation)
{
// Thumbprints are typically pasted from MMC with spaces / mixed case — normalise.
var normalised = new string(thumbprint.Where(char.IsLetterOrDigit).ToArray()).ToUpperInvariant();
if (!Enum.TryParse(storeLocation, ignoreCase: true, out var loc))
throw new InvalidOperationException(
$"DataProtection.Certificate.StoreLocation '{storeLocation}' is not a valid X509 StoreLocation. " +
"Use 'CurrentUser' or 'LocalMachine'.");
StoreName parsedStoreName;
if (Enum.TryParse(storeName, ignoreCase: true, out var sn))
{
parsedStoreName = sn;
using var store = new X509Store(parsedStoreName, loc);
return FindByThumbprint(store, normalised, storeName, storeLocation);
}
// Custom store name (e.g. operator's own store) — X509Store ctor takes the string as-is.
using var customStore = new X509Store(storeName, loc);
return FindByThumbprint(customStore, normalised, storeName, storeLocation);
}
private static X509Certificate2 FindByThumbprint(
X509Store store, string normalisedThumbprint, string storeName, string storeLocation)
{
store.Open(OpenFlags.ReadOnly);
// validOnly=false: an expired cert is still useful for DECRYPTING old key-ring entries
// (the new ones will be encrypted with whatever cert is configured next).
var matches = store.Certificates.Find(
X509FindType.FindByThumbprint, normalisedThumbprint, validOnly: false);
if (matches.Count == 0)
throw new InvalidOperationException(
$"No certificate found with thumbprint '{normalisedThumbprint}' " +
$"in {storeLocation}\\{storeName}.");
var cert = matches[0];
if (!cert.HasPrivateKey)
throw new InvalidOperationException(
$"Certificate '{normalisedThumbprint}' in {storeLocation}\\{storeName} " +
"does not have an accessible private key — DataProtection key-ring decryption " +
"would fail. Grant the service account read access to the private key, or " +
"supply a PFX file via DataProtection.Certificate.PfxPath.");
return cert;
}
}
Path: redb-identity/src/redb.Identity.Core/DataProtection/RedbAesGcmXmlEncryptor.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/DataProtection/RedbAesGcmXmlEncryptor.cs
----
using System.Security.Cryptography;
using System.Xml.Linq;
using Microsoft.AspNetCore.DataProtection.XmlEncryption;
namespace redb.Identity.Core.DataProtection;
///
/// C10 — AES-GCM XML encryptor for the DataProtection key-ring.
///
/// Encrypts each key-ring with AES-256-GCM using a 32-byte master
/// key supplied by the caller (typically from RedbIdentityOptions.DataProtection.MasterKey).
/// The decryptor type recorded in the descriptor is ;
/// ASP.NET DataProtection instantiates it via IActivator on key load, so the decryptor
/// pulls the master key from DI through the same singleton.
///
///
/// Wire format (single base64 token):
/// [12-byte nonce][16-byte tag][ciphertext].
///
///
internal sealed class RedbAesGcmXmlEncryptor : IXmlEncryptor
{
internal const string AlgorithmId = "aes-gcm-256";
internal const int NonceSize = 12;
internal const int TagSize = 16;
private readonly RedbMasterKeyProvider _keyProvider;
public RedbAesGcmXmlEncryptor(RedbMasterKeyProvider keyProvider)
{
ArgumentNullException.ThrowIfNull(keyProvider);
_keyProvider = keyProvider;
}
public EncryptedXmlInfo Encrypt(XElement plaintextElement)
{
ArgumentNullException.ThrowIfNull(plaintextElement);
var plaintextBytes = System.Text.Encoding.UTF8.GetBytes(
plaintextElement.ToString(SaveOptions.DisableFormatting));
var nonce = RandomNumberGenerator.GetBytes(NonceSize);
var ciphertext = new byte[plaintextBytes.Length];
var tag = new byte[TagSize];
using (var aes = new AesGcm(_keyProvider.Key, TagSize))
{
aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);
}
// Pack nonce | tag | ciphertext into a single base64 blob — keeps the XML compact
// and the decryptor doesn't need to juggle separate child elements.
var blob = new byte[NonceSize + TagSize + ciphertext.Length];
Buffer.BlockCopy(nonce, 0, blob, 0, NonceSize);
Buffer.BlockCopy(tag, 0, blob, NonceSize, TagSize);
Buffer.BlockCopy(ciphertext, 0, blob, NonceSize + TagSize, ciphertext.Length);
var encrypted = new XElement("encryptedKey",
new XElement("encryptionAlgorithm", AlgorithmId),
new XElement("value", Convert.ToBase64String(blob)));
return new EncryptedXmlInfo(encrypted, typeof(RedbAesGcmXmlDecryptor));
}
}
///
/// Companion decryptor for .
/// Resolved by ASP.NET DataProtection's IActivator at key-load time.
///
internal sealed class RedbAesGcmXmlDecryptor : IXmlDecryptor
{
private readonly RedbMasterKeyProvider _keyProvider;
public RedbAesGcmXmlDecryptor(IServiceProvider services)
{
ArgumentNullException.ThrowIfNull(services);
_keyProvider = (RedbMasterKeyProvider?)services.GetService(typeof(RedbMasterKeyProvider))
?? throw new InvalidOperationException(
"RedbAesGcmXmlDecryptor was activated but no RedbMasterKeyProvider is registered. " +
"This indicates the key-ring contains entries encrypted under the AES-GCM master key " +
"but the master key is no longer configured. Restore RedbIdentityOptions.DataProtection.MasterKey.");
}
public XElement Decrypt(XElement encryptedElement)
{
ArgumentNullException.ThrowIfNull(encryptedElement);
var algorithm = encryptedElement.Element("encryptionAlgorithm")?.Value;
if (!string.Equals(algorithm, RedbAesGcmXmlEncryptor.AlgorithmId, StringComparison.Ordinal))
throw new InvalidOperationException(
$"Unsupported algorithm '{algorithm}' for {nameof(RedbAesGcmXmlDecryptor)}; expected '{RedbAesGcmXmlEncryptor.AlgorithmId}'.");
var b64 = encryptedElement.Element("value")?.Value
?? throw new InvalidOperationException("Encrypted XML element is missing child.");
var blob = Convert.FromBase64String(b64);
if (blob.Length < RedbAesGcmXmlEncryptor.NonceSize + RedbAesGcmXmlEncryptor.TagSize)
throw new InvalidOperationException("Encrypted blob is too short to contain nonce + tag.");
var nonce = new byte[RedbAesGcmXmlEncryptor.NonceSize];
var tag = new byte[RedbAesGcmXmlEncryptor.TagSize];
var ciphertext = new byte[blob.Length - RedbAesGcmXmlEncryptor.NonceSize - RedbAesGcmXmlEncryptor.TagSize];
Buffer.BlockCopy(blob, 0, nonce, 0, RedbAesGcmXmlEncryptor.NonceSize);
Buffer.BlockCopy(blob, RedbAesGcmXmlEncryptor.NonceSize, tag, 0, RedbAesGcmXmlEncryptor.TagSize);
Buffer.BlockCopy(blob, RedbAesGcmXmlEncryptor.NonceSize + RedbAesGcmXmlEncryptor.TagSize,
ciphertext, 0, ciphertext.Length);
var plaintext = new byte[ciphertext.Length];
using (var aes = new AesGcm(_keyProvider.Key, RedbAesGcmXmlEncryptor.TagSize))
{
aes.Decrypt(nonce, ciphertext, tag, plaintext);
}
return XElement.Parse(System.Text.Encoding.UTF8.GetString(plaintext));
}
}
///
/// Holds the raw 32-byte AES-256 master key. Singleton; the byte array is owned by this
/// instance and is not exposed via mutable accessors.
///
internal sealed class RedbMasterKeyProvider
{
private readonly byte[] _key;
public RedbMasterKeyProvider(byte[] key)
{
ArgumentNullException.ThrowIfNull(key);
if (key.Length != 32)
throw new ArgumentException("AES-256 master key must be exactly 32 bytes.", nameof(key));
_key = (byte[])key.Clone();
}
/// Direct access to the raw key bytes. Do not mutate.
public byte[] Key => _key;
}
Path: redb-identity/src/redb.Identity.Core/DataProtection/XmlRepositoryRefreshProcessor.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/DataProtection/XmlRepositoryRefreshProcessor.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Identity.DataProtection;
using redb.Route.Abstractions;
using redb.Identity.Core.Routes;
namespace redb.Identity.Core.DataProtection;
///
/// Reloads the DataProtection XML key-ring snapshot from PROPS storage into
/// . Fired per-tick by a timer:// route
/// (see ). Runs on every replica —
/// this is intentionally NOT cluster-leader-only because each node maintains its own
/// in-process snapshot and must pick up keys rotated by other replicas.
///
internal sealed class XmlRepositoryRefreshProcessor : IProcessor
{
private readonly IServiceProvider _sp;
public XmlRepositoryRefreshProcessor(IServiceProvider sp)
{
ArgumentNullException.ThrowIfNull(sp);
_sp = sp;
}
public async Task Process(IExchange exchange, CancellationToken ct)
{
await using var scope = _sp.CreateAsyncScope();
var repo = scope.ServiceProvider.GetRequiredService();
var redb = scope.ServiceProvider.GetRequiredService();
var logger = scope.ServiceProvider
.GetRequiredService()
.CreateLogger();
var count = await repo.ReloadAsync(redb, ct).ConfigureAwait(false);
logger.LogDebug(
"redb.Identity: DataProtection key-ring snapshot refreshed ({Count} keys)",
count);
}
}
Path: redb-identity/src/redb.Identity.Core/EmailVerification/IEmailVerificationTokenStore.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Core/EmailVerification/IEmailVerificationTokenStore.cs
----
using System;
using System.Threading;
using System.Threading.Tasks;
namespace redb.Identity.Core.EmailVerification;
///
/// N-4 (Session C, sub-step N4-6): server-side e-mail-verification token store. Mirror of
/// with one extra binding — the
/// token is tied to the specific e-mail value snapshot captured at issue time, so a
/// stale link cannot vouch for an address the user has since changed.
///
public interface IEmailVerificationTokenStore
{
///
/// Issues a new verification token. Generates a 32-byte CSPRNG secret
/// (base64url-encoded), persists its peppered SHA-256 hash + the bound
/// snapshot, and returns the jti + plaintext token so
/// the caller can embed both into the verify URL.
///
/// User the verification is bound to.
///
/// Lower-cased snapshot of the user's e-mail at issue time. Confirm rejects the token
/// when the user's current e-mail no longer matches this value (double-change race).
///
///
/// Caller-supplied landing URL captured at issue time. Recorded for audit; the
/// whitelist check is enforced by the issuing processor against
/// ApplicationProps.EmailVerifyUris.
///
/// Time-to-live for this token. Typically 24 hours.
Task IssueAsync(
long userId,
string email,
string callerVerifyUrl,
TimeSpan ttl,
CancellationToken ct = default);
///
/// Verifies and atomically consumes a verification token keyed by .
/// On success the row is marked Consumed and the bound UserId + e-mail
/// snapshot are returned so the caller can apply the e-mail-match guard before
/// flipping UserProps.EmailVerified.
///
Task VerifyAndConsumeAsync(
Guid jti,
string token,
CancellationToken ct = default);
}
/// Result of .
public readonly record struct EmailVerificationIssueResult(
Guid Jti,
string PlaintextToken,
DateTimeOffset ExpiresAt);
/// Result of .
/// Whether the token verified AND the row was successfully consumed.
/// Owner user id when is true; otherwise 0.
/// Lower-cased e-mail snapshot bound at issue time; empty when is false.
/// Diagnostic reason; values: ok, not_found, expired, already_consumed, bad_token.
public readonly record struct EmailVerificationVerifyResult(
bool Success,
long UserId,
string Email,
string Reason);
Path: redb-identity/src/redb.Identity.Core/EmailVerification/RedbEmailVerificationTokenStore.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Core/EmailVerification/RedbEmailVerificationTokenStore.cs
----
using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
namespace redb.Identity.Core.EmailVerification;
///
/// N-4 (Session C, sub-step N4-6): redb-backed
/// . Direct mirror of
/// RedbPasswordResetTokenStore with one extra field on the persisted props
/// () and one extra field on the verify
/// result so the caller can guard against the double-change race.
///
public sealed class RedbEmailVerificationTokenStore : IEmailVerificationTokenStore
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly RecoveryCodePepperProvider _pepperProvider;
private readonly ILogger _logger;
private readonly TimeProvider _timeProvider;
public RedbEmailVerificationTokenStore(
IServiceScopeFactory scopeFactory,
RecoveryCodePepperProvider pepperProvider,
ILogger logger,
TimeProvider? timeProvider = null)
{
_scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
_pepperProvider = pepperProvider ?? throw new ArgumentNullException(nameof(pepperProvider));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_timeProvider = timeProvider ?? TimeProvider.System;
}
///
public async Task IssueAsync(
long userId,
string email,
string callerVerifyUrl,
TimeSpan ttl,
CancellationToken ct = default)
{
if (userId <= 0) throw new ArgumentOutOfRangeException(nameof(userId));
if (string.IsNullOrWhiteSpace(email)) throw new ArgumentException("email is required", nameof(email));
if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl));
var jti = Guid.NewGuid();
var token = GenerateToken();
var now = _timeProvider.GetUtcNow();
var expires = now + ttl;
var hash = RecoveryCodePepperProvider.PepperedSha256Hex(_pepperProvider.Pepper, token);
await using var scope = _scopeFactory.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
var obj = new RedbObject(new EmailVerificationTokenProps
{
Jti = jti.ToString("N"),
UserId = userId,
Email = email.Trim().ToLowerInvariant(),
TokenHash = hash,
PepperId = _pepperProvider.PepperId,
IssuedAt = now,
ExpiresAt = expires,
Consumed = false,
Attempts = 0,
CallerVerifyUrl = callerVerifyUrl ?? string.Empty,
});
obj.name = jti.ToString("N");
await redb.SaveAsync(obj).ConfigureAwait(false);
return new EmailVerificationIssueResult(jti, token, expires);
}
///
public async Task VerifyAndConsumeAsync(
Guid jti,
string token,
CancellationToken ct = default)
{
if (jti == Guid.Empty) return new EmailVerificationVerifyResult(false, 0, string.Empty, "not_found");
if (string.IsNullOrEmpty(token)) return new EmailVerificationVerifyResult(false, 0, string.Empty, "bad_token");
await using var scope = _scopeFactory.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
var key = jti.ToString("N");
await using var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false);
var row = await redb.Query()
.Where(o => o.Jti == key)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (row is null)
{
await tx.RollbackAsync().ConfigureAwait(false);
return new EmailVerificationVerifyResult(false, 0, string.Empty, "not_found");
}
if (row.key.HasValue)
await redb.LockForUpdateAsync(row.key.Value).ConfigureAwait(false);
var p = row.Props;
var now = _timeProvider.GetUtcNow();
if (p.Consumed)
{
await tx.CommitAsync().ConfigureAwait(false);
return new EmailVerificationVerifyResult(false, 0, string.Empty, "already_consumed");
}
if (p.ExpiresAt < now)
{
await tx.CommitAsync().ConfigureAwait(false);
return new EmailVerificationVerifyResult(false, 0, string.Empty, "expired");
}
if (_pepperProvider.PeppersFor(p.PepperId).Count == 0)
_logger.LogWarning("The token was hashed with pepper {PepperId}, which is no longer configured.", p.PepperId);
var ok = _pepperProvider.MatchesTokenHash(token.Trim(), p.TokenHash, p.PepperId);
p.Attempts++;
if (ok)
{
p.Consumed = true;
}
try
{
await redb.SaveAsync(row).ConfigureAwait(false);
await tx.CommitAsync().ConfigureAwait(false);
}
catch
{
await tx.RollbackAsync().ConfigureAwait(false);
throw;
}
return ok
? new EmailVerificationVerifyResult(true, p.UserId, p.Email, "ok")
: new EmailVerificationVerifyResult(false, 0, string.Empty, "bad_token");
}
private static string GenerateToken()
{
Span buf = stackalloc byte[32];
RandomNumberGenerator.Fill(buf);
return Base64UrlEncode(buf);
}
private static string Base64UrlEncode(ReadOnlySpan bytes)
{
var s = Convert.ToBase64String(bytes);
return s.TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
}
Path: redb-identity/src/redb.Identity.Core/Events/DeliveryBacklog.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/Events/DeliveryBacklog.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Query;
namespace redb.Identity.Core.Events;
///
/// The backlog of the delivery outbox (pending rows, age of the oldest), read from the database at most
/// once per and shared by the health check and the metric gauges
/// identity.delivery.pending and identity.delivery.oldest_pending_age. Every node reads the
/// same table, so every node reports the same backlog, whichever of them runs the worker.
///
public sealed class DeliveryBacklog
{
/// How long one reading is reused.
public static readonly TimeSpan MaxAge = TimeSpan.FromSeconds(15);
private readonly IServiceScopeFactory _scopes;
private readonly TimeProvider _time;
private readonly ILogger _logger;
private readonly SemaphoreSlim _refresh = new(1, 1);
private OutboxStats? _current;
private DateTimeOffset _readAt = DateTimeOffset.MinValue;
public DeliveryBacklog(IServiceScopeFactory scopes, TimeProvider time, ILogger logger)
{
_scopes = scopes;
_time = time;
_logger = logger;
}
/// The last reading, or null before the first one. Starts a new reading in the background when stale.
public OutboxStats? Current
{
get
{
if (Stale) _ = Task.Run(() => GetAsync(CancellationToken.None));
return _current;
}
}
/// A reading no older than ; null when the table cannot be read.
public async Task GetAsync(CancellationToken ct)
{
if (!Stale) return _current;
await _refresh.WaitAsync(ct).ConfigureAwait(false);
try
{
if (!Stale) return _current;
await using var scope = _scopes.CreateAsyncScope();
var store = new IdentityEventStore(
scope.ServiceProvider.GetRequiredService(),
scope.ServiceProvider.GetRequiredService());
_current = await store.StatsAsync(ct).ConfigureAwait(false);
_readAt = _time.GetUtcNow();
return _current;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Delivery backlog: the outbox could not be read.");
return null;
}
finally
{
_refresh.Release();
}
}
private bool Stale => _time.GetUtcNow() - _readAt > MaxAge;
}
Path: redb-identity/src/redb.Identity.Core/Events/IdentityEventStore.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/Events/IdentityEventStore.cs
----
using System.Collections.Concurrent;
using System.Text.Json.Serialization;
using redb.Core;
using redb.Core.Query;
namespace redb.Identity.Core.Events;
///
/// The flat SQL of the event pipeline: the audit row and the delivery outbox
/// (identity_delivery_outbox). No statement lives in a processor; each one is a section of an
/// embedded per-dialect resource (sql/events/{pg,mssql,sqlite}.sql), run through redb's
/// so it shares the connection and transaction handling of redb.
///
/// Every time the outbox stores or compares comes from the database clock, inside the statement: two
/// nodes whose clocks disagree still agree on who holds a lease and on what is due.
///
///
public sealed class IdentityEventStore
{
private static readonly ConcurrentDictionary> Statements = new();
private readonly IRedbService _redb;
private readonly IReadOnlyDictionary _sql;
public IdentityEventStore(IRedbService redb, ISqlDialect dialect)
{
_redb = redb ?? throw new ArgumentNullException(nameof(redb));
ArgumentNullException.ThrowIfNull(dialect);
_sql = StatementsFor(dialect.ProviderName);
}
/// Creates the outbox table and its indexes when they are missing; idempotent.
public Task EnsureOutboxAsync(CancellationToken ct = default)
=> _redb.Context.ExecuteAsync(_sql["create_outbox"], Array.Empty