Table of Contents

Class BaseAuthenticatorCore<TConnection>

Namespace
FishMMO.Auth.Implementation
Assembly
FishMMO-ServerAuth.dll

Abstract engine-independent base for all server authenticators. Provides X25519 ECDH handshake logic, stale-auth TTL sweeps, per-IP and global handshake rate limiting, and connection auth-state tracking — with no dependency on Unity, FishNet, or any game-engine type.

Concrete implementations supply transport-specific callbacks (broadcast, disconnect, IP resolution) by implementing the abstract members, then call OnHandshakeReceived(TConnection, byte[], byte[], string, ushort, ushort, string) from their transport layer.

public abstract class BaseAuthenticatorCore<TConnection>

Type Parameters

TConnection

The type representing a network connection.

Inheritance
BaseAuthenticatorCore<TConnection>
Derived
Inherited Members

Constructors

BaseAuthenticatorCore(IAccountManager<TConnection>)

Initializes the core with the required account manager.

protected BaseAuthenticatorCore(IAccountManager<TConnection> accountManager)

Parameters

accountManager IAccountManager<TConnection>

The account manager instance.

Fields

AuthHardDeadlineSeconds

Seconds into one authenticating phase after which RefreshAuthTtl(TConnection) no longer extends it, preventing unbounded TTL extension. See AuthenticatingCapSeconds.

protected const float AuthHardDeadlineSeconds = 60

Field Value

float

AuthStaleTtlSeconds

Seconds an authenticating connection may go without progress before it is purged. See ProgressTtlSeconds.

protected const float AuthStaleTtlSeconds = 15

Field Value

float

Remarks

Machine work only. A connection waiting on the player's two-factor code is bounded by TwoFactorWindowSeconds instead.

AuthSweepMaxRemovals

Maximum stale auth entries purged per sweep. The sweep runs every tick and only ever looks at the oldest entries, so this bounds one tick's disconnect work, not coverage: whatever is left is at the head for the next tick.

protected const int AuthSweepMaxRemovals = 64

Field Value

int

DefaultMaxPendingAuthConnections

public const int DefaultMaxPendingAuthConnections = 10000

Field Value

int

DefaultTwoFactorWindowSeconds

public const float DefaultTwoFactorWindowSeconds = 120

Field Value

float

HandshakeIpBurstLimit

Maximum Phase-2 handshake completions accepted from one IP inside HandshakeIpWindowSeconds. The old fixed 0.25 s debounce keyed the whole handshake round trip on one interval: any second completion inside the window — a player behind the same NAT as another, or a re-login whose connect+token+challenge cycle finishes faster than the window on a sub-10 ms link — was silently disconnected. A burst of 8 covers the legitimate worst case (a household logging in together, a fast reconnect loop) without meaningfully weakening the sustained per-IP throttle the limiter exists for.

protected const int HandshakeIpBurstLimit = 8

Field Value

int

HandshakeIpWindowSeconds

Duration of the per-IP Phase-2 handshake measurement window. Combined with HandshakeIpBurstLimit this sustains 4 completed handshakes/second/IP (unchanged from the previous single-deadline debounce) while allowing a burst of near-simultaneous completions from one IP.

protected const float HandshakeIpWindowSeconds = 2

Field Value

float

HandshakeRateLimitSweepMaxRemovals

Maximum closed windows removed per handshake rate-limit sweep.

protected const int HandshakeRateLimitSweepMaxRemovals = 2048

Field Value

int

MaxGlobalHandshakesPerSecond

Maximum X25519 handshakes accepted in a single 1-second window.

protected const int MaxGlobalHandshakesPerSecond = 500

Field Value

int

Properties

AccountManager

The account manager for this authenticator.

protected IAccountManager<TConnection> AccountManager { get; }

Property Value

IAccountManager<TConnection>

ExpectedGameVersion

Expected game version string (e.g. "0.1.0"). Set by the server host before connections are accepted. If null or empty, game version validation is skipped (development safety). When set, clients with a mismatched ClientHandshake.GameVersion are rejected with VersionMismatch.

public string ExpectedGameVersion { get; set; }

Property Value

