#pragma once #include #include #include #include #include #include #include #include #include #include #include namespace Echoion::Web::Security { namespace asio = boost::asio; class CidrBlock { public: CidrBlock(asio::ip::address network, unsigned int prefixLength); [[nodiscard]] bool contains( const asio::ip::address& address) const noexcept; private: asio::ip::address network_; unsigned int prefixLength_ = 0; }; using ParsedCidrs = std::expected, std::string>; [[nodiscard]] ParsedCidrs parseTrustedProxyCidrs( std::span cidrs); [[nodiscard]] std::string effectiveClientAddress( const asio::ip::address& immediatePeer, std::optional forwardedFor, std::span trustedProxies); [[nodiscard]] bool validShortSlug(std::string_view slug) noexcept; [[nodiscard]] bool validRedirectLocation(std::string_view location) noexcept; class ShortLinkRateLimiter { public: using Clock = std::chrono::steady_clock; using TimePoint = Clock::time_point; struct Config { double globalRate = 200.0; double globalBurst = 400.0; double peerRate = 10.0; double peerBurst = 20.0; std::size_t maxPeers = 4096; Clock::duration idleTimeout = std::chrono::minutes(10); Clock::duration sweepInterval = std::chrono::minutes(1); }; ShortLinkRateLimiter(); explicit ShortLinkRateLimiter(Config config); [[nodiscard]] bool allow(std::string_view peer); [[nodiscard]] bool allow(std::string_view peer, TimePoint now); void reset(); [[nodiscard]] std::size_t trackedPeerCount() const; private: struct TokenBucket { double tokens = 0.0; TimePoint updated{}; bool initialized = false; }; struct PeerBucket { TokenBucket bucket; TimePoint lastSeen{}; }; static void refill(TokenBucket& bucket, double rate, double burst, TimePoint now) noexcept; void evictIdle(TimePoint now, bool force); Config config_; mutable std::mutex mutex_; TokenBucket global_; std::unordered_map peers_; TimePoint nextSweep_{}; bool sweepInitialized_ = false; }; } // namespace Echoion::Web::Security