Working on server side stuff
This commit is contained in:
1 parent
a784da9fb4
commit
542fc191fa
12 files changed
+756
-63
No files matched your search
@@ -426,6 +426,14 @@ Protocol v2 uses server-sequenced deterministic lockstep:
|
||||
- Post-tick canonical hashes exclude persistence timestamps and local
|
||||
presentation state. A mismatch is diagnosed but not automatically repaired.
|
||||
|
||||
Within one tick the server keeps only each player's last order (destination,
|
||||
`set_target`, or `clear_attack_target`); `applyScheduledCommand()` defines their
|
||||
semantics identically on the server and replicas. A stalled client freezes and
|
||||
then fast-forwards through all buffered contiguous ticks; any lost connection
|
||||
(including a clean close or rejection) returns the client to the main menu, and
|
||||
the server broadcasts a disable command for the departed player's character. See
|
||||
`WEBSOCKET_NETWORKING.md` for details.
|
||||
|
||||
No wall-clock timestamp participates in simulation. `steady_clock` paces the
|
||||
server and local render accumulator only, so different machine clocks do not
|
||||
affect command placement or state. The current missing-packet policy is to stall;
|
||||
|
||||
+71
-1
@@ -62,6 +62,75 @@ configured player slot connects or disconnects.
|
||||
locations against the replica and presents completed-tick events. It never
|
||||
advances simulation from a render-frame delta.
|
||||
|
||||
## Delayed Ticks and Connection Loss
|
||||
|
||||
- **Delay.** The client never advances simulation from wall-clock time. If tick N
|
||||
is missing it stalls: the world looks frozen, but input is still sent (the
|
||||
server schedules it two ticks after it arrives). When the missing ticks arrive
|
||||
the client applies all contiguous buffered ticks in one `update()` call, so
|
||||
the game visibly fast-forwards. There is no timeout or resynchronization.
|
||||
- **Connection lost.** `WebsocketGameClient::connectionFailed()` becomes true
|
||||
on any socket error, any close after connecting (including a clean server
|
||||
close), a `server_full`/`incompatible` rejection, or a compatibility
|
||||
fingerprint mismatch. `Game` then unloads the campaign and returns to the main
|
||||
menu / campaign selection (checked once loading has completed).
|
||||
- **Server side.** A read error, close, or write error releases the slot, closes
|
||||
the socket, and schedules `SetCharacterEnabledCommand(enabled=false)` for the
|
||||
next tick, which is broadcast so every replica disables that character.
|
||||
Inputs queued from a released slot in the same update are discarded.
|
||||
- There is no application-level heartbeat; a silently dead peer is detected by
|
||||
Beast's idle timeout.
|
||||
|
||||
## Message Signing and Rate Limiting
|
||||
|
||||
- **Session secret.** On connect the server generates 32 random bytes and sends
|
||||
them hex-encoded as `sessionSecret` in `initial_state`. The client must receive
|
||||
a valid 64-hex-character secret or the message is rejected.
|
||||
- **Per-message key.** `key = SHA-256(sessionSecret || appPepper || bigEndian(clientSequence))`.
|
||||
The pepper is rebuilt at run time from three masked fragments in separate
|
||||
functions (`MessageAuth.h`); it is never one contiguous constant. This raises
|
||||
the cost of extraction but cannot stop a determined reverse engineer, since the
|
||||
client must hold it. Change the fragments for each release if desired.
|
||||
- **Signature.** Every client input envelope carries `signature =
|
||||
hex(HMAC-SHA256(key, "type|clientSequence|payload"))`, where `payload` is the
|
||||
canonical JSON dump. `clientSequence` starts at 1 per connection and must
|
||||
strictly increase (replay protection).
|
||||
- **Validation order (server, per session, on the network thread).** rate limit,
|
||||
then signature, then sequence, then payload parsing.
|
||||
- **Rate limit.** More than `kMaxCommandsPerSecond` (20) messages inside a
|
||||
sliding one-second window counts every message, valid or not.
|
||||
- **Kick.** A rate-limit, signature or replay failure makes the server send a
|
||||
final `error` (`rate_limited`, `invalid_signature` or `replayed_message`),
|
||||
ignore the session, and close it. The slot is released and
|
||||
`SetCharacterEnabledCommand(enabled=false)` is broadcast like any disconnect.
|
||||
The client treats any error other than `invalid_input` as a lost connection and
|
||||
returns to the menu. A malformed but correctly signed payload only yields
|
||||
`invalid_input` and does not kick.
|
||||
- **Primitives.** SHA-256/HMAC are implemented in the header-only
|
||||
`src/game_server/MessageAuth.h`, because the standalone server and the web
|
||||
client do not link OpenSSL. It is checked against the standard test vectors.
|
||||
- **Limits.** Over plain `ws://` the secret travels in cleartext, so use `wss://`
|
||||
(the reverse proxy). Only client inputs are signed; the server's tick messages
|
||||
are not.
|
||||
|
||||
## Multiple Commands per Frame
|
||||
|
||||
A client may send several inputs in one frame; each is a separate message. The
|
||||
server keeps, per player and per scheduled tick, only the **last order**, where
|
||||
an order is `destination_input`, `set_target`, or `clear_attack_target`.
|
||||
`try_attack_combo` and presence commands are never dropped. Orders are applied
|
||||
by the shared `applyScheduledCommand()` (`LockstepApply.h`) on the server and on
|
||||
every replica:
|
||||
|
||||
- destination: clear the attack target, then walk to the point;
|
||||
- `set_target`: stop the current walk, then attack (the chase path is planned by
|
||||
the simulation);
|
||||
- `clear_attack_target`: clear the attack target only.
|
||||
|
||||
So "walk to A, then attack NPC 1" attacks, and "attack NPC 1, then walk to A"
|
||||
walks. The client therefore sends the destination before `set_target` when a
|
||||
hostile NPC is clicked, and no longer sends redundant trailing clears.
|
||||
|
||||
## Campaign Routing
|
||||
|
||||
The graphical game uses stable router objects for `IGameServer` and
|
||||
@@ -116,7 +185,8 @@ Message types are:
|
||||
- `tick` (server to client): tick ID, globally sequenced destination,
|
||||
character-action, and character-presence commands, and post-tick diagnostic
|
||||
state hash;
|
||||
- `error` (server to client): invalid input, incompatibility, or full server.
|
||||
- `error` (server to client): invalid input, incompatibility, full server, or a
|
||||
kick (`rate_limited`, `invalid_signature`, `replayed_message`).
|
||||
|
||||
Protocol v1 is not compatible. Malformed payloads, non-finite or out-of-range
|
||||
coordinates, duplicate client sequences, empty action IDs, and unsupported
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "game_server/NetworkProtocol.h"
|
||||
#include "game_server/MessageAuth.h"
|
||||
#include "LocationState.h"
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
@@ -41,6 +42,7 @@ int main()
|
||||
initial.assignedPlayerId = "player1";
|
||||
initial.snapshotTick = 42;
|
||||
initial.compatibilityFingerprint = "lockstep-v2:battle_zone_multiplayer";
|
||||
initial.sessionSecret = FRG::auth::generateSessionSecretHex();
|
||||
const std::string message = FRG::makeInitialStateMessage(initial);
|
||||
FRG::InitialStateMessage parsed;
|
||||
std::string error;
|
||||
@@ -48,6 +50,10 @@ int main()
|
||||
FRG::parseInitialStateMessage(message, parsed, error),
|
||||
"valid initial-state envelope was rejected");
|
||||
require(parsed.state == original, "state payload did not round trip");
|
||||
require(
|
||||
parsed.sessionSecret == initial.sessionSecret &&
|
||||
parsed.sessionSecret.size() == 64,
|
||||
"session secret did not round trip");
|
||||
require(parsed.snapshotTick == 42, "snapshot tick did not round trip");
|
||||
require(
|
||||
parsed.assignedPlayerId == "player1",
|
||||
@@ -189,5 +195,109 @@ int main()
|
||||
actionTick.commands[0]),
|
||||
"character action was not scheduled with input delay");
|
||||
|
||||
// Primitives against published test vectors.
|
||||
{
|
||||
const FRG::auth::Digest abc =
|
||||
FRG::auth::sha256(FRG::auth::toBytes("abc"));
|
||||
require(
|
||||
FRG::auth::hexEncode(abc.data(), abc.size()) ==
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
|
||||
"SHA-256 test vector failed");
|
||||
const FRG::auth::Digest mac = FRG::auth::hmacSha256(
|
||||
FRG::auth::Bytes(20, 0x0b), FRG::auth::toBytes("Hi There"));
|
||||
require(
|
||||
FRG::auth::hexEncode(mac.data(), mac.size()) ==
|
||||
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
|
||||
"HMAC-SHA256 RFC 4231 test vector failed");
|
||||
require(
|
||||
FRG::auth::generateSessionSecretHex() !=
|
||||
FRG::auth::generateSessionSecretHex(),
|
||||
"session secrets are not random");
|
||||
require(
|
||||
FRG::auth::deriveMessageKey({1}, FRG::auth::appPepper(), 1) !=
|
||||
FRG::auth::deriveMessageKey({1}, FRG::auth::appPepper(), 2),
|
||||
"message key does not depend on the sequence");
|
||||
}
|
||||
|
||||
// Signed input messages.
|
||||
{
|
||||
const std::string secret = FRG::auth::generateSessionSecretHex();
|
||||
const std::string otherSecret = FRG::auth::generateSessionSecretHex();
|
||||
const std::string signedMessage = FRG::signInputMessage(
|
||||
FRG::makeDestinationInputMessage({5, point(1.f, 0.f, 2.f)}), secret);
|
||||
std::uint64_t sequence = 0;
|
||||
std::string authError;
|
||||
require(
|
||||
FRG::verifyInputMessage(signedMessage, secret, sequence, authError) &&
|
||||
sequence == 5,
|
||||
"valid signature was rejected");
|
||||
FRG::DestinationInputMessage stillParses;
|
||||
require(
|
||||
FRG::parseDestinationInputMessage(signedMessage, stillParses, authError),
|
||||
"signed message no longer parses");
|
||||
require(
|
||||
!FRG::verifyInputMessage(signedMessage, otherSecret, sequence, authError),
|
||||
"signature verified under another session secret");
|
||||
require(
|
||||
!FRG::verifyInputMessage(
|
||||
FRG::makeDestinationInputMessage({5, point(1.f, 0.f, 2.f)}),
|
||||
secret, sequence, authError),
|
||||
"unsigned message was accepted");
|
||||
nlohmann::json tampered = nlohmann::json::parse(signedMessage);
|
||||
tampered["payload"]["target"][0] = 50.0;
|
||||
require(
|
||||
!FRG::verifyInputMessage(tampered.dump(), secret, sequence, authError),
|
||||
"tampered payload was accepted");
|
||||
nlohmann::json resequenced = nlohmann::json::parse(signedMessage);
|
||||
resequenced["payload"]["clientSequence"] = 6;
|
||||
require(
|
||||
!FRG::verifyInputMessage(resequenced.dump(), secret, sequence, authError),
|
||||
"re-sequenced message was accepted");
|
||||
const std::string action = FRG::signInputMessage(
|
||||
FRG::makeCharacterActionInputMessage({9, "set_target", "npc_1"}), secret);
|
||||
require(
|
||||
FRG::verifyInputMessage(action, secret, sequence, authError) &&
|
||||
sequence == 9,
|
||||
"signed character action was rejected");
|
||||
}
|
||||
|
||||
// Several orders in one frame: only the player's last order survives.
|
||||
FRG::LockstepTimeline burst(2);
|
||||
burst.schedule("player1", point(1.f, 0.f, 1.f));
|
||||
burst.scheduleCharacterAction("player1", "clear_attack_target");
|
||||
burst.scheduleCharacterAction("player1", "try_attack_combo");
|
||||
burst.schedule("player2", point(9.f, 0.f, 9.f));
|
||||
burst.scheduleCharacterAction("player1", "set_target", "npc_1");
|
||||
burst.advance();
|
||||
const FRG::TickMessage burstTick = burst.advance();
|
||||
require(
|
||||
burstTick.commands.size() == 3,
|
||||
"superseded orders were not coalesced");
|
||||
require(
|
||||
std::holds_alternative<FRG::ScheduledCharacterActionCommand>(
|
||||
burstTick.commands[0]) &&
|
||||
std::get<FRG::ScheduledCharacterActionCommand>(
|
||||
burstTick.commands[0]).action == "try_attack_combo",
|
||||
"combo was dropped or reordered");
|
||||
require(
|
||||
std::get<FRG::ScheduledDestinationCommand>(
|
||||
burstTick.commands[1]).playerId == "player2",
|
||||
"another player's order was coalesced away");
|
||||
require(
|
||||
std::get<FRG::ScheduledCharacterActionCommand>(
|
||||
burstTick.commands[2]).action == "set_target",
|
||||
"last order did not win");
|
||||
|
||||
FRG::LockstepTimeline reversed(2);
|
||||
reversed.scheduleCharacterAction("player1", "set_target", "npc_1");
|
||||
reversed.schedule("player1", point(3.f, 0.f, 3.f));
|
||||
reversed.advance();
|
||||
const FRG::TickMessage reversedTick = reversed.advance();
|
||||
require(
|
||||
reversedTick.commands.size() == 1 &&
|
||||
std::holds_alternative<FRG::ScheduledDestinationCommand>(
|
||||
reversedTick.commands[0]),
|
||||
"destination after attack did not replace the attack order");
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -341,5 +341,25 @@ int main()
|
||||
authoritative.snapshot()->players.at("player2").state.enabled,
|
||||
"reconnected player was not enabled");
|
||||
|
||||
// Flooding past the per-second command limit kicks the player.
|
||||
for (int i = 0; i < 40; ++i)
|
||||
replacement.submit(FRG::SetCharacterDestinationCommand{
|
||||
{}, {}, point(static_cast<float>(i), 0.f, 0.f), {}});
|
||||
require(
|
||||
waitFor([&]() {
|
||||
replacement.update(0);
|
||||
return replacement.connectionFailed();
|
||||
}),
|
||||
"command flood did not get the player kicked");
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
server.update();
|
||||
require(
|
||||
waitFor([&]() {
|
||||
client->update(0);
|
||||
return !client->snapshot()->players.at("player2").state.enabled;
|
||||
}) &&
|
||||
!authoritative.snapshot()->players.at("player2").state.enabled,
|
||||
"kicked player's character was not disabled for everyone");
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
+4
-5
@@ -2072,7 +2072,6 @@ namespace FRG
|
||||
: Vec3fp::fromEigen(clickedObject->state.position);
|
||||
setCharacterTarget(*player, interactionTarget);
|
||||
pathVisualization.start(*player, interactionTarget.toEigen());
|
||||
clearCharacterAttackTarget(*player);
|
||||
//logger() << "[CLICK] Player moving to object..." << std::endl;
|
||||
}
|
||||
else {
|
||||
@@ -2104,8 +2103,6 @@ namespace FRG
|
||||
tryCharacterAttackCombo(*player);
|
||||
}
|
||||
const std::string targetId = clickedNpc->entityId();
|
||||
gameServer_.submit(SetCharacterTargetCommand{
|
||||
locationId_, player->entityId(), targetId});
|
||||
gameServer_.submit(SetLocationTargetsCommand{
|
||||
locationId_, std::string(), std::string(), std::string()});
|
||||
|
||||
@@ -2116,6 +2113,10 @@ namespace FRG
|
||||
clickedNpcState->position.toEigen(),
|
||||
PathVisualization::Style::Hostile);
|
||||
}
|
||||
// Must follow any destination: in lockstep the last order of
|
||||
// a frame wins, and attacking must supersede the walk.
|
||||
gameServer_.submit(SetCharacterTargetCommand{
|
||||
locationId_, player->entityId(), targetId});
|
||||
|
||||
if (distance <= static_cast<float>(clickedNpcState->interactionRadius)) {
|
||||
//logger() << "[CLICK] Hostile NPC " << npcIndex << " in range; firing on_npc_interact" << std::endl;
|
||||
@@ -2173,12 +2174,10 @@ namespace FRG
|
||||
*player,
|
||||
clickedTeleport->position,
|
||||
PathVisualization::Style::Teleport);
|
||||
clearCharacterAttackTarget(*player);
|
||||
} else {
|
||||
const Eigen::Vector3f clickedDestination(hit.x(), 0.f, hit.z());
|
||||
setCharacterTarget(*player, Vec3fp::fromEigen(clickedDestination));
|
||||
pathVisualization.start(*player, clickedDestination);
|
||||
clearCharacterAttackTarget(*player);
|
||||
gameServer_.submit(SetLocationTargetsCommand{
|
||||
locationId_, std::string(), std::string(), std::string()});
|
||||
if (onPlayerFloorWalk) onPlayerFloorWalk();
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#include "IGameServer.h"
|
||||
#include "NetworkProtocol.h"
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
|
||||
namespace FRG {
|
||||
|
||||
// Applies one globally sequenced lockstep command. Shared by the server and
|
||||
// every replica so they cannot diverge.
|
||||
// - destination: cancels any attack target, then walks to the point;
|
||||
// - set_target: cancels the current walk, then attacks (update() plans the chase);
|
||||
// - clear_attack_target: clears the attack target only.
|
||||
inline void applyScheduledCommand(
|
||||
IGameServer& server, const std::string& locationId,
|
||||
const ScheduledCommand& scheduled)
|
||||
{
|
||||
std::visit([&](const auto& command) {
|
||||
using T = std::decay_t<decltype(command)>;
|
||||
if constexpr (std::is_same_v<T, ScheduledDestinationCommand>) {
|
||||
server.submit(ClearCharacterAttackTargetCommand{
|
||||
locationId, command.playerId});
|
||||
server.submit(SetCharacterDestinationCommand{
|
||||
locationId, command.playerId, command.target, {}});
|
||||
} else if constexpr (std::is_same_v<T, ScheduledCharacterEnabledCommand>) {
|
||||
server.submit(SetCharacterEnabledCommand{
|
||||
command.locationId, command.characterId, command.enabled});
|
||||
} else if (command.action == "set_target") {
|
||||
server.submit(StopCharacterCommand{locationId, command.playerId});
|
||||
server.submit(SetCharacterTargetCommand{
|
||||
locationId, command.playerId, command.targetId});
|
||||
} else if (command.action == "clear_attack_target") {
|
||||
server.submit(ClearCharacterAttackTargetCommand{
|
||||
locationId, command.playerId});
|
||||
} else if (command.action == "try_attack_combo") {
|
||||
server.submit(TryCharacterAttackComboCommand{
|
||||
locationId, command.playerId});
|
||||
}
|
||||
}, scheduled);
|
||||
}
|
||||
|
||||
} // namespace FRG
|
||||
@@ -0,0 +1,259 @@
|
||||
#pragma once
|
||||
|
||||
// Portable, dependency-free SHA-256 / HMAC-SHA256 and the helpers used to sign
|
||||
// client input messages. Header-only so every platform target (Windows, web,
|
||||
// standalone server) shares one implementation without OpenSSL.
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace FRG {
|
||||
namespace auth {
|
||||
|
||||
using Bytes = std::vector<std::uint8_t>;
|
||||
using Digest = std::array<std::uint8_t, 32>;
|
||||
|
||||
inline constexpr std::size_t kSessionSecretBytes = 32;
|
||||
|
||||
namespace detail {
|
||||
|
||||
inline std::uint32_t rotr(std::uint32_t value, unsigned count)
|
||||
{
|
||||
return (value >> count) | (value << (32u - count));
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
inline Digest sha256(const Bytes& data)
|
||||
{
|
||||
static const std::uint32_t k[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x7632ff20,
|
||||
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
||||
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
|
||||
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585,
|
||||
0x106aa070, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
||||
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
||||
0x609bbfa4, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x01010103, 0x391c0cb3, 0x4ed8aa4a,
|
||||
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
||||
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f1};
|
||||
std::uint32_t h[8] = {
|
||||
0x6a09e667, 0xb0fa3350, 0x3c6ef372, 0xa54ff53a,
|
||||
0x0010023f, 0x9b05688c, 0x1f83d9ab, 0xbe5f012a};
|
||||
|
||||
Bytes message = data;
|
||||
const std::uint64_t bitLength = static_cast<std::uint64_t>(data.size()) * 8u;
|
||||
message.push_back(0x80);
|
||||
while (message.size() % 64 != 56) message.push_back(0);
|
||||
for (int shift = 56; shift >= 0; shift -= 8)
|
||||
message.push_back(static_cast<std::uint8_t>(bitLength >> shift));
|
||||
|
||||
for (std::size_t offset = 0; offset < message.size(); offset += 64) {
|
||||
std::uint32_t w[64];
|
||||
for (std::size_t i = 0; i < 16; ++i) {
|
||||
const std::size_t at = offset + i * 4;
|
||||
w[i] = (static_cast<std::uint32_t>(message[at]) << 24) |
|
||||
(static_cast<std::uint32_t>(message[at + 1]) << 16) |
|
||||
(static_cast<std::uint32_t>(message[at + 2]) << 8) |
|
||||
static_cast<std::uint32_t>(message[at + 3]);
|
||||
}
|
||||
for (std::size_t i = 16; i < 64; ++i) {
|
||||
const std::uint32_t s0 = detail::rotr(w[i - 15], 7) ^
|
||||
detail::rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
const std::uint32_t s1 = detail::rotr(w[i - 2], 17) ^
|
||||
detail::rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3];
|
||||
std::uint32_t e = h[4], f = h[5], g = h[6], hh = h[7];
|
||||
for (std::size_t i = 0; i < 64; ++i) {
|
||||
const std::uint32_t s1 = detail::rotr(e, 6) ^ detail::rotr(e, 11) ^
|
||||
detail::rotr(e, 25);
|
||||
const std::uint32_t choose = (e & f) ^ (~e & g);
|
||||
const std::uint32_t t1 = hh + s1 + choose + k[i] + w[i];
|
||||
const std::uint32_t s0 = detail::rotr(a, 2) ^ detail::rotr(a, 13) ^
|
||||
detail::rotr(a, 22);
|
||||
const std::uint32_t majority = (a & b) ^ (a & c) ^ (b & c);
|
||||
const std::uint32_t t2 = s0 + majority;
|
||||
hh = g; g = f; f = e; e = d + t1;
|
||||
d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
|
||||
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
||||
}
|
||||
|
||||
Digest digest{};
|
||||
for (std::size_t i = 0; i < 8; ++i) {
|
||||
digest[i * 4] = static_cast<std::uint8_t>(h[i] >> 24);
|
||||
digest[i * 4 + 1] = static_cast<std::uint8_t>(h[i] >> 16);
|
||||
digest[i * 4 + 2] = static_cast<std::uint8_t>(h[i] >> 8);
|
||||
digest[i * 4 + 3] = static_cast<std::uint8_t>(h[i]);
|
||||
}
|
||||
return digest;
|
||||
}
|
||||
|
||||
inline Bytes toBytes(const std::string& text)
|
||||
{
|
||||
return Bytes(text.begin(), text.end());
|
||||
}
|
||||
|
||||
inline Digest hmacSha256(const Bytes& key, const Bytes& message)
|
||||
{
|
||||
Bytes block(64, 0);
|
||||
if (key.size() > 64) {
|
||||
const Digest hashed = sha256(key);
|
||||
std::copy(hashed.begin(), hashed.end(), block.begin());
|
||||
} else {
|
||||
std::copy(key.begin(), key.end(), block.begin());
|
||||
}
|
||||
Bytes inner(64), outer(64);
|
||||
for (std::size_t i = 0; i < 64; ++i) {
|
||||
inner[i] = block[i] ^ 0x36;
|
||||
outer[i] = block[i] ^ 0x5c;
|
||||
}
|
||||
inner.insert(inner.end(), message.begin(), message.end());
|
||||
const Digest innerDigest = sha256(inner);
|
||||
outer.insert(outer.end(), innerDigest.begin(), innerDigest.end());
|
||||
return sha256(outer);
|
||||
}
|
||||
|
||||
inline std::string hexEncode(const std::uint8_t* data, std::size_t size)
|
||||
{
|
||||
static const char digits[] = "0123456789abcdef";
|
||||
std::string result;
|
||||
result.reserve(size * 2);
|
||||
for (std::size_t i = 0; i < size; ++i) {
|
||||
result.push_back(digits[data[i] >> 4]);
|
||||
result.push_back(digits[data[i] & 0x0f]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
inline std::string hexEncode(const Bytes& bytes)
|
||||
{
|
||||
return hexEncode(bytes.data(), bytes.size());
|
||||
}
|
||||
|
||||
inline bool hexDecode(const std::string& text, Bytes& out)
|
||||
{
|
||||
if (text.size() % 2 != 0) return false;
|
||||
auto nibble = [](char c) -> int {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
};
|
||||
out.clear();
|
||||
out.reserve(text.size() / 2);
|
||||
for (std::size_t i = 0; i < text.size(); i += 2) {
|
||||
const int high = nibble(text[i]);
|
||||
const int low = nibble(text[i + 1]);
|
||||
if (high < 0 || low < 0) return false;
|
||||
out.push_back(static_cast<std::uint8_t>(high * 16 + low));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Compares in time independent of where the first difference occurs.
|
||||
inline bool constantTimeEquals(const std::string& left, const std::string& right)
|
||||
{
|
||||
if (left.size() != right.size()) return false;
|
||||
std::uint8_t difference = 0;
|
||||
for (std::size_t i = 0; i < left.size(); ++i)
|
||||
difference |= static_cast<std::uint8_t>(left[i] ^ right[i]);
|
||||
return difference == 0;
|
||||
}
|
||||
|
||||
// 32 bytes from the OS entropy source, hex encoded (64 characters).
|
||||
inline std::string generateSessionSecretHex()
|
||||
{
|
||||
std::random_device device;
|
||||
Bytes secret(kSessionSecretBytes);
|
||||
for (std::size_t i = 0; i < secret.size(); i += 4) {
|
||||
const std::uint32_t value = device();
|
||||
for (std::size_t j = 0; j < 4 && i + j < secret.size(); ++j)
|
||||
secret[i + j] = static_cast<std::uint8_t>(value >> (8 * j));
|
||||
}
|
||||
return hexEncode(secret);
|
||||
}
|
||||
|
||||
// ---- App pepper ----------------------------------------------------------
|
||||
// The pepper is never present as one contiguous constant: three masked
|
||||
// fragments live in separate functions and are recombined at run time. This
|
||||
// only raises the cost of extracting it from the binary; anything shipped to
|
||||
// the client can ultimately be recovered, so signatures deter casual
|
||||
// tampering and replay, not a determined reverse engineer.
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#define FRG_AUTH_NOINLINE __declspec(noinline)
|
||||
#else
|
||||
#define FRG_AUTH_NOINLINE __attribute__((noinline))
|
||||
#endif
|
||||
|
||||
namespace detail {
|
||||
|
||||
FRG_AUTH_NOINLINE inline Bytes ppc()
|
||||
{
|
||||
static const std::uint8_t masked[] = {0x6f, 0x5d, 0xe1, 0x07, 0x3b, 0xc4, 0x01, 0x1c, 0x92, 0x34, 0x12};
|
||||
Bytes out;
|
||||
for (std::size_t i = 0; i < sizeof(masked); ++i)
|
||||
out.push_back(static_cast<std::uint8_t>(masked[i] ^ (0x5a + i * 7)));
|
||||
return out;
|
||||
}
|
||||
|
||||
FRG_AUTH_NOINLINE inline Bytes ppb()
|
||||
{
|
||||
static const std::uint8_t masked[] = {0xbb, 0xfa, 0x84, 0x10, 0x6c, 0xa0, 0xd3, 0x48, 0x0e, 0xb0, 0x71};
|
||||
Bytes out;
|
||||
for (std::size_t i = 0; i < sizeof(masked); ++i)
|
||||
out.push_back(static_cast<std::uint8_t>(masked[i] ^ (0xc3 - i * 11)));
|
||||
return out;
|
||||
}
|
||||
|
||||
FRG_AUTH_NOINLINE inline Bytes ppa()
|
||||
{
|
||||
static const std::uint8_t masked[] = {0xc8, 0x09, 0x31, 0xf4, 0xf1, 0x80, 0xe5, 0x5b, 0x9d, 0x03};
|
||||
Bytes out;
|
||||
for (std::size_t i = 0; i < sizeof(masked); ++i)
|
||||
out.push_back(static_cast<std::uint8_t>(masked[i] ^ (0x19 + i * 13)));
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
inline Bytes appPepper()
|
||||
{
|
||||
Bytes a = detail::ppc();
|
||||
const Bytes b = detail::ppb();
|
||||
const Bytes c = detail::bba();
|
||||
// Interleave instead of concatenating so no fragment order is obvious.
|
||||
Bytes pepper;
|
||||
const std::size_t longest = (std::max)({a.size(), b.size(), c.size()});
|
||||
for (std::size_t i = 0; i < longest; ++i) {
|
||||
if (i < a.size()) pepper.push_back(a[i]);
|
||||
if (i < b.size()) pepper.push_back(b[i]);
|
||||
if (i < c.size()) pepper.push_back(c[i]);
|
||||
}
|
||||
return pepper;
|
||||
}
|
||||
|
||||
// key(seq) = SHA-256(sessionSecret || pepper || big-endian seq)
|
||||
inline Bytes deriveMessageKey(
|
||||
const Bytes& sessionSecret, const Bytes& pepper, std::uint64_t sequence)
|
||||
{
|
||||
Bytes material = sessionSecret;
|
||||
material.insert(material.end(), pepper.begin(), pepper.end());
|
||||
for (int shift = 56; shift >= 0; shift -= 8)
|
||||
material.push_back(static_cast<std::uint8_t>(sequence >> shift));
|
||||
const Digest key = sha256(material);
|
||||
return Bytes(key.begin(), key.end());
|
||||
}
|
||||
|
||||
} // namespace auth
|
||||
} // namespace FRG
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "NetworkProtocol.h"
|
||||
#include "MessageAuth.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <iomanip>
|
||||
@@ -165,10 +167,79 @@ std::string makeInitialStateMessage(const InitialStateMessage& message)
|
||||
{"snapshotTick", message.snapshotTick},
|
||||
{"tickMs", message.tickMs},
|
||||
{"inputDelayTicks", message.inputDelayTicks},
|
||||
{"compatibilityFingerprint", message.compatibilityFingerprint}
|
||||
{"compatibilityFingerprint", message.compatibilityFingerprint},
|
||||
{"sessionSecret", message.sessionSecret}
|
||||
});
|
||||
}
|
||||
|
||||
namespace {
|
||||
std::string signedText(
|
||||
const std::string& type, std::uint64_t sequence,
|
||||
const nlohmann::json& payload)
|
||||
{
|
||||
return type + "|" + std::to_string(sequence) + "|" + payload.dump();
|
||||
}
|
||||
|
||||
std::string computeSignature(
|
||||
const std::string& sessionSecretHex, std::uint64_t sequence,
|
||||
const std::string& text)
|
||||
{
|
||||
auth::Bytes secret;
|
||||
if (!auth::hexDecode(sessionSecretHex, secret) ||
|
||||
secret.size() != auth::kSessionSecretBytes)
|
||||
return {};
|
||||
const auth::Bytes key =
|
||||
auth::deriveMessageKey(secret, auth::appPepper(), sequence);
|
||||
const auth::Digest mac = auth::hmacSha256(key, auth::toBytes(text));
|
||||
return auth::hexEncode(mac.data(), mac.size());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string signInputMessage(
|
||||
const std::string& unsignedMessage, const std::string& sessionSecretHex)
|
||||
{
|
||||
nlohmann::json message = nlohmann::json::parse(unsignedMessage);
|
||||
const nlohmann::json& payload = message.at("payload");
|
||||
const std::uint64_t sequence = payload.at("clientSequence").get<std::uint64_t>();
|
||||
message["signature"] = computeSignature(
|
||||
sessionSecretHex, sequence,
|
||||
signedText(message.at("type").get<std::string>(), sequence, payload));
|
||||
return message.dump();
|
||||
}
|
||||
|
||||
bool verifyInputMessage(
|
||||
const std::string& text, const std::string& sessionSecretHex,
|
||||
std::uint64_t& clientSequence, std::string& error)
|
||||
{
|
||||
try {
|
||||
const nlohmann::json message = nlohmann::json::parse(text);
|
||||
if (!message.is_object() || !message.contains("payload") ||
|
||||
!message["payload"].is_object() || !message.contains("type") ||
|
||||
!message["type"].is_string() || !message.contains("signature") ||
|
||||
!message["signature"].is_string()) {
|
||||
error = "unsigned or malformed message";
|
||||
return false;
|
||||
}
|
||||
const nlohmann::json& payload = message["payload"];
|
||||
if (!readTick(payload, "clientSequence", clientSequence, error))
|
||||
return false;
|
||||
const std::string expected = computeSignature(
|
||||
sessionSecretHex, clientSequence,
|
||||
signedText(message["type"].get<std::string>(), clientSequence, payload));
|
||||
if (expected.empty() ||
|
||||
!auth::constantTimeEquals(
|
||||
expected, message["signature"].get<std::string>())) {
|
||||
error = "invalid signature";
|
||||
return false;
|
||||
}
|
||||
error.clear();
|
||||
return true;
|
||||
} catch (const std::exception& exception) {
|
||||
error = exception.what();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool parseInitialStateMessage(
|
||||
const std::string& text, InitialStateMessage& message, std::string& error)
|
||||
{
|
||||
@@ -191,6 +262,20 @@ bool parseInitialStateMessage(
|
||||
error = "unsupported lockstep timing";
|
||||
return false;
|
||||
}
|
||||
if (!payload.contains("sessionSecret") ||
|
||||
!payload["sessionSecret"].is_string()) {
|
||||
error = "initial state is missing the session secret";
|
||||
return false;
|
||||
}
|
||||
message.sessionSecret = payload["sessionSecret"].get<std::string>();
|
||||
{
|
||||
auth::Bytes decoded;
|
||||
if (!auth::hexDecode(message.sessionSecret, decoded) ||
|
||||
decoded.size() != auth::kSessionSecretBytes) {
|
||||
error = "invalid session secret";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
message.state = payload["state"];
|
||||
message.assignedPlayerId = payload["assignedPlayerId"].get<std::string>();
|
||||
message.compatibilityFingerprint =
|
||||
@@ -198,10 +283,37 @@ bool parseInitialStateMessage(
|
||||
return !message.assignedPlayerId.empty();
|
||||
}
|
||||
|
||||
namespace {
|
||||
bool isOrderCommand(const ScheduledCommand& command, const std::string& playerId)
|
||||
{
|
||||
if (const auto* destination = std::get_if<ScheduledDestinationCommand>(&command))
|
||||
return destination->playerId == playerId;
|
||||
if (const auto* action = std::get_if<ScheduledCharacterActionCommand>(&command))
|
||||
return action->playerId == playerId &&
|
||||
(action->action == "set_target" ||
|
||||
action->action == "clear_attack_target");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Within one tick only the player's last order (destination, set_target or
|
||||
// clear_attack_target) survives; combos and presence commands are untouched.
|
||||
void dropSupersededOrders(
|
||||
std::vector<ScheduledCommand>& commands, const std::string& playerId)
|
||||
{
|
||||
commands.erase(
|
||||
std::remove_if(commands.begin(), commands.end(),
|
||||
[&](const ScheduledCommand& command) {
|
||||
return isOrderCommand(command, playerId);
|
||||
}),
|
||||
commands.end());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::uint64_t LockstepTimeline::schedule(
|
||||
const std::string& playerId, const Vec3fp& target)
|
||||
{
|
||||
const std::uint64_t sequence = nextCommandSequence_++;
|
||||
dropSupersededOrders(pending_[currentTick_ + inputDelayTicks_], playerId);
|
||||
pending_[currentTick_ + inputDelayTicks_].push_back(
|
||||
ScheduledDestinationCommand{sequence, playerId, target});
|
||||
return sequence;
|
||||
@@ -222,6 +334,8 @@ std::uint64_t LockstepTimeline::scheduleCharacterAction(
|
||||
const std::string& playerId, std::string action, std::string targetId)
|
||||
{
|
||||
const std::uint64_t sequence = nextCommandSequence_++;
|
||||
if (action == "set_target" || action == "clear_attack_target")
|
||||
dropSupersededOrders(pending_[currentTick_ + inputDelayTicks_], playerId);
|
||||
pending_[currentTick_ + inputDelayTicks_].push_back(
|
||||
ScheduledCharacterActionCommand{
|
||||
sequence, playerId, std::move(action), std::move(targetId)});
|
||||
|
||||
@@ -22,8 +22,14 @@ struct InitialStateMessage {
|
||||
std::int64_t tickMs = kSimulationTickMs;
|
||||
std::uint32_t inputDelayTicks = kDefaultInputDelayTicks;
|
||||
std::string compatibilityFingerprint;
|
||||
// 32 random bytes (64 hex chars) issued per connection; used with the app
|
||||
// pepper to derive per-message HMAC keys.
|
||||
std::string sessionSecret;
|
||||
};
|
||||
|
||||
// Server-side limit on client messages; exceeding it gets the player kicked.
|
||||
inline constexpr std::size_t kMaxCommandsPerSecond = 20;
|
||||
|
||||
struct DestinationInputMessage {
|
||||
std::uint64_t clientSequence = 0;
|
||||
Vec3fp target;
|
||||
@@ -101,6 +107,18 @@ std::string makeCharacterActionInputMessage(
|
||||
bool parseCharacterActionInputMessage(
|
||||
const std::string& text, CharacterActionInputMessage& message,
|
||||
std::string& error);
|
||||
// Adds an HMAC-SHA256 "signature" to a client input envelope. The key is
|
||||
// SHA-256(sessionSecret || appPepper || clientSequence); the signed text is
|
||||
// "type|clientSequence|payload". Unsigned make*InputMessage output is what the
|
||||
// parse* functions consume, so signing is layered on top.
|
||||
std::string signInputMessage(
|
||||
const std::string& unsignedMessage, const std::string& sessionSecretHex);
|
||||
// Verifies the signature and extracts the clientSequence. Returns false (with
|
||||
// an error) for a missing/invalid signature or malformed envelope.
|
||||
bool verifyInputMessage(
|
||||
const std::string& text, const std::string& sessionSecretHex,
|
||||
std::uint64_t& clientSequence, std::string& error);
|
||||
|
||||
std::string makeTickMessage(const TickMessage& message);
|
||||
bool parseTickMessage(
|
||||
const std::string& text, TickMessage& message, std::string& error);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "WebsocketGameClient.h"
|
||||
#include "NetworkProtocol.h"
|
||||
#include "LockstepApply.h"
|
||||
#include "../utils/Utils.h"
|
||||
#ifdef __EMSCRIPTEN__
|
||||
#include <emscripten/websocket.h>
|
||||
@@ -408,8 +409,14 @@ private:
|
||||
buffer_,
|
||||
[this](beast::error_code error, std::size_t) {
|
||||
if (error) {
|
||||
// A clean close is also a lost connection for the game.
|
||||
if (error == websocket::error::closed) {
|
||||
connected_.store(false);
|
||||
if (error != websocket::error::closed) fail("read", error);
|
||||
connectionFailed_.store(true);
|
||||
std::cerr << "[network] Server closed the connection\n";
|
||||
} else {
|
||||
fail("read", error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
std::string message = beast::buffers_to_string(buffer_.data());
|
||||
@@ -497,18 +504,18 @@ void WebsocketGameClient::submit(const GameCommand& command)
|
||||
if (!initialized_) return;
|
||||
if (const auto* destination =
|
||||
std::get_if<SetCharacterDestinationCommand>(&command)) {
|
||||
impl_->send(makeDestinationInputMessage(
|
||||
{nextClientSequence_++, destination->target}));
|
||||
impl_->send(signInputMessage(makeDestinationInputMessage(
|
||||
{nextClientSequence_++, destination->target}), sessionSecret_));
|
||||
} else if (const auto* target =
|
||||
std::get_if<SetCharacterTargetCommand>(&command)) {
|
||||
impl_->send(makeCharacterActionInputMessage(
|
||||
{nextClientSequence_++, "set_target", target->targetId}));
|
||||
impl_->send(signInputMessage(makeCharacterActionInputMessage(
|
||||
{nextClientSequence_++, "set_target", target->targetId}), sessionSecret_));
|
||||
} else if (std::holds_alternative<ClearCharacterAttackTargetCommand>(command)) {
|
||||
impl_->send(makeCharacterActionInputMessage(
|
||||
{nextClientSequence_++, "clear_attack_target", {}}));
|
||||
impl_->send(signInputMessage(makeCharacterActionInputMessage(
|
||||
{nextClientSequence_++, "clear_attack_target", {}}), sessionSecret_));
|
||||
} else if (std::holds_alternative<TryCharacterAttackComboCommand>(command)) {
|
||||
impl_->send(makeCharacterActionInputMessage(
|
||||
{nextClientSequence_++, "try_attack_combo", {}}));
|
||||
impl_->send(signInputMessage(makeCharacterActionInputMessage(
|
||||
{nextClientSequence_++, "try_attack_combo", {}}), sessionSecret_));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,12 +540,15 @@ void WebsocketGameClient::update(std::int64_t)
|
||||
logger() << "[network] Incompatible server content: expected "
|
||||
<< expectedCompatibilityFingerprint_ << ", received "
|
||||
<< initial.compatibilityFingerprint << '\n';
|
||||
rejected_ = true;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
replica_.load(initial.state);
|
||||
replica_.setLocalPlayerId(initial.assignedPlayerId);
|
||||
nextExpectedTick_ = initial.snapshotTick + 1;
|
||||
sessionSecret_ = std::move(initial.sessionSecret);
|
||||
nextClientSequence_ = 1;
|
||||
compatibilityFingerprint_ =
|
||||
std::move(initial.compatibilityFingerprint);
|
||||
pendingTicks_.clear();
|
||||
@@ -570,8 +580,9 @@ void WebsocketGameClient::update(std::int64_t)
|
||||
if (parseErrorMessage(text, errorCode, errorDetail)) {
|
||||
logger() << "[network] Server rejected request (" << errorCode
|
||||
<< "): " << errorDetail << '\n';
|
||||
if (errorCode == "server_full" ||
|
||||
errorCode == "incompatible")
|
||||
// Everything except a recoverable malformed-input report ends the
|
||||
// session (server_full, incompatible, rate_limited, kicked, ...).
|
||||
if (errorCode != "invalid_input")
|
||||
rejected_ = true;
|
||||
continue;
|
||||
}
|
||||
@@ -587,25 +598,7 @@ void WebsocketGameClient::update(std::int64_t)
|
||||
const std::string locationId =
|
||||
replica_.snapshot()->currentLocationId;
|
||||
for (const ScheduledCommand& scheduled : tick.commands) {
|
||||
std::visit([&](const auto& command) {
|
||||
using T = std::decay_t<decltype(command)>;
|
||||
if constexpr (std::is_same_v<T, ScheduledDestinationCommand>) {
|
||||
replica_.submit(SetCharacterDestinationCommand{
|
||||
locationId, command.playerId, command.target, {}});
|
||||
} else if constexpr (std::is_same_v<T, ScheduledCharacterEnabledCommand>) {
|
||||
replica_.submit(SetCharacterEnabledCommand{
|
||||
command.locationId, command.characterId, command.enabled});
|
||||
} else if (command.action == "set_target") {
|
||||
replica_.submit(SetCharacterTargetCommand{
|
||||
locationId, command.playerId, command.targetId});
|
||||
} else if (command.action == "clear_attack_target") {
|
||||
replica_.submit(ClearCharacterAttackTargetCommand{
|
||||
locationId, command.playerId});
|
||||
} else if (command.action == "try_attack_combo") {
|
||||
replica_.submit(TryCharacterAttackComboCommand{
|
||||
locationId, command.playerId});
|
||||
}
|
||||
}, scheduled);
|
||||
applyScheduledCommand(replica_, locationId, scheduled);
|
||||
}
|
||||
replica_.update(kSimulationTickMs);
|
||||
completedSimulationTicks_.push_back({
|
||||
@@ -655,7 +648,8 @@ bool WebsocketGameClient::connected() const
|
||||
|
||||
bool WebsocketGameClient::connectionFailed() const
|
||||
{
|
||||
return impl_->connectionFailed();
|
||||
// Rejection (server full / incompatible content) is also a failed connection.
|
||||
return rejected_ || impl_->connectionFailed();
|
||||
}
|
||||
|
||||
} // namespace FRG
|
||||
@@ -68,6 +68,7 @@ private:
|
||||
std::uint64_t nextExpectedTick_ = 0;
|
||||
std::uint64_t nextClientSequence_ = 1;
|
||||
std::string compatibilityFingerprint_;
|
||||
std::string sessionSecret_;
|
||||
std::string expectedCompatibilityFingerprint_;
|
||||
bool initialized_ = false;
|
||||
bool rejected_ = false;
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
#include "WebsocketGameServer.h"
|
||||
#include "InternalGameServer.h"
|
||||
#include "NetworkProtocol.h"
|
||||
#include "LockstepApply.h"
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/beast.hpp>
|
||||
#include "MessageAuth.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
@@ -30,16 +33,53 @@ public:
|
||||
std::function<void(const std::shared_ptr<ServerSession>&)>;
|
||||
|
||||
ServerSession(
|
||||
tcp::socket socket, std::string playerId,
|
||||
tcp::socket socket, std::string playerId, std::string sessionSecret,
|
||||
InputHandler inputHandler, CloseHandler closeHandler)
|
||||
: socket_(std::move(socket))
|
||||
, playerId_(std::move(playerId))
|
||||
, sessionSecret_(std::move(sessionSecret))
|
||||
, inputHandler_(std::move(inputHandler))
|
||||
, closeHandler_(std::move(closeHandler))
|
||||
{
|
||||
}
|
||||
|
||||
const std::string& playerId() const { return playerId_; }
|
||||
const std::string& sessionSecret() const { return sessionSecret_; }
|
||||
bool kicked() const { return kicked_; }
|
||||
|
||||
// Counts one received message in a sliding one-second window. Returns false
|
||||
// once the player exceeds kMaxCommandsPerSecond.
|
||||
bool allowMessage()
|
||||
{
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
while (!recentMessages_.empty() &&
|
||||
now - recentMessages_.front() > std::chrono::seconds(1))
|
||||
recentMessages_.pop_front();
|
||||
recentMessages_.push_back(now);
|
||||
return recentMessages_.size() <= kMaxCommandsPerSecond;
|
||||
}
|
||||
|
||||
// Accepts only strictly increasing sequence numbers (replay protection).
|
||||
bool acceptSequence(std::uint64_t sequence)
|
||||
{
|
||||
if (sequence <= lastSequence_) return false;
|
||||
lastSequence_ = sequence;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Sends a final error, ignores all further input and ticks, then closes.
|
||||
// Closing releases the slot, so the character is disabled for everyone.
|
||||
void kick(const std::string& code, const std::string& detail)
|
||||
{
|
||||
if (kicked_ || closed_) return;
|
||||
kicked_ = true;
|
||||
std::cout << "[network] Kicking player slot '" << playerId_ << "' ("
|
||||
<< code << "): " << detail << std::endl;
|
||||
closeAfterWrite_ = true;
|
||||
const bool writeInProgress = !outbound_.empty();
|
||||
outbound_.push_back(makeErrorMessage(code, detail));
|
||||
if (!writeInProgress) write();
|
||||
}
|
||||
|
||||
void start(std::string initialState, bool closeAfterWrite = false)
|
||||
{
|
||||
@@ -62,6 +102,7 @@ public:
|
||||
|
||||
void send(std::string message)
|
||||
{
|
||||
if (closed_ || kicked_) return;
|
||||
const bool writeInProgress = !outbound_.empty();
|
||||
outbound_.push_back(std::move(message));
|
||||
if (!writeInProgress) write();
|
||||
@@ -83,7 +124,9 @@ private:
|
||||
const std::string message =
|
||||
beast::buffers_to_string(self->inbound_.data());
|
||||
self->inbound_.consume(self->inbound_.size());
|
||||
if (self->kicked_) return;
|
||||
self->inputHandler_(self, message);
|
||||
if (self->kicked_) return;
|
||||
self->read();
|
||||
});
|
||||
}
|
||||
@@ -96,6 +139,11 @@ private:
|
||||
if (error) {
|
||||
std::cerr << "[network] WebSocket write failed: "
|
||||
<< error.message() << '\n';
|
||||
// Release the slot and stop queueing ticks for a dead peer.
|
||||
self->outbound_.clear();
|
||||
beast::error_code ignored;
|
||||
beast::get_lowest_layer(self->socket_).close(ignored);
|
||||
self->notifyClosed();
|
||||
return;
|
||||
}
|
||||
self->outbound_.pop_front();
|
||||
@@ -120,10 +168,14 @@ private:
|
||||
beast::flat_buffer inbound_;
|
||||
std::deque<std::string> outbound_;
|
||||
std::string playerId_;
|
||||
std::string sessionSecret_;
|
||||
std::deque<std::chrono::steady_clock::time_point> recentMessages_;
|
||||
std::uint64_t lastSequence_ = 0;
|
||||
InputHandler inputHandler_;
|
||||
CloseHandler closeHandler_;
|
||||
bool closeAfterWrite_ = false;
|
||||
bool closed_ = false;
|
||||
bool kicked_ = false;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
@@ -224,11 +276,30 @@ private:
|
||||
break;
|
||||
}
|
||||
}
|
||||
const std::string sessionSecret = auth::generateSessionSecretHex();
|
||||
auto session =
|
||||
std::make_shared<ServerSession>(
|
||||
std::move(socket), playerId,
|
||||
std::move(socket), playerId, sessionSecret,
|
||||
[this](const std::shared_ptr<ServerSession>& source,
|
||||
const std::string& message) {
|
||||
if (!source->allowMessage()) {
|
||||
source->kick("rate_limited",
|
||||
"Too many commands per second");
|
||||
return;
|
||||
}
|
||||
std::uint64_t signedSequence = 0;
|
||||
std::string authError;
|
||||
if (!verifyInputMessage(
|
||||
message, source->sessionSecret(),
|
||||
signedSequence, authError)) {
|
||||
source->kick("invalid_signature", authError);
|
||||
return;
|
||||
}
|
||||
if (!source->acceptSequence(signedSequence)) {
|
||||
source->kick("replayed_message",
|
||||
"Message sequence did not increase");
|
||||
return;
|
||||
}
|
||||
DestinationInputMessage destination;
|
||||
std::string destinationError;
|
||||
if (parseDestinationInputMessage(
|
||||
@@ -283,6 +354,7 @@ private:
|
||||
initial.snapshotTick = latestTick_;
|
||||
initial.compatibilityFingerprint =
|
||||
compatibilityFingerprint_;
|
||||
initial.sessionSecret = sessionSecret;
|
||||
session->start(makeInitialStateMessage(initial));
|
||||
std::cout << "[network] Initial state queued for player '"
|
||||
<< playerId << "'" << std::endl;
|
||||
@@ -341,6 +413,11 @@ void WebsocketGameServer::update()
|
||||
lastClientSequences_.erase(playerId);
|
||||
for (const Impl::PendingInput& pending : impl_->takeInputs()) {
|
||||
std::uint64_t& previous = lastClientSequences_[pending.playerId];
|
||||
// Input queued before the slot was released must not reach a disabled
|
||||
// character.
|
||||
if (std::find(releasedPlayers.begin(), releasedPlayers.end(),
|
||||
pending.playerId) != releasedPlayers.end())
|
||||
continue;
|
||||
const std::uint64_t sequence = std::visit(
|
||||
[](const auto& input) { return input.clientSequence; },
|
||||
pending.input);
|
||||
@@ -359,29 +436,8 @@ void WebsocketGameServer::update()
|
||||
|
||||
TickMessage tick = timeline_.advance();
|
||||
for (const ScheduledCommand& scheduled : tick.commands) {
|
||||
std::visit([this](const auto& command) {
|
||||
using T = std::decay_t<decltype(command)>;
|
||||
if constexpr (std::is_same_v<T, ScheduledDestinationCommand>) {
|
||||
gameServer_.submit(SetCharacterDestinationCommand{
|
||||
gameServer_.snapshot()->currentLocationId,
|
||||
command.playerId, command.target, {}});
|
||||
} else if constexpr (std::is_same_v<T, ScheduledCharacterEnabledCommand>) {
|
||||
gameServer_.submit(SetCharacterEnabledCommand{
|
||||
command.locationId, command.characterId, command.enabled});
|
||||
} else if (command.action == "set_target") {
|
||||
gameServer_.submit(SetCharacterTargetCommand{
|
||||
gameServer_.snapshot()->currentLocationId,
|
||||
command.playerId, command.targetId});
|
||||
} else if (command.action == "clear_attack_target") {
|
||||
gameServer_.submit(ClearCharacterAttackTargetCommand{
|
||||
gameServer_.snapshot()->currentLocationId,
|
||||
command.playerId});
|
||||
} else if (command.action == "try_attack_combo") {
|
||||
gameServer_.submit(TryCharacterAttackComboCommand{
|
||||
gameServer_.snapshot()->currentLocationId,
|
||||
command.playerId});
|
||||
}
|
||||
}, scheduled);
|
||||
applyScheduledCommand(
|
||||
gameServer_, gameServer_.snapshot()->currentLocationId, scheduled);
|
||||
}
|
||||
gameServer_.update(kSimulationTickMs);
|
||||
nlohmann::json state;
|
||||
|
||||
Reference in new issue
Block a user