string

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 virtual bool IsWorkerIdle { get; }

Property Value

bool

LogPrefix

Log source tag used in all log messages emitted by this core.

protected virtual string LogPrefix { get; }

Property Value

string

MaxPendingAuthConnections

Maximum number of connections allowed to be mid-authentication at once. A handshake that would exceed it is offered to OnHandshakeDeferred(TConnection) (the login queue) and dropped when that declines.

public int MaxPendingAuthConnections { get; set; }

Property Value

int

Remarks

Only connections still authenticating count; a player at the two-factor prompt does not, and the whole pending set, prompts included, is instead held to PendingCeilingMultiplier times this (see AdmitsNewPending(int, int, int)). Tracking ends when a connection authenticates (EndAuthTracking(TConnection)), is purged, or runs out of time. Set by the host from configuration before connections are accepted; values below 1 are raised to 1.

NowSeconds

The core's clock: seconds on this process's monotonic clock. Every duration the core times — the pending-authentication limits, the two-factor window, the rate limits and debounces — reads it here.

protected virtual double NowSeconds { get; }

Property Value

double

Remarks

Only differences between readings mean anything. Virtual so a test can move time forward past a two-factor window or a debounce without waiting for it; nothing else overrides it, and an override must never run backwards.

PendingAuthCount

Connections currently mid-authentication, awaiting a second factor included.

public int PendingAuthCount { get; }

Property Value

int

TwoFactorWindowSeconds

Seconds a player has to answer one two-factor prompt before the connection is dropped.

public float TwoFactorWindowSeconds { get; set; }

Property Value

float

Remarks

Every prompt gets the whole window: the first, and each re-prompt after a counted wrong code. Set by the host from configuration; values are brought into [MinTwoFactorWindowSeconds, MaxTwoFactorWindowSeconds] (see ClampTwoFactorWindow(double)). A change applies to prompts already on screen too.

Methods

BeginAwaitingTwoFactor(TConnection)

Puts a connection on the two-factor prompt: from now it has TwoFactorWindowSeconds to send a code, and nothing but a code starts the clock again.

protected void BeginAwaitingTwoFactor(TConnection conn)

Parameters

conn TConnection

The connection being prompted.

Remarks

Call immediately before sending the prompt — TwoFactorRequired, or a re-prompt after a counted attempt — so every prompt the player sees carries a full window. Does nothing for a connection no longer tracked; it is already being dropped.

BroadcastAuthResult(TConnection, ClientAuthenticationResult, bool)

Broadcasts an authentication result to a single connection.

protected abstract void BroadcastAuthResult(TConnection conn, ClientAuthenticationResult result, bool reliable)

Parameters

conn TConnection

Target connection.

result ClientAuthenticationResult

Auth result code.

reliable bool

True for reliable delivery, false for unreliable.

BroadcastCookieChallenge(TConnection, byte[])

Sends a cookie-challenge ServerHandshake response to the client. Called on the network-receive thread — must be non-blocking.

protected abstract void BroadcastCookieChallenge(TConnection conn, byte[] cookie)

Parameters

conn TConnection

The target connection.

cookie byte[]

The HMAC cookie to send.

BroadcastServerHandshake(TConnection, byte[], ushort)

