2026-10-23 18:20:04 +02:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
|
|
// Opening handshake validation per RFC 6455 section 4. Requires
|
|
|
|
|
// Upgrade/Connection headers and a 16-byte Sec-WebSocket-Key, picks
|
|
|
|
|
// at most one subprotocol, and builds the 101 response with the
|
|
|
|
|
// accept hash. Pure function of request plus config: no I/O.
|
|
|
|
|
|
|
|
|
|
#include <optional>
|
|
|
|
|
#include <string>
|
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
|
|
#include "realtime/shared/http_seam.h"
|
|
|
|
|
|
|
|
|
|
namespace molo::realtime::websocket::server {
|
|
|
|
|
|
|
|
|
|
struct HandshakeConfig {
|
|
|
|
|
// Subprotocols the server offers, in preference order. Empty
|
|
|
|
|
// means the server speaks no subprotocol: a request asking for
|
|
|
|
|
// one is still accepted when require_subprotocol is false, with
|
|
|
|
|
// no protocol echoed.
|
|
|
|
|
std::vector<std::string> subprotocols;
|
|
|
|
|
bool require_subprotocol = false;
|
2026-10-25 20:06:04 +01:00
|
|
|
|
|
|
|
|
// Exact-match allow-list for the browser-sent Origin header (CSWSH
|
|
|
|
|
// defense, CWE-1385). Empty means closed: any request that carries an
|
|
|
|
|
// Origin header is rejected, matching CorsPolicy's closed-by-default
|
|
|
|
|
// convention (src/security/guard/CorsPolicy.h). A request with no
|
|
|
|
|
// Origin header at all (non-browser clients) is not checked here.
|
|
|
|
|
std::vector<std::string> allowed_origins;
|
2026-10-23 18:20:04 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
struct HandshakeResult {
|
|
|
|
|
bool ok = false;
|
|
|
|
|
shared::HttpResponse response;
|
|
|
|
|
std::string accept_key;
|
|
|
|
|
std::string subprotocol;
|
|
|
|
|
std::string failure_reason;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
class HandshakeValidator {
|
|
|
|
|
public:
|
|
|
|
|
explicit HandshakeValidator(HandshakeConfig config = HandshakeConfig{});
|
|
|
|
|
|
|
|
|
|
HandshakeResult validate(const shared::HttpRequest& req) const;
|
|
|
|
|
|
|
|
|
|
// base64(SHA-1(key + GUID)) per RFC 6455 section 1.3.
|
|
|
|
|
static std::string accept_for(const std::string& key);
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
HandshakeConfig config_;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
} // namespace molo::realtime::websocket::server
|