XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

LumaTunnel

【WinUI】LumaTunnel 是一个面向个人多设备的 Windows 代理系统。客户端在本机提供 HTTP/HTTPS CONNECT 与 SOCKS5 TCP 代理,并通过一个受信任 TLS 证书保护的 WSS 会话,将多个 TCP 流复用到自建 Windows Server 节点。

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Collections.Concurrent;
using XFEExtension.NetCore.ServerInteractive.Implements.CoreService;

namespace LumaTunnel.Server.Core.Services;

public sealed class ApiRateLimitVerifyService : ServerCoreVerifyServiceBase
{
    private static readonly ConcurrentDictionary<string, Window> s_windows = new(StringComparer.Ordinal);

    public override async Task<bool> VerifyRequestAsync()
    {
        if (string.IsNullOrWhiteSpace(ClientIP))
            return await base.VerifyRequestAsync().ConfigureAwait(false);

        var now = DateTimeOffset.UtcNow;
        var window = s_windows.GetOrAdd(ClientIP, static _ => new Window());
        lock (window)
        {
            while (window.Requests.TryPeek(out var timestamp) && now - timestamp > TimeSpan.FromMinutes(1))
                window.Requests.TryDequeue(out _);

            if (window.BlockedUntil > now || window.Requests.Count >= 120)
            {
                window.BlockedUntil = now.AddMinutes(1);
                return false;
            }

            window.Requests.Enqueue(now);
        }

        return await base.VerifyRequestAsync().ConfigureAwait(false);
    }

    private sealed class Window
    {
        public ConcurrentQueue<DateTimeOffset> Requests { get; } = new();
        public DateTimeOffset BlockedUntil { get; set; }
    }
}