Advanced Simulator Authority

Some games require enhanced security against cheating or player griefing. This is done by giving authoritative privileges to Simulators only.

Configuring for cloud-hosted Replication Server

In the Project Settings section of the Online Dashboard under Advanced Authority Config, you can select which Host Authority features are enabled for Rooms and Worlds separately, under Rooms Host Authority and Worlds Host Authority.

Configuring for local development

In the coherence project settings, under Local Replication Server, you can select which Host Authority features are enabled for a locally run Replication Server World. If you are manually launching the Replication Server from the CLI, the --host-authority-features parameter should be passed into the command with comma-separated dash-cased-enabled features names.

For example:

replication-server worlds --host-authority-features=create-entities,validate-connection

To select which Host Authority features are enabled for a locally run Room, you need to set SelfHostedRoomCreationOptions.HostAuthority at Room creation time.

Restricting Entity Creation

The HostAuthority.CreateEntities feature is used to only allow Simulators to create entities. Once created, these entities can have their state authority transferred and their lifetime managed by non-simulators, but no Client is allowed to create entities while this restriction is active.

With entity creation restriction enabled, the CoherenceSyncs that have the Simulate In option set to Client Side or Server Side With Client Input and are spawned by a Client will automatically get destroyed. The ones set to Server Side will just get disabled.

Simulator can still use any of the available options. Client Side works the same as Server Side and has no effect on the Simulator-side entities, while the Server Side With Client Input should be used together with CoherenceInput.

Disabling global query for Client connections on the Coherence Bridge

By default, when Client connections are active, the CoherenceBridge will automatically create a global query entity on behalf of the Client. If the Client is not authorized to create entities, this results in an error on the Replication Server indicating that an entity creation was rejected. To avoid these error logs, the auto creation of the global query can be disabled in the CoherenceBridge configuration:

Uncheck the Create Global Query option

A global query can be created manually as part of a prefab by using the CoherenceGlobalQuery component. This prefab can then be transferred to other clients from the simulator to give those clients access to the global client connections.

Validating Client Connections

The HostAuthority.ValidateConnection feature is used to restrict who can connect to a World or a Room. Upon enabling this feature, the connected Simulator will receive a validation request on every connection attempt from a Client. The connection is allowed only if the Simulator responds with the accepted validation response.

To handle the connection validation requests, the Simulator can subscribe to CoherenceBridge.onValidateConnectionRequest. To respond to the validation request, call Respond() on the ConnectionValidationRequest provided, passing in the validation response:

using Coherence.Brisk;
using Coherence.Toolkit;
using UnityEngine;

public class Example : MonoBehaviour
{
    public CoherenceBridge bridge;

    private void Awake()
    {
        bridge.onValidateConnectionRequest.AddListener(OnValidateConnectionRequest);
    }

    private void OnValidateConnectionRequest(ConnectionValidationRequest request)
    {
        // Your own validation logic goes here.
        var accept = true;

        // Call request.Respond() to accept or reject the connection.
        // This could be done later on (not on this frame), if needed.
        request.Respond(new ConnectionValidationResponse(accept));
    }
}

If the Simulator rejects the connection, the Client will receive a connection denied error with the ConnectionCloseReason.ConnectionRejectedByHost.

The response can be handled asynchronously by storing the request and calling the Respond() at a later time.

The validation is a subject to a 5-second timeout. If a connection is not validated within that time period it will be automatically rejected, resulting in the Client receiving a "Connection denied" error with theConnectionCloseReason.ConnectionValidationTimeout reason.

Custom user payload

Before initiating the connection, the user can set an optional custom user payload which will be sent to the Simulator for validation. The payload is of type byte[], and can contain an access token or any other data. To send the payload for validation, you must set it before initiating the connection:

bridge.SetConnectionValidationPayload(new CustomPayload(myToken));
bridge.JoinRoom(roomData); // or bridge.Connect(...);

Custom host payload

When responding to a connection validation request, the Simulator can also send a custom payload back to the user. This is done by passing the payload to the ConnectionValidationResponse when calling the Respond() method.

The Client can access the payload sent by the Simulator depending if the connection validation was accepted or rejected:

  • If the connection was accepted, the payload can be accessed by calling the CoherenceBridge function GetValidatedHostPayload() after the connection was established.

  • Or, if the connection was rejected, the payload is contained inside the connection denied error together with the ConnectionCloseReason.ConnectionRejectedByHost.

using Coherence.Brisk;
using Coherence.Common;
using Coherence.Connection;
using Coherence.Toolkit;
using UnityEngine;

[RequireComponent(typeof(CoherenceBridge))]
public class ConnectionValidationHandler : MonoBehaviour, IConnectionValidationHandler
{
    public string Password; // Set in the editor

    private void Start() {
        var bridge = GetComponent<CoherenceBridge>();
        bridge.ConnectionValidationHandler = this;

        bridge.onConnectionError.AddListener((_, exception) => {
            if (exception is ConnectionDeniedException deniedException)
            {
                Debug.Log("Connection denied. " +
                            $"Reason: {deniedException.CloseReason}, " +
                            $"Message: {deniedException.HostPayload.AsString}");
            }
        });
    }

    public void OnValidateConnectionRequest(ConnectionValidationRequest request) {
        if (request.UserPayload.AsString == Password) {
            request.Respond(new ConnectionValidationResponse(true));
        } else {
            var message = new CustomPayload("Invalid password");
            request.Respond(new ConnectionValidationResponse(false, message));
        }
    }
}

Kicking Client Connections

A Simulator can forcefully disconnect other Clients by kicking them. When kicking a Client, the Simulator can also send an optional host payload of type byte[] which will be sent to the kicked Client, together with the ConnectionCloseReason.KickedByHost.

// On simulator
var payload = new CustomPayload("Kicked for griefing.");
bridge.KickConnection(clientID, payload);

// On client
bridge.onConnectionError.AddListener((bridge, exception) =>
{
    if (exception is ConnectionDeniedException deniedException &&
        deniedException.CloseReason == ConnectionCloseReason.KickedByHost)
    {
        var message = deniedException.HostPayload.AsString;
        Debug.Log($"Kicked with message: {message}");
    }
});

Simulator payload

It is sometimes useful for the Client creating a room to pass information to the Simulator handling that room. If the information is public and can be seen by other Clients, using room Tags or a Key-Value dictionary is the best way to pass it.

If, however, the information is secret and should be known only to the Simulator, then we can use the Simulator Payload:

// On the client
var roomCreationOptions = new RoomCreationOptions {
    SimPayload = roomPassword,
};

var roomsService = PlayerAccount.Main.Services.Rooms;
roomsService
    .GetRoomServiceForRegion("eu")
    .CreateRoom(OnRoomCreated, roomCreationOptions);

// On the simulator
string password = SimulatorUtility.Payload;

This feature is also available for Worlds. The payload can be set via the dashboard, in the World configurator (Simulator configuration -> Optional simulator payload).

Known limitations

  • The Client Connections system is not fully operable when Entity creation restriction is enabled. While connections will be registered and their ClientIDs are available, the Client connection objects' state won't be synced and no commands can be sent for those objects. This applies only to the client-side connection objects. This limitation is slated to be removed in the future.

Last updated

Was this helpful?