Class SrpAuthenticatorCore<TConnection>
- Namespace
- FishMMO.Auth.Implementation
- Assembly
- FishMMO-ServerAuth.dll
Engine-independent SRP-6a authenticator core for LoginServer use. Extends BaseAuthenticatorCore<TConnection> with bounded-channel SRP verify/proof workers, TOTP two-factor authentication, kick-request tracking, and per-IP/per-account rate limiting — with no dependency on Unity, FishNet, or any game-engine type.
Subclasses provide transport-specific callbacks for broadcasting auth results, disconnecting connections, resolving IP addresses, and performing database operations.
public abstract class SrpAuthenticatorCore<TConnection> : BaseAuthenticatorCore<TConnection>
Type Parameters
TConnectionThe type representing a network connection.
- Inheritance
-
BaseAuthenticatorCore<TConnection>SrpAuthenticatorCore<TConnection>
- Inherited Members
Constructors
SrpAuthenticatorCore(ISrpAccountManager<TConnection>)
Initializes the SRP authenticator core.
protected SrpAuthenticatorCore(ISrpAccountManager<TConnection> accountManager)
Parameters
accountManagerISrpAccountManager<TConnection>SRP account manager instance.
Properties
AccountVerifyDebounceSeconds
Minimum seconds between account-verify debounce entries for the same identifier. Override to 0 in test subclasses to disable per-username rate limiting between sessions.
protected virtual float AccountVerifyDebounceSeconds { get; }
Property Value
IsWorkerIdle
Returns true when no async worker operations are in-flight. Subclasses with bounded-channel workers should override to check channel emptiness. Default returns true.
public override bool IsWorkerIdle { get; }
Property Value
LoginServerId
LoginServer database ID, embedded in issued tokens.
public long LoginServerId { get; set; }
Property Value
MaxConcurrentTotpVerifications
Default maximum number of TOTP code verifications running concurrently. Configurable via .cfg AuthMaxConcurrentTotpVerifications.
public int MaxConcurrentTotpVerifications { get; set; }
Property Value
MaxLoginFailuresPerUsername
Maximum SRP proof failures tracked per username before that username is locked out. Override to 0 in test subclasses to disable the lockout.
protected virtual int MaxLoginFailuresPerUsername { get; }
Property Value
Remarks
Higher than the TOTP threshold on purpose. A TOTP code is six digits read off a screen and typed immediately, so fifteen failures is already generous; a password is typed from memory by someone who may have several, and locking a legitimate owner out of their own account is itself a denial of service. Ten failures inside the window is well beyond ordinary mistyping and far below what guessing needs.
ProofChannelCapacity
Default maximum pending SRP proof requests in the bounded channel. Configurable via .cfg AuthSrpProofChannelCapacity.
public int ProofChannelCapacity { get; set; }
Property Value
ProofWorkerCount
Default number of concurrent SRP proof worker tasks. Configurable via .cfg AuthSrpProofWorkerCount.
public int ProofWorkerCount { get; set; }
Property Value
TokenExpirationMinutes
Token validity duration in minutes.
public float TokenExpirationMinutes { get; set; }
Property Value
TokenSigningKey
HMAC signing key for token generation. Set by the server system on startup. If null, token issuance is disabled.
public byte[]? TokenSigningKey { get; set; }
Property Value
- byte[]
TokenSigningKeyId
Database ID of the HMAC signing key used for token generation.
public long TokenSigningKeyId { get; set; }
Property Value
TotpMasterKey
AES-256 master key for decrypting TOTP secrets from the database during login. Must match the key used by AccountCreationSystem.
public byte[]? TotpMasterKey { get; set; }
Property Value
- byte[]
VerifyChannelCapacity
Default maximum pending SRP verify requests in the bounded channel. Configurable via .cfg AuthSrpVerifyChannelCapacity.
public int VerifyChannelCapacity { get; set; }
Property Value
VerifyWorkerCount
Default number of concurrent SRP verify worker tasks. Configurable via .cfg AuthSrpVerifyWorkerCount.
public int VerifyWorkerCount { get; set; }
Property Value
Methods
BroadcastAuthResult(TConnection, ClientAuthenticationResult, bool, int)
Broadcasts an auth result together with a retry-after hint. The default drops the hint; a transport whose result message can carry it overrides this.
protected virtual void BroadcastAuthResult(TConnection conn, ClientAuthenticationResult result, bool reliable, int retryAfterSeconds)
Parameters
connTConnectionresultClientAuthenticationResultreliableboolretryAfterSecondsint
BroadcastSrpSuccess(TConnection, byte[], ClientAuthenticationResult, byte[]?)
Broadcasts the SRP success response (encrypted server proof + result + optional token) to the client.
protected abstract void BroadcastSrpSuccess(TConnection conn, byte[] encryptedServerProof, ClientAuthenticationResult result, byte[]? encryptedToken)
Parameters
connTConnectionTarget connection.
encryptedServerProofbyte[]AES-GCM encrypted server proof bytes.
resultClientAuthenticationResultAuth result code accompanying the proof.
encryptedTokenbyte[]AES-GCM encrypted auth token, or
nullif login was not successful.
BroadcastSrpVerifyResponse(TConnection, byte[], byte[])
Broadcasts a generic auth result to the client.
protected abstract void BroadcastSrpVerifyResponse(TConnection conn, byte[] encryptedSalt, byte[] encryptedPublicServerEphemeral)
Parameters
connTConnectionTarget connection.
encryptedSaltbyte[]AES-GCM encrypted SRP salt.
encryptedPublicServerEphemeralbyte[]AES-GCM encrypted server public ephemeral.
CheckHasPendingKickAsync(string)
Checks whether a pending kick request exists for the given account name.
protected abstract Task<bool> CheckHasPendingKickAsync(string username)
Parameters
usernamestringAccount name to check.
Returns
CheckIsOnlineAsync(string)
Checks whether any character for the given account name is currently online.
protected abstract Task<bool> CheckIsOnlineAsync(string username)
Parameters
usernamestringAccount name to check.
Returns
CheckSignInAccessAsync(string, AccessLevel)
Decides whether a proven account may sign in at all — the closed-test (beta) gate. Called only after a correct SRP proof and after the unverified and banned checks.
protected virtual Task<ClientAuthenticationResult?> CheckSignInAccessAsync(string accountName, AccessLevel accessLevel)
Parameters
accountNamestringaccessLevelAccessLevel
Returns
- Task<ClientAuthenticationResult?>
Null to admit; otherwise the result to refuse with, normally BetaAccessRequired.
ClearLoginFailuresAsync(string)
Clears the shared password failure count after a correct proof. Default: no-op.
protected virtual Task ClearLoginFailuresAsync(string accountName)
Parameters
accountNamestring
Returns
ClearTwoFactorFailuresAsync(string)
Clears the shared two-factor failure count after a correct code. Default: no-op.
protected virtual Task ClearTwoFactorFailuresAsync(string accountName)
Parameters
accountNamestring
Returns
FetchAccountForLoginAsync(string, bool)
Fetches account data for SRP login (by username or email).
protected abstract Task<SrpAuthenticatorCore<TConnection>.SrpAccountLookupResult> FetchAccountForLoginAsync(string identifier, bool isEmail)
Parameters
Returns
- Task<SrpAuthenticatorCore<TConnection>.SrpAccountLookupResult>
An SrpAuthenticatorCore<TConnection>.SrpAccountLookupResult with account data if found.
GetTwoFactorLockedUntilAsync(string)
Until when the second step is locked, or null. Only consulted after a correct password, so the lock may be reported to the client. Default: never locked.
protected virtual Task<DateTime?> GetTwoFactorLockedUntilAsync(string accountName)
Parameters
accountNamestring
Returns
InitializeWorkersCore(CancellationToken)
Subclass-specific worker initialization: create channels and start worker tasks. Called after the base generates the cookie key.
protected override void InitializeWorkersCore(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenToken for signalling worker shutdown.
IsAllowedEmailUsername(string)
Validates an email-format username against the allowed email username rules.
Delegates to Authentication.IsAllowedEmailUsername (FishMMO-SharedUtility).
protected abstract bool IsAllowedEmailUsername(string username)
Parameters
usernamestringThe email address to validate.
Returns
- bool
trueif the email is a valid login identifier; otherwise,false.
IsAllowedUsername(string)
Validates a username against the allowed username rules.
Delegates to Authentication.IsAllowedUsername (FishMMO-SharedUtility).
protected abstract bool IsAllowedUsername(string username)
Parameters
usernamestringThe username string to validate.
Returns
- bool
trueif the username is allowed; otherwise,false.
IsConnectionActive(TConnection)
Returns whether a connection is currently active (connected and not disposed).
protected abstract bool IsConnectionActive(TConnection conn)
Parameters
connTConnectionThe connection to check.
Returns
- bool
trueif the connection is still active; otherwise,false.
IsLoginLockedAsync(string)
Whether password sign-in for the account is locked in shared storage. Checked before the SRP proof is evaluated; a locked account is refused exactly like a wrong password.
protected virtual Task<bool> IsLoginLockedAsync(string accountName)
Parameters
accountNamestring
Returns
Remarks
Default: never locked, so a subclass with no shared store (the unit-test harness) keeps the
in-memory lockout only. accountName is the canonical account name when the
account exists, and the identifier as typed when it does not — answer both identically.
OnAuthSweep()
Override for subclass-specific logic that runs alongside the stale-auth sweep.
protected override void OnAuthSweep()
OnAuthenticationResult(TConnection, bool)
Called when an authentication result (success or failure) must be reported for a connection. Implementations should call OnAuthenticationResult event, FishNet's PassAuthentication/FailAuthentication, etc.
protected abstract void OnAuthenticationResult(TConnection conn, bool authenticated)
Parameters
connTConnectionThe authenticated (or rejected) connection.
authenticatedboolTrue if authentication succeeded.
OnPurgeConnectionState(TConnection)
Override for subclass-specific cleanup during connection purge.
Called before AccountManager.RemoveConnectionAccount but after
ClearTransientAuthState(int) has removed TTL tracking.
protected override void OnPurgeConnectionState(TConnection conn)
Parameters
connTConnectionThe connection being purged.
OnSrpProofReceived(TConnection, byte[], uint)
Gate for an incoming SRP proof request. Validates connection state and enqueues for async processing. No decryption or SRP math occurs here.
public void OnSrpProofReceived(TConnection conn, byte[] encryptedProof, uint seq)
Parameters
connTConnectionThe network connection.
encryptedProofbyte[]Encrypted proof bytes.
sequintBroadcast sequence number.
OnSrpVerifyReceived(TConnection, byte[], byte[], uint)
Gate for an incoming SRP verify request. Validates connection state, applies rate limits, and enqueues for async processing. No decryption or database work occurs here.
public void OnSrpVerifyReceived(TConnection conn, byte[] encryptedUsername, byte[] encryptedPublicEphemeral, uint seq)
Parameters
connTConnectionThe network connection.
encryptedUsernamebyte[]Encrypted username bytes.
encryptedPublicEphemeralbyte[]Encrypted public ephemeral bytes.
sequintBroadcast sequence number.
OnTwoFactorVerifyReceived(TConnection, byte[], uint)
Gate for an incoming TOTP verification code. Validates state, applies rate limits, and dispatches async processing.
public void OnTwoFactorVerifyReceived(TConnection conn, byte[] encryptedCode, uint seq)
Parameters
connTConnectionThe network connection.
encryptedCodebyte[]Encrypted TOTP code bytes.
sequintBroadcast sequence number.
PersistKickRequestAsync(string)
Persists a kick request for the given account name to the database.
protected abstract Task PersistKickRequestAsync(string username)
Parameters
usernamestringAccount name to kick.
Returns
PersistTokenHashAsync(string, string, int)
Persists the hashed token for the given account to the database (for revocation tracking).
protected abstract Task<bool> PersistTokenHashAsync(string username, string tokenHash, int expirationMinutes)
Parameters
usernamestringAccount name.
tokenHashstringSHA-256 hex hash of the raw token.
expirationMinutesintToken validity duration.
Returns
- Task<bool>
True when the hash was recorded. False refuses the login with ServerBusy: a token whose hash is not in the database is treated as revoked by every world server.
RecordLoginFailureAsync(string)
Counts one failed SRP proof towards the shared lockout. Default: no-op.
protected virtual Task RecordLoginFailureAsync(string accountName)
Parameters
accountNamestring
Returns
RecordTwoFactorFailureAsync(string)
Counts one wrong authenticator or recovery code. Returns when the step is now locked until, or null when it is not locked. Default: no-op, never locks.
protected virtual Task<DateTime?> RecordTwoFactorFailureAsync(string accountName)
Parameters
accountNamestring
Returns
ResolveClientRealIp(TConnection)
Attempts to complete login and returns the final auth result.
Override to apply server-type-specific login logic (e.g., WorldServer player limit checks).
Default: returns defaultResult unchanged.
protected virtual string? ResolveClientRealIp(TConnection conn)
Parameters
connTConnection
Returns
- string
The final ClientAuthenticationResult to send to the client.
ShutdownWorkersCore()
Subclass-specific worker shutdown: complete channel writers, null channel references, and clear subclass-specific state. Called BEFORE the base zeroes the cookie key.
protected override void ShutdownWorkersCore()
TickRateLimits()
Sweeps the kick-request debounce and auth rate-limit trackers. Call from the hosting environment's per-tick update alongside Tick().
public void TickRateLimits()
TryIssueDiscordVerificationCodeAsync(string)
Called after a correct proof when the account chose Discord verification, Discord is switched on, and no Discord code has ever been issued — typically because the channel was switched on after the account registered. The implementation should issue the code, which queues its one DM.
protected virtual Task<bool> TryIssueDiscordVerificationCodeAsync(string username)
Parameters
usernamestringThe account username.
Returns
Remarks
Fire-and-forget like the resends, so it must not throw. Never a resend: a Discord code is issued once and its DM is sent once. Virtual with a no-op default.
TryLoginAsync(ClientAuthenticationResult, string)
Attempts to complete login authentication. Override in subclasses for server-type-specific logic (e.g., WorldServer checks player limit).
protected virtual Task<ClientAuthenticationResult> TryLoginAsync(ClientAuthenticationResult defaultResult, string username)
Parameters
defaultResultClientAuthenticationResultusernamestring
Returns
TryResendVerificationEmailIfExpiredAsync(string, DateTime?)
Called after a correct proof when an unverified account is owed an email code. The implementation should check whether the verification code has expired and, if so, generate a new code and enqueue a fresh verification email. No-op when the code is still valid.
protected abstract Task<bool> TryResendVerificationEmailIfExpiredAsync(string username, DateTime? verifyCodeExpiresUtc)
Parameters
usernamestringThe account username.
verifyCodeExpiresUtcDateTime?UTC expiry of the current code, or null.
Returns
TryResendVerificationSmsIfExpiredAsync(string, DateTime?)
The SMS twin of TryResendVerificationEmailIfExpiredAsync(string, DateTime?). Called after a correct proof when the account is owed an SMS code. The implementation should, when the SMS code is missing or expired, generate a new code, store it and enqueue a fresh message.
protected virtual Task<bool> TryResendVerificationSmsIfExpiredAsync(string username, DateTime? phoneVerifyCodeExpiresUtc)
Parameters
usernamestringThe account username.
phoneVerifyCodeExpiresUtcDateTime?UTC expiry of the current SMS code, or null when none was issued.
Returns
Remarks
Fire-and-forget: the caller does not await it, so an implementation must not throw. Virtual with a no-op default so a subclass without an SMS queue need not override it.
VerifyTotpCodeAsync(string, string, byte[])
Verifies a TOTP code for the given username against the database-stored secret.
protected abstract Task<SrpAuthenticatorCore<TConnection>.TwoFactorVerifyOutcome> VerifyTotpCodeAsync(string username, string totpCode, byte[] totpMasterKey)
Parameters
usernamestringAccount name.
totpCodestring6-digit TOTP code (plaintext).
totpMasterKeybyte[]AES-256 key for decrypting the stored TOTP secret.
Returns
- Task<SrpAuthenticatorCore<TConnection>.TwoFactorVerifyOutcome>
Valid or Invalid for a code that was checked; ServerError when it could not be checked, which is answered ServerBusy and never counted as a failed attempt.