# Advanced Simulator Authority

Some games require enhanced security against cheating or player griefing. This is done by giving authoritative privileges to [Simulators](https://docs.coherence.io/1.7/manual/simulation-server) only.

{% hint style="warning" %}
Advanced Simulator Authority is a specific feature set meant for advanced use cases. Most projects should consider simpler setups first, like [distributed authority](https://docs.coherence.io/1.7/authority#distributed-client-authority) or simple [server-authoritative](https://docs.coherence.io/1.7/manual/authority/server-authoritative-setup). This approach adds complexity, especially around object creation and error handling.
{% endhint %}

### Configuring for cloud-hosted Replication Server

In the **Project Settings** section of the [Online Dashboard](https://docs.coherence.io/1.7/hosting/coherence-cloud/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](https://docs.coherence.io/1.7/manual/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.

{% hint style="warning" %}
If any host authority feature is enabled, the Replication Server will not allow Clients to be connected without a Simulator being connected as well.

If a Client tries to connect before a Simulator, the connection will be denied with the `ConnectionCloseReason.HostNotReady`.

If a Simulator disconnects, while other Clients are connected to the server, the Replication Server will forcefully disconnect all other Clients as well with the `ConnectionCloseReason.HostDisconnected`.
{% endhint %}

## 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.

{% hint style="warning" %}
By default, all CoherenceSyncs have [AuthorityTransferType](https://docs.coherence.io/1.7/authority/authority-transfer#types-of-authority-transfer) set to "Steal". This means that malicious players could steal the authority of any entity and break the game.&#x20;

Instead of manually changing the AuthorityTransferType on every new CoherenceSync, you can change the default value of it in the **coherence** [project settings](https://docs.coherence.io/1.7/manual/project-settings). See [Types of authority transfer](https://docs.coherence.io/1.7/authority/authority-transfer#types-of-authority-transfer).
{% endhint %}

{% hint style="info" %}
With entity creation restriction enabled, the CoherenceSyncs that have the [Simulate In](https://docs.coherence.io/1.7/components/coherence-sync#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](https://docs.coherence.io/1.7/manual/components/coherenceinput).
{% endhint %}

### Disabling global query for Client connections on the Coherence Bridge

By default, when [Client connections](https://docs.coherence.io/1.7/manual/client-connections) are active, the [CoherenceBridge](https://docs.coherence.io/1.7/manual/components/coherence-bridge) 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:

<figure><img src="https://2400155846-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNGFZGdbLA4bzHQXTuDMT%2Fuploads%2Fd6yFcnthb0QLyPOziV1a%2Fimage_2025-04-25_122147030.png?alt=media&#x26;token=0abb2328-d25b-430b-9283-4bc1e7c68546" alt=""><figcaption><p>Uncheck the Create Global Query option</p></figcaption></figure>

[A global query can be created manually](https://docs.coherence.io/1.7/manual/simulation-server/advanced-simulator-authority/simulator-query-transfer) as part of a prefab by using the[ CoherenceGlobalQuery](https://docs.coherence.io/1.7/manual/components/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:

```csharp
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](https://docs.coherence.io/1.7/components/coherence-bridge#onconnectionerror) with the `ConnectionCloseReason.ConnectionRejectedByHost`.

{% hint style="info" %}
The response can be handled asynchronously by storing the `request` and calling the `Respond()` at a later time.&#x20;

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 the`ConnectionCloseReason.ConnectionValidationTimeout` reason.
{% endhint %}

### 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:

```csharp
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.

{% hint style="warning" %}
The payload size is limited to 512 bytes.
{% endhint %}

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](https://docs.coherence.io/1.7/manual/components/coherence-bridge) function `GetValidatedHostPayload()` after the connection was established.
* Or, if the connection was rejected, the payload is contained inside the [connection denied error](https://docs.coherence.io/1.7/components/coherence-bridge#onconnectionerror) together with the `ConnectionCloseReason.ConnectionRejectedByHost`.

```csharp
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`.

```csharp
// 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**:

```csharp
// 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;
```

{% hint style="info" %}
This feature is also available for Worlds. The payload can be set via the [dashboard](https://docs.coherence.io/1.7/hosting/coherence-cloud/online-dashboard), in the **World configurator** (**Simulator configuration -> Optional simulator payload**).
{% endhint %}

## Known limitations

* The [Client Connections](https://docs.coherence.io/1.7/manual/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.