Sends the final ServerHandshake response (with the server's X25519 public key) to complete ECDH key agreement. Called on the network-receive thread — must be non-blocking.

protected abstract void BroadcastServerHandshake(TConnection conn, byte[] serverPublicKey, ushort agreedVersion)

Parameters

conn TConnection

The target connection.

serverPublicKey byte[]

Server's ephemeral X25519 public key.

agreedVersion ushort

Negotiated protocol version.

ClearTransientAuthState(int)

Clears transient per-connection authenticator TTL tracking state.

protected void ClearTransientAuthState(int clientId)

Parameters

clientId int

Connection client ID.

DisconnectConnection(TConnection, bool)

Disconnects the specified connection.

protected abstract void DisconnectConnection(TConnection conn, bool graceful)

Parameters

conn TConnection

The connection to disconnect.

graceful bool

If true, attempt a graceful close; otherwise force-close immediately.

EndAuthTracking(TConnection)

Ends pending-authentication tracking for a connection that has just authenticated.

public void EndAuthTracking(TConnection conn)

Parameters

conn TConnection

The connection that authenticated.

Remarks

Called by the host when it applies a successful authentication result. Until this existed nothing ended tracking on success: every authenticated connection went on holding one of the MaxPendingAuthConnections slots until its TTL ran out, and the stale sweep then found it authenticated and logged it as a recycled connection — a warning for every successful sign-in that stayed connected for longer than AuthStaleTtlSeconds.

Removes only the entry that belongs to conn, so a late call for a connection whose client ID has since been recycled cannot end the new connection's tracking.

EnqueueMainThread(TConnection, Action)

Enqueues an action to be executed on the main/UI thread. Implementations using Unity must marshal all network API calls (Broadcast, Disconnect) via this method. Non-Unity implementations may execute immediately or use their own dispatcher.

protected abstract void EnqueueMainThread(TConnection conn, Action action)

Parameters

conn TConnection

The connection context (for lifetime checking).

action Action

The action to enqueue.

GetConnectionAddress(TConnection)

Returns the remote IP address (or equivalent string identifier) for the connection. Used for cookie challenge IP binding and rate limiting.

protected abstract string GetConnectionAddress(TConnection conn)

Parameters

conn TConnection

Returns

string

GetConnectionClientId(TConnection)

Returns the numeric client ID for the connection (e.g., FishNet ClientId). Used as the key for TTL tracking dictionaries.

protected abstract int GetConnectionClientId(TConnection conn)

Parameters

conn TConnection

Returns

int

HandleConnectionStopped(TConnection)

Called by the hosting transport layer when a connection has been disconnected. Purges all authenticator state for the connection without disconnecting (already stopped).

public void HandleConnectionStopped(TConnection conn)

Parameters

conn TConnection

The stopped connection.

InitializeWorkers(CancellationToken)

Generates a fresh cookie HMAC key and starts protocol-specific workers. Must be called before accepting connections.

public void InitializeWorkers(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Token for signalling graceful shutdown.

InitializeWorkersCore(CancellationToken)

Subclass-specific worker initialization: create channels and start worker tasks. Called after the base generates the cookie key.

protected abstract void InitializeWorkersCore(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Token for signalling worker shutdown.

IsAuthPending(TConnection)

Whether conn has completed its handshake and is still authenticating or awaiting its second factor — in the hands of this core's time limits.

public bool IsAuthPending(TConnection conn)

Parameters

conn TConnection

Returns

bool

IsConnectionAuthenticated(TConnection)

Returns whether this connection has already completed authentication. Called on the network-receive thread — must be thread-safe and non-blocking.

protected abstract bool IsConnectionAuthenticated(TConnection conn)

Parameters

conn TConnection

Returns

bool

OnAuthSweep()

Override for subclass-specific logic that runs alongside the stale-auth sweep.

protected virtual void OnAuthSweep()

OnHandshakeDeferred(TConnection)

Invoked when a handshake cannot be admitted because the pending authentication cap (MaxPendingAuthConnections) has been reached. Override to implement a login queue — return true if the connection was queued and should NOT be disconnected; return false (default) to drop the handshake.

protected virtual bool OnHandshakeDeferred(TConnection conn)

Parameters

conn TConnection

The connection that is being deferred.

Returns

bool

true if the connection was queued; false to reject.

OnHandshakeReceived(TConnection, byte[], byte[], string, ushort, ushort, string)

Processes an incoming client handshake. Must be called from the transport layer (e.g., on receipt of a ClientHandshakeBroadcast). Implements a two-phase stateless cookie challenge followed by X25519 ECDH key agreement. Runs with no blocking I/O — safe to call on a network-receive thread.

public bool OnHandshakeReceived(TConnection conn, byte[] publicKey, byte[] cookie, string connectionToken, ushort minVersion, ushort maxVersion, string gameVersion = "")

Parameters

conn TConnection

The network connection.

publicKey byte[]

Client's X25519 ephemeral public key (32 bytes). Must not be null.

cookie byte[]

Cookie echoed from a prior challenge, or null on first attempt.

connectionToken string
minVersion ushort

Minimum protocol version supported by the client.

maxVersion ushort

Maximum protocol version supported by the client.

gameVersion string

Returns

bool

true when this call completed the key agreement and the connection is now tracked as pending authentication; false for a cookie challenge, a refusal, a deferral to the login queue, or a duplicate.

Remarks

The return value is the hand-off between the host's handshake timeout and this core. A host bounds a new connection until its handshake completes; once this returns true the connection is tracked here as pending authentication and the limits in PendingAuthRules bound it, so the host must stop timing the handshake. Timing it on until authentication made the handshake timeout a limit on the whole sign-in, two-factor prompt included.

OnPurgeConnectionState(TConnection)

Override for subclass-specific cleanup during connection purge. Called before AccountManager.RemoveConnectionAccount but after ClearTransientAuthState(int) has removed TTL tracking.

protected virtual void OnPurgeConnectionState(TConnection conn)

Parameters

conn TConnection

The connection being purged.

OnTick()

Override for subclass-specific per-tick logic (e.g., additional periodic sweeps).

protected virtual void OnTick()

PurgeConnectionAuthState(TConnection, bool)

Purges all authenticator state for a connection and optionally disconnects it. TTL tracking is cleared before disconnect to prevent races.

protected void PurgeConnectionAuthState(TConnection conn, bool disconnect)

Parameters

conn TConnection

Connection to purge.

disconnect bool

If true, disconnect the client after purge.

RefreshAuthTtl(TConnection)

Records progress on an authenticating connection, restarting its AuthStaleTtlSeconds TTL. Call from async workers at meaningful progress points to prevent premature sweeping.

protected void RefreshAuthTtl(TConnection conn)

Parameters

conn TConnection

Connection whose TTL to refresh.

Remarks

Refused once the current authenticating phase has run for AuthHardDeadlineSeconds, and ignored while the connection is awaiting its second factor: that phase is bounded by TwoFactorWindowSeconds alone, and a verification of an earlier code finishing late must not take it off its window. Refreshes only a connection that is still tracked; it used to write the timestamp unconditionally, so a refresh landing after tracking had ended re-created an entry with no connection behind it.

ResolveRateLimitKey(TConnection)

Resolves a rate-limit key for a connection. Override to return a connection-ID string in proxy/NAT deployments where all clients share the same transport-level IP. Default: returns the normalized remote IP address.

protected virtual string ResolveRateLimitKey(TConnection conn)

Parameters

conn TConnection

The network connection.

Returns

string

A string key suitable for per-identity rate limiting.

ResumeAuthentication(TConnection)

Returns a connection to Authenticating with a fresh phase: the player's code has arrived and the servers are checking it, which is machine work again and bounded like it.

protected void ResumeAuthentication(TConnection conn)

Parameters

conn TConnection

The connection whose code is being checked.

ShutdownWorkers()

Gracefully shuts down all async workers and zeroes sensitive key material. Calls ShutdownWorkersCore() first to allow subclasses to complete channel writers for graceful worker exit.

public void ShutdownWorkers()

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 abstract void ShutdownWorkersCore()

Tick()

Runs the stale-auth TTL sweep and the handshake rate-limit sweep. Must be called periodically by the hosting environment (e.g., every server tick or Update frame).

public void Tick()

TrackAuthStart(TConnection)

Starts pending-authentication tracking for a connection whose handshake is completing, in Authenticating. A client ID already tracked is restarted. Returns false if the pending authentication cap has been reached.

protected bool TrackAuthStart(TConnection conn)

Parameters

conn TConnection

Connection entering the authentication flow.

Returns

bool

true if tracking was started; false if the cap was reached.

TryGetPendingAuthPhase(TConnection, out PendingAuthPhase)

The phase a connection's pending authentication is in, when it has completed its handshake and not yet authenticated.

public bool TryGetPendingAuthPhase(TConnection conn, out PendingAuthPhase phase)

Parameters

conn TConnection

The connection.

phase PendingAuthPhase

Its phase, when pending.

Returns

bool

true when conn is pending here.